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
60a49d6486090eb1972efa89cf7e171e87fc7c49
blocks.lua
blocks.lua
local M = {} local io=require"io" local table=require"table" local crypto=require"crypto" local lfs=require"lfs" local dir=require"pl.dir" local plpath=require"pl.path" local class=require"pl.class" M.BLOCKSIZE=8192 function M.bintohex(s) return (s:gsub('(.)', function(c) return string.format('%02x', string.byte(c)) end)) end -- Start a weak checksum on a block of data -- Good for a rolling checksum function M.start_cksum(data) local a = 0 local b = 0 local l = data:len() local x for i = 1, l do x = data:byte(i) a = a + x b = b + (l - i) * x end return a, b end -- Complete weak checksum on a smallish block function M.weak_cksum(data) local a, b = M.start_cksum(data) return (b * 65536) + a end -- Roll checksum byte-by-byte function M.roll_cksum(removed_byte, added_byte, a, b) a = a - (removed_byte - added_byte) b = b - ((removed_byte * M.BLOCKSIZE) - a) return a, b end function M.strong_cksum(data) return crypto.evp.digest("sha1", data) end M.FileIndex = class() function M.FileIndex:_init(path) self.path = path self.strong = nil self.blocks = {} end function M.get_file_index(path) local index = M.FileIndex(path) local f = io.open(path, "r") local block_num = 1 local buf local hash = crypto.evp.new("sha1") while true do buf = f:read(M.BLOCKSIZE) if not buf then break end index.blocks[block_num] = {weak=M.weak_cksum(buf), strong=M.strong_cksum(buf)} hash:update(buf) block_num = block_num + 1 end io.close(f) index.strong = hash:digest() return index end function M.get_file_block(path, block_nums) local result = {} local f = io.open(path, "r") for block_num in pairs(block_nums) do f:seek(block_num * M.BLOCKSIZE) result[block_num] = f:read(M.BLOCKSIZE) end return result end M.DirIndex = class() function M.DirIndex:_init(path) self.path = path self.dirs = {} self.files = {} self.strong = nil end function M.get_dir_index(path) local root_index = M.DirIndex(path) local dir_index_map = {} dir_index_map[path]=root_index local dir_index = nil for root, subdirs, files in dir.walk(path) do dir_index = dir_index_map[root] local fpath for i, f in pairs(files) do fpath = plpath.join(root, f) table.insert(dir_index.files, M.get_file_index(fpath)) end local dpath local sub_index for i, d in pairs(subdirs) do dpath = plpath.join(root, d) sub_index = M.DirIndex(dpath) dir_index_map[dpath] = sub_index table.insert(dir_index.dirs, sub_index) end end return root_index end return M
local M = {} local io=require"io" local table=require"table" local crypto=require"crypto" local lfs=require"lfs" local dir=require"pl.dir" local plpath=require"pl.path" local class=require"pl.class" M.BLOCKSIZE=8192 function M.bintohex(s) return (s:gsub('(.)', function(c) return string.format('%02x', string.byte(c)) end)) end -- Start a weak checksum on a block of data -- Good for a rolling checksum function M.start_cksum(data) local a = 0 local b = 0 local l = data:len() local x for i = 1, l do x = data:byte(i) a = a + x b = b + (l - i) * x end return a, b end -- Complete weak checksum on a smallish block function M.weak_cksum(data) local a, b = M.start_cksum(data) return (b * 65536) + a end -- Roll checksum byte-by-byte function M.roll_cksum(removed_byte, added_byte, a, b) a = a - (removed_byte - added_byte) b = b - ((removed_byte * M.BLOCKSIZE) - a) return a, b end function M.strong_cksum(data) return crypto.evp.digest("sha1", data) end M.FileIndex = class() function M.FileIndex:_init(name) self.name = name self.strong = nil self.blocks = {} end function M.get_file_index(path) local index = M.FileIndex(plpath.basename(path)) local f = io.open(path, "r") local block_num = 1 local buf local hash = crypto.evp.new("sha1") while true do buf = f:read(M.BLOCKSIZE) if not buf then break end index.blocks[block_num] = {weak=M.weak_cksum(buf), strong=M.strong_cksum(buf)} hash:update(buf) block_num = block_num + 1 end io.close(f) index.strong = hash:digest() return index end function M.get_file_block(path, block_nums) local result = {} local f = io.open(path, "r") for block_num in pairs(block_nums) do f:seek(block_num * M.BLOCKSIZE) result[block_num] = f:read(M.BLOCKSIZE) end return result end M.DirIndex = class() function M.DirIndex:_init(name) self.name = name self.dirs = {} self.files = {} self.strong = nil end function M.get_dir_index(path) local root_index = M.DirIndex(plpath.basename(path)) local dir_index_map = {} dir_index_map[path]=root_index local dir_index = nil for root, subdirs, files in dir.walk(path) do dir_index = dir_index_map[root] local fpath for i, f in pairs(files) do fpath = plpath.join(root, f) table.insert(dir_index.files, M.get_file_index(fpath)) end local dpath local sub_index for i, d in pairs(subdirs) do dpath = plpath.join(root, d) sub_index = M.DirIndex(plpath.basename(dpath)) dir_index_map[dpath] = sub_index table.insert(dir_index.dirs, sub_index) end end return dir_index_map, root_index end return M
Fixed bugs in directory indexing. Using real penlight objects.
Fixed bugs in directory indexing. Using real penlight objects.
Lua
mit
cmars/replican-sync,daququ/replican-sync
675410bf611e6cd5472cb953a2984d127baf01f5
ffi/rtc.lua
ffi/rtc.lua
--[[-- Module for interfacing with the RTC (real time clock). This module provides the ability to schedule wakeups through RTC. See <http://man7.org/linux/man-pages/man4/rtc.4.html> for technical details. @module ffi.rtc ]] local ffi = require("ffi") local bor = bit.bor local C = ffi.C -- Load header definitions for functions and constants to the ffi.C namespace. local dummy = require("ffi/posix_h") local dummy = require("ffi/rtc_h") ----------------------------------------------------------------- local RTC = { _wakeup_scheduled = false, -- Flipped in @{setWakeupAlarm} and @{unsetWakeupAlarm}. _wakeup_scheduled_ptm = nil, -- Stores a reference to the time of the last scheduled wakeup alarm. } --[[-- Adds seconds to epoch. @int seconds_from_now Number of seconds. @treturn int (cdata) Epoch. --]] function RTC:secondsFromNowToEpoch(seconds_from_now) local t = ffi.new("time_t[1]") t[0] = C.time(nil) t[0] = t[0] + seconds_from_now local epoch = C.mktime(C.localtime(t)) return epoch end --[[-- Set wakeup alarm. If you want to set the alarm to a certain amount of time from now, you can process your value with @{secondsFromNowToEpoch}. @int Epoch. @enabled bool Whether the call enables or disables the alarm. Defaults to true. @treturn bool Success. @treturn re Error code (if any). @treturn err Error string (if any). --]] function RTC:setWakeupAlarm(epoch, enabled) enabled = (enabled ~= nil) and enabled or true local ptm = C.gmtime(ffi.new("time_t[1]", epoch)) self._wakeup_scheduled_ptm = ptm local wake = ffi.new("struct rtc_wkalrm") wake.time.tm_sec = ptm.tm_sec wake.time.tm_min = ptm.tm_min wake.time.tm_hour = ptm.tm_hour wake.time.tm_mday = ptm.tm_mday wake.time.tm_mon = ptm.tm_mon wake.time.tm_year = ptm.tm_year -- wday, yday, and isdst fields are unused by Linux wake.time.tm_wday = -1 wake.time.tm_yday = -1 wake.time.tm_isdst = -1 wake.enabled = enabled and 1 or 0 local err local rtc0 = C.open("/dev/rtc0", bor(C.O_RDONLY, C.O_NONBLOCK)) if rtc0 == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm open /dev/rtc0", rtc0, err) return nil, rtc0, err end local re = C.ioctl(rtc0, C.RTC_WKALM_SET, wake) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm ioctl RTC_WKALM_SET", re, err) return nil, re, err end re = C.close(rtc0) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm close /dev/rtc0", re, err) return nil, re, err end if enabled then self._wakeup_scheduled = true else self._wakeup_scheduled = false self._wakeup_scheduled_ptm = nil end return true end --[[-- Unset wakeup alarm. --]] function RTC:unsetWakeupAlarm() self:setWakeupAlarm(-1, false) self._wakeup_scheduled = false self._wakeup_scheduled_ptm = nil end --[[-- Get a copy of the wakealarm we set (if any). This value is compared with @{getWakeupAlarmSys} in @{validateWakeupAlarmByProximity}. @treturn tm (time struct) --]] function RTC:getWakeupAlarm() return self._wakeup_scheduled_ptm end --[[-- Get RTC wakealarm from system. @treturn tm (time struct) --]] function RTC:getWakeupAlarmSys() local wake = ffi.new("struct rtc_wkalrm") local err, re local rtc0 = C.open("/dev/rtc0", C.O_RDONLY) if rtc0 == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm open /dev/rtc0", rtc0, err) return nil, rtc0, err end re = C.ioctl(rtc0, C.RTC_WKALM_RD, wake) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm ioctl RTC_WKALM_RD", re, err) return nil, re, err end re = C.close(rtc0) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm close /dev/rtc0", re, err) return nil, re, err end if wake ~= -1 then local t = ffi.new("time_t[1]") t[0] = C.time(nil) local tm = ffi.new("struct tm") -- luacheck: ignore tm = C.gmtime(t) tm.tm_sec = wake.time.tm_sec tm.tm_min = wake.time.tm_min tm.tm_hour = wake.time.tm_hour tm.tm_mday = wake.time.tm_mday tm.tm_mon = wake.time.tm_mon tm.tm_year = wake.time.tm_year return tm end end --[[-- Checks if the alarm we set matches the system alarm as well as the current time. --]] function RTC:validateWakeupAlarmByProximity(task_alarm_epoch, proximity) -- In principle alarm time and current time should match within a second, -- but let's be absurdly generous and assume anything within 30 is a match. proximity = proximity or 30 local alarm = self:getWakeupAlarm() local alarm_epoch local alarm_sys = self:getWakeupAlarmSys() local alarm_sys_epoch -- this seems a bit roundabout local current_time = ffi.new("time_t[1]") current_time[0] = C.time(nil) local current_time_epoch = C.mktime(C.gmtime(current_time)) if not (alarm and alarm_sys) then return end alarm_epoch = C.mktime(alarm) alarm_sys_epoch = C.mktime(alarm_sys) print("validateWakeupAlarmByProximity", task_alarm_epoch, alarm_epoch, alarm_sys_epoch, current_time_epoch) -- If our stored alarm and the system alarm don't match, we didn't set it. if not (alarm_epoch == alarm_sys_epoch) then return end -- If our stored alarm and the provided task alarm don't match, -- we're not talking about the same task. This should never happen. if task_alarm_epoch and not (alarm_epoch == task_alarm_epoch) then return end local diff = current_time_epoch - alarm_epoch if diff >= 0 and diff < proximity then return true end end --[[-- Checks if we scheduled a wakeup alarm. @treturn bool --]] function RTC:isWakeupAlarmScheduled() return self._wakeup_scheduled end return RTC
--[[-- Module for interfacing with the RTC (real time clock). This module provides the ability to schedule wakeups through RTC. See <http://man7.org/linux/man-pages/man4/rtc.4.html> for technical details. @module ffi.rtc ]] local ffi = require("ffi") local bor = bit.bor local C = ffi.C -- Load header definitions for functions and constants to the ffi.C namespace. local dummy = require("ffi/posix_h") local dummy = require("ffi/rtc_h") ----------------------------------------------------------------- local RTC = { _wakeup_scheduled = false, -- Flipped in @{setWakeupAlarm} and @{unsetWakeupAlarm}. _wakeup_scheduled_ptm = nil, -- Stores a reference to the time of the last scheduled wakeup alarm. } --[[-- Adds seconds to epoch. @int seconds_from_now Number of seconds. @treturn int (cdata) Epoch. --]] function RTC:secondsFromNowToEpoch(seconds_from_now) local t = ffi.new("time_t[1]") t[0] = C.time(nil) t[0] = t[0] + seconds_from_now local epoch = C.mktime(C.localtime(t)) return epoch end --[[-- Set wakeup alarm. If you want to set the alarm to a certain amount of time from now, you can process your value with @{secondsFromNowToEpoch}. @int Epoch. @enabled bool Whether the call enables or disables the alarm. Defaults to true. @treturn bool Success. @treturn re Error code (if any). @treturn err Error string (if any). --]] function RTC:setWakeupAlarm(epoch, enabled) enabled = (enabled ~= nil) and enabled or true local ptm = C.gmtime(ffi.new("time_t[1]", epoch)) self._wakeup_scheduled_ptm = ptm local wake = ffi.new("struct rtc_wkalrm") wake.time.tm_sec = ptm.tm_sec wake.time.tm_min = ptm.tm_min wake.time.tm_hour = ptm.tm_hour wake.time.tm_mday = ptm.tm_mday wake.time.tm_mon = ptm.tm_mon wake.time.tm_year = ptm.tm_year -- wday, yday, and isdst fields are unused by Linux wake.time.tm_wday = -1 wake.time.tm_yday = -1 wake.time.tm_isdst = -1 wake.enabled = enabled and 1 or 0 local err local rtc0 = C.open("/dev/rtc0", bor(C.O_RDONLY, C.O_NONBLOCK)) if rtc0 == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm open /dev/rtc0", rtc0, err) return nil, rtc0, err end local re = C.ioctl(rtc0, C.RTC_WKALM_SET, wake) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm ioctl RTC_WKALM_SET", re, err) return nil, re, err end re = C.close(rtc0) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("setWakeupAlarm close /dev/rtc0", re, err) return nil, re, err end if enabled then self._wakeup_scheduled = true else self._wakeup_scheduled = false self._wakeup_scheduled_ptm = nil end return true end --[[-- Unset wakeup alarm. --]] function RTC:unsetWakeupAlarm() self:setWakeupAlarm(-1, false) self._wakeup_scheduled = false self._wakeup_scheduled_ptm = nil end --[[-- Get a copy of the wakealarm we set (if any). This value is compared with @{getWakeupAlarmSys} in @{validateWakeupAlarmByProximity}. @treturn tm (time struct) --]] function RTC:getWakeupAlarm() return self._wakeup_scheduled_ptm end --[[-- Get RTC wakealarm from system. @treturn tm (time struct) --]] function RTC:getWakeupAlarmSys() local wake = ffi.new("struct rtc_wkalrm") local err, re local rtc0 = C.open("/dev/rtc0", C.O_RDONLY) if rtc0 == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm open /dev/rtc0", rtc0, err) return nil, rtc0, err end re = C.ioctl(rtc0, C.RTC_WKALM_RD, wake) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm ioctl RTC_WKALM_RD", re, err) return nil, re, err end re = C.close(rtc0) if re == -1 then err = ffi.string(C.strerror(ffi.errno())) print("getWakeupAlarm close /dev/rtc0", re, err) return nil, re, err end if wake ~= -1 then local t = ffi.new("time_t[1]") t[0] = C.time(nil) local tm = ffi.new("struct tm") -- luacheck: ignore tm = C.gmtime(t) tm.tm_sec = wake.time.tm_sec tm.tm_min = wake.time.tm_min tm.tm_hour = wake.time.tm_hour tm.tm_mday = wake.time.tm_mday tm.tm_mon = wake.time.tm_mon tm.tm_year = wake.time.tm_year return tm end end --[[-- Checks if the alarm we set matches the system alarm as well as the current time. --]] function RTC:validateWakeupAlarmByProximity(task_alarm_epoch, proximity) -- In principle alarm time and current time should match within a second, -- but let's be absurdly generous and assume anything within 30 is a match. proximity = proximity or 30 local alarm = self:getWakeupAlarm() local alarm_epoch local alarm_sys = self:getWakeupAlarmSys() local alarm_sys_epoch -- this seems a bit roundabout local current_time = ffi.new("time_t[1]") current_time[0] = C.time(nil) local current_time_epoch = C.mktime(C.gmtime(current_time)) if not (alarm and alarm_sys) then return end -- Convert from UTC to local because these time-related functions are @#$@#$ stupid. local task_alarm_epoch_local = task_alarm_epoch and C.mktime(C.gmtime(ffi.new("time_t[1]", task_alarm_epoch))) or nil alarm_epoch = C.mktime(alarm) alarm_sys_epoch = C.mktime(alarm_sys) print("validateWakeupAlarmByProximity", task_alarm_epoch_local, alarm_epoch, alarm_sys_epoch, current_time_epoch) -- If our stored alarm and the system alarm don't match, we didn't set it. if not (alarm_epoch == alarm_sys_epoch) then return end -- If our stored alarm and the provided task alarm don't match, -- we're not talking about the same task. This should never happen. if task_alarm_epoch_local and not (alarm_epoch == task_alarm_epoch_local) then return end local diff = current_time_epoch - alarm_epoch if diff >= 0 and diff < proximity then return true end end --[[-- Checks if we scheduled a wakeup alarm. @treturn bool --]] function RTC:isWakeupAlarmScheduled() return self._wakeup_scheduled end return RTC
[fix] RTC: Compare time values in the right timezone (#977)
[fix] RTC: Compare time values in the right timezone (#977) Fixes <https://github.com/koreader/koreader/issues/5376>.
Lua
agpl-3.0
Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,koreader/koreader-base,Frenzie/koreader-base
e1728fada330ce65d565aa80ed51cccfcc0fe6cd
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = node("lm") page.target = template("linkmeter/index") page.order = 10 page.sysauth = { "anon", "root" } page.sysauth_authenticator = require "luci.controller.linkmeter.lm".lmauth entry({"lm", "set"}, call("set")) entry({"lm", "login"}, call("rootredirect")).sysauth = "root" end function lmauth(validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) setfenv(sdat, {}) sdat = sdat() if sdat.token == luci.dispatcher.context.urltoken then user = sdat.user end end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then vals = require "luci.http.protocol".urldecode_params(rawset) end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end local uci = luci.model.uci.cursor() local device = uci:get("linkmeter", "daemon", "serial_device") local f = nixio.open(device, "w") if f == nil then return dsp.error500("Can not open serial device "..device) end http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end http.write("%s to %s\n" % {k,v}) f:write("/set?%s=%s\n" % {k,v}) end f:close() http.write("Done!") end
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = node("lm") page.target = template("linkmeter/index") page.order = 10 page.sysauth = { "anon", "root" } page.sysauth_authenticator = require "luci.controller.linkmeter.lm".lmauth entry({"lm", "set"}, call("set")) entry({"lm", "login"}, call("rootredirect")).sysauth = "root" end function lmauth(validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) setfenv(sdat, {}) sdat = sdat() if sdat.token == luci.dispatcher.context.urltoken then user = sdat.user end end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then if rawset:sub(1, 5) == "/set?" then rawset = rawset:sub(6) end vals = require "luci.http.protocol".urldecode_params(rawset) end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end local uci = luci.model.uci.cursor() local device = uci:get("linkmeter", "daemon", "serial_device") local f = nixio.open(device, "w") if f == nil then return dsp.error500("Can not open serial device "..device) end http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end http.write("%s to %s\n" % {k,v}) f:write("/set?%s=%s\n" % {k,v}) end f:close() http.write("Done!") end
[lm] Allow rawset to be prefixed with /set? because I know someone's gonna try that
[lm] Allow rawset to be prefixed with /set? because I know someone's gonna try that
Lua
mit
CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter
eb9a0d9965f961539b644562ebbd5053e4264d7b
testserver/item/id_321_depot.lua
testserver/item/id_321_depot.lua
-- Depots -- UPDATE common SET com_script='item.id_321_depot' WHERE com_itemid=321; module("item.id_321_depot", package.seeall) function LookAtItem(User,Item) local lang = User:getPlayerLanguage(); local LookAtStr = world:getItemName(321,lang).." ("; --NewIllarion if (Item.data==101) then LookAtStr = LookAtStr.."Cadomyr"; elseif (Item.data==102) then LookAtStr = LookAtStr.."Runewick"; elseif (Item.data==103) then LookAtStr = LookAtStr.."Galmair"; elseif (Item.data==104) then if (lang==0) then LookAtStr = LookAtStr.."Gasthof zur Hanfschlinge"; else LookAtStr = LookAtStr.."The Hemp Necktie Inn"; end elseif (Item.data==1337) then if (lang==0) then LookAtStr = LookAtStr.."Estralis - Hand ab, sonst Hand ab!"; else LookAtStr = LookAtStr.."Estralis - Hands off or hands off!"; end else theOwner=getCharForId(Item.data); if theOwner then LookAtStr = LookAtStr..theOwner.name; else LookAtStr = LookAtStr.."Debugging: Unknown depot"; end end LookAtStr = LookAtStr..")"; world:itemInform(User,Item,LookAtStr); end
-- Depots -- UPDATE common SET com_script='item.id_321_depot' WHERE com_itemid=321; require("base.common") require("base.lookat") module("item.id_321_depot", package.seeall) function LookAtItem(User, Item) local lookAt = base.lookat.GenerateLookAt(User, Item) local depotId = tonumber(Item.getData("depot")) if depotId == 101 then lookAt.description = "Cadomyr" elseif depotId == 102 then lookAt.description = "Runewick" elseif depotId == 103 then lookAt.description = "Galmair" elseif depotId == 104 then lookAt.description = base.common.GetNLS(User, "Gasthof zur Hanfschlinge", "The Hemp Necktie Inn") end world:itemInform(User, Item, lookAt) end
Fix depot lookat
Fix depot lookat
Lua
agpl-3.0
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content
c9fa92101add6fadf3e62042da9dd21594cbbd65
kong/dao/schemas/upstreams.lua
kong/dao/schemas/upstreams.lua
local Errors = require "kong.dao.errors" local utils = require "kong.tools.utils" local match = string.match local sub = string.sub local DEFAULT_SLOTS = 100 local SLOTS_MIN, SLOTS_MAX = 10, 2^16 local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX local function check_nonnegative(arg) if arg < 0 then return false, "must be greater than or equal to 0" end end local function check_positive_int(t) if t < 1 or t > 2^31 - 1 or math.floor(t) ~= t then return false, "must be an integer between 1 and " .. 2^31 - 1 end return true end local function check_http_path(arg) if match(arg, "^%s*$") then return false, "path is empty" end if sub(arg, 1, 1) ~= "/" then return false, "must be prefixed with slash" end return true end local function check_http_statuses(arg) for _, s in ipairs(arg) do if type(s) ~= "number" then return false, "array element is not a number" end if math.floor(s) ~= s then return false, "must be an integer" end -- Accept any three-digit status code, -- applying Postel's law in case of nonstandard HTTP codes if s < 100 or s > 999 then return false, "invalid status code '" .. s .. "': must be between 100 and 999" end end return true end -- same fields as lua-resty-healthcheck library local healthchecks_defaults = { active = { timeout = 1, concurrency = 10, http_path = "/", healthy = { interval = 0, -- 0 = disabled by default http_statuses = { 200, 302 }, successes = 2, }, unhealthy = { interval = 0, -- 0 = disabled by default http_statuses = { 429, 404, 500, 501, 502, 503, 504, 505 }, tcp_failures = 2, timeouts = 3, http_failures = 5, }, }, passive = { healthy = { http_statuses = { 200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308 }, successes = 5, }, unhealthy = { http_statuses = { 429, 500, 503 }, tcp_failures = 2, timeouts = 7, http_failures = 5, }, }, } local funcs = { timeout = check_nonnegative, concurrency = check_positive_int, interval = check_nonnegative, successes = check_positive_int, tcp_failures = check_positive_int, timeouts = check_positive_int, http_failures = check_positive_int, http_path = check_http_path, http_statuses = check_http_statuses, } local function gen_schema(tbl) local ret = {} for k, v in pairs(tbl) do if type(v) == "number" or type(v) == "string" then ret[k] = { type = type(v), default = v, func = funcs[k] } elseif type(v) == "table" then if v[1] then ret[k] = { type = "array", default = v, func = funcs[k] } else ret[k] = { type = "table", schema = gen_schema(v), default = v } end end end return { fields = ret } end return { table = "upstreams", primary_key = {"id"}, fields = { id = { type = "id", dao_insert_value = true, required = true, }, created_at = { type = "timestamp", immutable = true, dao_insert_value = true, required = true, }, name = { -- name is a hostname like name that can be referenced in an `upstream_url` field type = "string", unique = true, required = true, }, hash_on = { -- primary hash-key type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_fallback = { -- secondary key, if primary fails type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_on_header = { -- header name, if `hash_on == "header"` type = "string", }, hash_fallback_header = { -- header name, if `hash_fallback == "header"` type = "string", }, slots = { -- the number of slots in the loadbalancer algorithm type = "number", default = DEFAULT_SLOTS, }, healthchecks = { type = "table", schema = gen_schema(healthchecks_defaults), default = healthchecks_defaults, }, }, self_check = function(schema, config, dao, is_updating) -- check the name if config.name then local p = utils.normalize_ip(config.name) if not p then return false, Errors.schema("Invalid name; must be a valid hostname") end if p.type ~= "name" then return false, Errors.schema("Invalid name; no ip addresses allowed") end if p.port then return false, Errors.schema("Invalid name; no port allowed") end end if config.hash_on_header then local ok, err = utils.validate_header_name(config.hash_on_header) if not ok then return false, Errors.schema("Header: " .. err) end end if config.hash_fallback_header then local ok, err = utils.validate_header_name(config.hash_fallback_header) if not ok then return false, Errors.schema("Header: " .. err) end end if (config.hash_on == "header" and not config.hash_on_header) or (config.hash_fallback == "header" and not config.hash_fallback_header) then return false, Errors.schema("Hashing on 'header', " .. "but no header name provided") end if config.hash_on and config.hash_fallback then if config.hash_on == "none" then if config.hash_fallback ~= "none" then return false, Errors.schema("Cannot set fallback if primary " .. "'hash_on' is not set") end else if config.hash_on == config.hash_fallback then if config.hash_on ~= "header" then return false, Errors.schema("Cannot set fallback and primary " .. "hashes to the same value") else local upper_hash_on = config.hash_on_header:upper() local upper_hash_fallback = config.hash_fallback_header:upper() if upper_hash_on == upper_hash_fallback then return false, Errors.schema("Cannot set fallback and primary ".. "hashes to the same value") end end end end end if config.slots then -- check the slots number if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then return false, Errors.schema(SLOTS_MSG) end end return true end, }
local Errors = require "kong.dao.errors" local utils = require "kong.tools.utils" local match = string.match local sub = string.sub local DEFAULT_SLOTS = 100 local SLOTS_MIN, SLOTS_MAX = 10, 2^16 local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX local function check_nonnegative(arg) if arg < 0 then return false, "must be greater than or equal to 0" end end local function check_positive_int(t) if t < 1 or t > 2^31 - 1 or math.floor(t) ~= t then return false, "must be an integer between 1 and " .. 2^31 - 1 end return true end local function check_http_path(arg) if match(arg, "^%s*$") then return false, "path is empty" end if sub(arg, 1, 1) ~= "/" then return false, "must be prefixed with slash" end return true end local function check_http_statuses(arg) for _, s in ipairs(arg) do if type(s) ~= "number" then return false, "array element is not a number" end if math.floor(s) ~= s then return false, "must be an integer" end -- Accept any three-digit status code, -- applying Postel's law in case of nonstandard HTTP codes if s < 100 or s > 999 then return false, "invalid status code '" .. s .. "': must be between 100 and 999" end end return true end -- same fields as lua-resty-healthcheck library local healthchecks_defaults = { active = { timeout = 1, concurrency = 10, http_path = "/", healthy = { interval = 0, -- 0 = probing disabled by default http_statuses = { 200, 302 }, successes = 0, -- 0 = disabled by default }, unhealthy = { interval = 0, -- 0 = probing disabled by default http_statuses = { 429, 404, 500, 501, 502, 503, 504, 505 }, tcp_failures = 0, -- 0 = disabled by default timeouts = 0, -- 0 = disabled by default http_failures = 0, -- 0 = disabled by default }, }, passive = { healthy = { http_statuses = { 200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308 }, successes = 0, }, unhealthy = { http_statuses = { 429, 500, 503 }, tcp_failures = 0, -- 0 = circuit-breaker disabled by default timeouts = 0, -- 0 = circuit-breaker disabled by default http_failures = 0, -- 0 = circuit-breaker disabled by default }, }, } local funcs = { timeout = check_nonnegative, concurrency = check_positive_int, interval = check_nonnegative, successes = check_positive_int, tcp_failures = check_positive_int, timeouts = check_positive_int, http_failures = check_positive_int, http_path = check_http_path, http_statuses = check_http_statuses, } local function gen_schema(tbl) local ret = {} for k, v in pairs(tbl) do if type(v) == "number" or type(v) == "string" then ret[k] = { type = type(v), default = v, func = funcs[k] } elseif type(v) == "table" then if v[1] then ret[k] = { type = "array", default = v, func = funcs[k] } else ret[k] = { type = "table", schema = gen_schema(v), default = v } end end end return { fields = ret } end return { table = "upstreams", primary_key = {"id"}, fields = { id = { type = "id", dao_insert_value = true, required = true, }, created_at = { type = "timestamp", immutable = true, dao_insert_value = true, required = true, }, name = { -- name is a hostname like name that can be referenced in an `upstream_url` field type = "string", unique = true, required = true, }, hash_on = { -- primary hash-key type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_fallback = { -- secondary key, if primary fails type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_on_header = { -- header name, if `hash_on == "header"` type = "string", }, hash_fallback_header = { -- header name, if `hash_fallback == "header"` type = "string", }, slots = { -- the number of slots in the loadbalancer algorithm type = "number", default = DEFAULT_SLOTS, }, healthchecks = { type = "table", schema = gen_schema(healthchecks_defaults), default = healthchecks_defaults, }, }, self_check = function(schema, config, dao, is_updating) -- check the name if config.name then local p = utils.normalize_ip(config.name) if not p then return false, Errors.schema("Invalid name; must be a valid hostname") end if p.type ~= "name" then return false, Errors.schema("Invalid name; no ip addresses allowed") end if p.port then return false, Errors.schema("Invalid name; no port allowed") end end if config.hash_on_header then local ok, err = utils.validate_header_name(config.hash_on_header) if not ok then return false, Errors.schema("Header: " .. err) end end if config.hash_fallback_header then local ok, err = utils.validate_header_name(config.hash_fallback_header) if not ok then return false, Errors.schema("Header: " .. err) end end if (config.hash_on == "header" and not config.hash_on_header) or (config.hash_fallback == "header" and not config.hash_fallback_header) then return false, Errors.schema("Hashing on 'header', " .. "but no header name provided") end if config.hash_on and config.hash_fallback then if config.hash_on == "none" then if config.hash_fallback ~= "none" then return false, Errors.schema("Cannot set fallback if primary " .. "'hash_on' is not set") end else if config.hash_on == config.hash_fallback then if config.hash_on ~= "header" then return false, Errors.schema("Cannot set fallback and primary " .. "hashes to the same value") else local upper_hash_on = config.hash_on_header:upper() local upper_hash_fallback = config.hash_fallback_header:upper() if upper_hash_on == upper_hash_fallback then return false, Errors.schema("Cannot set fallback and primary ".. "hashes to the same value") end end end end end if config.slots then -- check the slots number if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then return false, Errors.schema(SLOTS_MSG) end end return true end, }
hotfix(healthchecks) disable circuit-breaker functionality by default
hotfix(healthchecks) disable circuit-breaker functionality by default To avoid unexpected behaviors for users, this makes all health counter thresholds to be zero by default, effectively making the circuit-breaker functionality of passive healthchecks to be disabled by default. Users need to opt-in by supplying threshold values to enable the cut-off of targets based on analysis of ongoing traffic. This commit requires functionality introduced in lua-resty-healthcheck 0.3.0.
Lua
apache-2.0
jebenexer/kong,Kong/kong,Kong/kong,Mashape/kong,Kong/kong
f6857db44b262013a119918632a281000c8cf34a
src_trunk/resources/lves-system/s_lves_system.lua
src_trunk/resources/lves-system/s_lves_system.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// function realisticDamage(attacker, weapon, bodypart, loss) if (attacker) and (weapon) then local health = getElementHealth(source) local intLoss = loss * health local armor = getPedArmor(source) if (weapon==8) then -- katana setPedHeadless(source, true) killPed(source, attacker, weapon, bodypart) end if (bodypart==9) and not (armor>0) then -- Head and no armor. setPedHeadless(source, true) killPed(source, attacker, weapon, bodypart) exports.global:givePlayerAchievement(attacker, 12) exports.global:givePlayerAchievement(source, 15) end end end addEventHandler("onPlayerDamage", getRootElement(), realisticDamage) function playerDeath() outputChatBox("Respawn in 10 seconds.", source) setTimer(respawnPlayer, 10000, 1, source) end addEventHandler("onPlayerWasted", getRootElement(), playerDeath) function respawnPlayer(thePlayer) if (isElement(thePlayer)) then local cost = math.random(25,50) local money = getElementData(thePlayer, "money") setPedHeadless(thePlayer, false) -- Fix for injected cash if (cost>money) then cost = money end if (exports.global:isPlayerSilverDonator(thePlayer)) then cost = 0 else exports.global:takePlayerSafeMoney(thePlayer, cost) end local result = mysql_query(handler, "SELECT bankbalance FROM factions WHERE id='2' OR id='3' LIMIT 2") if (mysql_num_rows(result)>0) then local tax = exports.global:getTaxAmount() local currentESBalance = mysql_result(result, 1, 1) local currentGOVBalance = mysql_result(result, 2, 1) local ESMoney = math.ceil((1-tax)*cost) local GOVMoney = math.ceil(tax*cost) local theTeamES = getTeamFromName("Los Santos Emergency Services") local theTeamGov = getTeamFromName("Government of Los Santos") setElementData(theTeamES, "money", (currentESBalance+ESMoney)) setElementData(theTeamGov, "money", (currentGOVBalance+GOVMoney+money)) local update = mysql_query(handler, "UPDATE factions SET bankbalance='" .. (currentESBalance+ESMoney) .. "' WHERE id='2'") local update2 = mysql_query(handler, "UPDATE factions SET bankbalance='" .. (currentGOVBalance+GOVMoney+money) .. "' WHERE id='3'") local update3 = mysql_query(handler, "UPDATE characters SET deaths = deaths + 1 WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(thePlayer)) .. "'") if (update) then mysql_free_result(update) end if (update2) then mysql_free_result(update2) end if (update3) then mysql_free_result(update3) end setCameraInterior(thePlayer, 0) outputChatBox("You have recieved treatment from the Los Santos Emergency Services. Cost: " .. cost .. "$", thePlayer, 255, 255, 0) -- take all drugs local count = 0 for i = 30, 43 do while exports.global:doesPlayerHaveItem(thePlayer, i, -1) do exports.global:takePlayerItem(thePlayer, i, -1) count = count + 1 end end if count > 0 then outputChatBox("LSES Employee: We handed your drugs over to the LSPD Investigators.", thePlayer, 255, 194, 14) end local theSkin = getPedSkin(thePlayer) local theTeam = getPlayerTeam(thePlayer) local fat = getPedStat(thePlayer, 21) local muscle = getPedStat(thePlayer, 23) setPedStat(thePlayer, 21, fat) setPedStat(thePlayer, 23, muscle) spawnPlayer(thePlayer, 1183.291015625, -1323.033203125, 13.577140808105, 267.4580078125, theSkin, 0, 0, theTeam) fadeCamera(thePlayer, true, 2) end mysql_free_result(result) end end function deathRemoveWeapons(weapons, removedWeapons) setTimer(giveGunsBack, 10005, 1, source, weapons, removedWeapons) end addEvent("onDeathRemovePlayerWeapons", true) addEventHandler("onDeathRemovePlayerWeapons", getRootElement(), deathRemoveWeapons) function giveGunsBack(thePlayer, weapons, removedWeapons) if (removedWeapons~=nil) then if tonumber(getElementData(thePlayer, "license.gun")) == 0 and getElementData(getPlayerTeam(thePlayer),"type") ~= 2 then outputChatBox("LSES Employee: We have taken away weapons which you did not have a license for. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14) else outputChatBox("LSES Employee: We have taken away weapons which you are not allowed to carry. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14) end end for key, value in ipairs(weapons) do local weapon = tonumber(weapons[key][1]) local ammo = tonumber(weapons[key][2]) local removed = tonumber(weapons[key][3]) if (removed==0) then exports.global:giveWeapon(thePlayer, weapon, ammo, false) else exports.global:takeWeapon(thePlayer, weapon) end end end
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// function realisticDamage(attacker, weapon, bodypart, loss) if (attacker) and (weapon) then local health = getElementHealth(source) local intLoss = loss * health local armor = getPedArmor(source) if (weapon==8) then -- katana setPedHeadless(source, true) killPed(source, attacker, weapon, bodypart) end if (bodypart==9) and not (armor>0) then -- Head and no armor. setPedHeadless(source, true) killPed(source, attacker, weapon, bodypart) exports.global:givePlayerAchievement(attacker, 12) exports.global:givePlayerAchievement(source, 15) end end end addEventHandler("onPlayerDamage", getRootElement(), realisticDamage) function playerDeath() outputChatBox("Respawn in 10 seconds.", source) setTimer(respawnPlayer, 10000, 1, source) end addEventHandler("onPlayerWasted", getRootElement(), playerDeath) function respawnPlayer(thePlayer) if (isElement(thePlayer)) then local cost = math.random(25,50) local money = getElementData(thePlayer, "money") setPedHeadless(thePlayer, false) -- Fix for injected cash if (cost>money) then cost = money end if (exports.global:isPlayerSilverDonator(thePlayer)) then cost = 0 else exports.global:takePlayerSafeMoney(thePlayer, cost) end local result = mysql_query(handler, "SELECT bankbalance FROM factions WHERE id='2' OR id='3' LIMIT 2") if (mysql_num_rows(result)>0) then local tax = exports.global:getTaxAmount() local currentESBalance = mysql_result(result, 1, 1) local currentGOVBalance = mysql_result(result, 2, 1) local ESMoney = math.ceil((1-tax)*cost) local GOVMoney = math.ceil(tax*cost) local theTeamES = getTeamFromName("Los Santos Emergency Services") local theTeamGov = getTeamFromName("Government of Los Santos") setElementData(theTeamES, "money", (currentESBalance+ESMoney)) setElementData(theTeamGov, "money", (currentGOVBalance+GOVMoney+money)) local update = mysql_query(handler, "UPDATE factions SET bankbalance='" .. (currentESBalance+ESMoney) .. "' WHERE id='2'") local update2 = mysql_query(handler, "UPDATE factions SET bankbalance='" .. (currentGOVBalance+GOVMoney+money) .. "' WHERE id='3'") local update3 = mysql_query(handler, "UPDATE characters SET deaths = deaths + 1 WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(thePlayer)) .. "'") if (update) then mysql_free_result(update) end if (update2) then mysql_free_result(update2) end if (update3) then mysql_free_result(update3) end setCameraInterior(thePlayer, 0) local text = "You have recieved treatment from the Los Santos Emergency Services." if cost > 0 then text = text .. " Cost: " .. cost .. "$" end outputChatBox(text, thePlayer, 255, 255, 0) -- take all drugs local count = 0 for i = 30, 43 do while exports.global:doesPlayerHaveItem(thePlayer, i, -1) do exports.global:takePlayerItem(thePlayer, i, -1) count = count + 1 end end if count > 0 then outputChatBox("LSES Employee: We handed your drugs over to the LSPD Investigators.", thePlayer, 255, 194, 14) end local theSkin = getPedSkin(thePlayer) local theTeam = getPlayerTeam(thePlayer) local fat = getPedStat(thePlayer, 21) local muscle = getPedStat(thePlayer, 23) setPedStat(thePlayer, 21, fat) setPedStat(thePlayer, 23, muscle) spawnPlayer(thePlayer, 1183.291015625, -1323.033203125, 13.577140808105, 267.4580078125, theSkin, 0, 0, theTeam) fadeCamera(thePlayer, true, 2) end mysql_free_result(result) end end function deathRemoveWeapons(weapons, removedWeapons) setTimer(giveGunsBack, 10005, 1, source, weapons, removedWeapons) end addEvent("onDeathRemovePlayerWeapons", true) addEventHandler("onDeathRemovePlayerWeapons", getRootElement(), deathRemoveWeapons) function giveGunsBack(thePlayer, weapons, removedWeapons) if (removedWeapons~=nil) then if tonumber(getElementData(thePlayer, "license.gun")) == 0 and getElementData(getPlayerTeam(thePlayer),"type") ~= 2 then outputChatBox("LSES Employee: We have taken away weapons which you did not have a license for. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14) else outputChatBox("LSES Employee: We have taken away weapons which you are not allowed to carry. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14) end end for key, value in ipairs(weapons) do local weapon = tonumber(weapons[key][1]) local ammo = tonumber(weapons[key][2]) local removed = tonumber(weapons[key][3]) if (removed==0) then exports.global:giveWeapon(thePlayer, weapon, ammo, false) else exports.global:takeWeapon(thePlayer, weapon) end end end
text fix
text fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1297 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
b0e365f9c5557e5f4d3a627e29d988131b25931a
orange/plugins/dynamic_upstream/handler.lua
orange/plugins/dynamic_upstream/handler.lua
local pairs = pairs local ipairs = ipairs local ngx_re_sub = ngx.re.sub local ngx_re_find = ngx.re.find local string_sub = string.sub local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local extractor_util = require("orange.utils.extractor") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local ngx_set_uri = ngx.req.set_uri local ngx_set_uri_args = ngx.req.set_uri_args local ngx_decode_args = ngx.decode_args local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, "rewrite") -- extract阶段 local variables = extractor_util.extract_variables(rule.extractor) -- handle阶段 if pass then local handle = rule.handle if handle and handle.uri_tmpl then local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables) if to_rewrite and to_rewrite ~= ngx_var_uri then if handle.log == true then ngx.log(ngx.INFO, "[Rewrite] ", ngx_var_uri, " to:", to_rewrite) end local from, to, err = ngx_re_find(to_rewrite, "[%?]{1}", "jo") if not err and from and from >= 1 then --local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo") local qs = string_sub(to_rewrite, from+1) if qs then local args = ngx_decode_args(qs, 0) if args then ngx_set_uri_args(args) end end end ngx_set_uri(to_rewrite, true) end end return true end end end return false end local DynamicUpstreamHandler = BasePlugin:extend() DynamicUpstreamHandler.PRIORITY = 2000 function DynamicUpstreamHandler:new(store) RewriteHandler.super.new(self, "rewrite-plugin") self.store = store end function DynamicUpstreamHandler:rewrite(conf) DynamicUpstreamHandler.super.rewrite(self) local enable = orange_db.get("rewrite.enable") local meta = orange_db.get_json("rewrite.meta") local selectors = orange_db.get_json("rewrite.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do ngx.log(ngx.INFO, "==[Rewrite][PASS THROUGH SELECTOR:", sid, "]") local selector = selectors[sid] if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "rewrite")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[Rewrite][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "rewrite", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[Rewrite][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return DynamicUpstreamHandler
local pairs = pairs local ipairs = ipairs local ngx_re_sub = ngx.re.sub local ngx_re_find = ngx.re.find local string_sub = string.sub local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local extractor_util = require("orange.utils.extractor") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local ngx_set_uri_args = ngx.req.set_uri_args local ngx_decode_args = ngx.decode_args local function ngx_set_uri(uri,rule_handle) ngx.var.upstream_request_uri = '/'..uri .. '?' .. ngx.encode_args(ngx.req.get_uri_args()) ngx.var.upstream_name = rule_handle.upstream_name ngx.log(ngx.INFO,'[DynamicUpstream][upstream uri][http://',ngx.var.upstream_name,ngx.var.upstream_request_uri,']') end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, "dynamic_upstream") -- extract阶段 local variables = extractor_util.extract_variables(rule.extractor) -- handle阶段 if pass then local handle = rule.handle if handle and handle.uri_tmpl and handle.upstream_name then local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables) if to_rewrite and to_rewrite ~= ngx_var_uri then if handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream] ", ngx_var_uri, " to:", to_rewrite) end local from, to, err = ngx_re_find(to_rewrite, "[%?]{1}", "jo") if not err and from and from >= 1 then --local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo") local qs = string_sub(to_rewrite, from+1) if qs then local args = ngx_decode_args(qs, 0) if args then ngx_set_uri_args(args) end end end ngx_set_uri(to_rewrite, handle) return true end end return true end end end return false end local DynamicUpstreamHandler = BasePlugin:extend() DynamicUpstreamHandler.PRIORITY = 2000 function DynamicUpstreamHandler:new(store) DynamicUpstreamHandler.super.new(self, "dynamic-upstream-plugin") self.store = store end function DynamicUpstreamHandler:rewrite(conf) DynamicUpstreamHandler.super.rewrite(self) local enable = orange_db.get("dynamic_upstream.enable") local meta = orange_db.get_json("dynamic_upstream.meta") local selectors = orange_db.get_json("dynamic_upstream.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do local selector = selectors[sid] ngx.log(ngx.INFO, "==[DynamicUpstream][START SELECTOR:", sid, "][NAME:",selector.name,']') if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "dynamic_upstream")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "dynamic_upstream", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return DynamicUpstreamHandler
fix&refactor: modify the orange/plugins code copied from rewrite plugiins to achieve the dynamic upstream feature
fix&refactor: modify the orange/plugins code copied from rewrite plugiins to achieve the dynamic upstream feature
Lua
mit
sumory/orange,sumory/orange,sumory/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange
bcd513525963391fbafa73bfe66099ed9e47eafe
applications/luci-wol/luasrc/model/cbi/wol.lua
applications/luci-wol/luasrc/model/cbi/wol.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: olsrd.lua 5560 2009-11-21 00:22:35Z jow $ ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 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 ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
applications/luci-wol: fix copyright
applications/luci-wol: fix copyright git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6092 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
eugenesan/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,ch3n2k/luci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,vhpham80/luci,jschmidlapp/luci,freifunk-gluon/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,8devices/carambola2-luci,phi-psi/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,ch3n2k/luci,jschmidlapp/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,zwhfly/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,jschmidlapp/luci,gwlim/luci,freifunk-gluon/luci,phi-psi/luci,ch3n2k/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,Canaan-Creative/luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,Flexibity/luci,stephank/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,vhpham80/luci,stephank/luci,ch3n2k/luci,stephank/luci,phi-psi/luci,stephank/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,vhpham80/luci,freifunk-gluon/luci,8devices/carambola2-luci,jschmidlapp/luci,Flexibity/luci,Flexibity/luci,phi-psi/luci,ch3n2k/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,jschmidlapp/luci,8devices/carambola2-luci,Canaan-Creative/luci,Canaan-Creative/luci,stephank/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,freifunk-gluon/luci,saraedum/luci-packages-old,gwlim/luci,freifunk-gluon/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci
222415b12ecd545ed8adfb86afc16a6e21c36f6a
src/ui/Timeline.lua
src/ui/Timeline.lua
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local TEXT_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 15); local DEFAULT_FONT = love.graphics.newFont(12); local MARGIN_LEFT = 10; local MARGIN_RIGHT = 10; local HEIGHT = 30; local TOTAL_STEPS = 128; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local Timeline = {}; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Timeline.new(visible, totalCommits, date) local self = {}; local steps = totalCommits < TOTAL_STEPS and totalCommits or TOTAL_STEPS; local stepWidth = (love.graphics.getWidth() - MARGIN_LEFT - MARGIN_RIGHT) / steps; local currentStep = 0; local highlighted = -1; local w, h = 2, -5; --- -- Calculates which timestep the user has clicked on and returns the -- index of the commit which has been mapped to that location. -- @param x - The clicked x-position -- local function calculateCommitIndex(x) return math.floor(totalCommits / (steps / math.floor((x / stepWidth)))); end --- -- Maps a certain commit to a timestep. -- local function calculateTimelineIndex(cindex) return math.floor((cindex / totalCommits) * (steps - 1) + 1); end function self:draw() if not visible then return end for i = 1, steps do if i == highlighted then love.graphics.setColor(200, 0, 0); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2.1); elseif i == currentStep then love.graphics.setColor(80, 80, 80); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2); else love.graphics.setColor(50, 50, 50); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w, h); end love.graphics.setColor(100, 100, 100); love.graphics.setFont(TEXT_FONT); love.graphics.print(date, love.graphics.getWidth() * 0.5 - TEXT_FONT:getWidth(date) * 0.5, love.graphics.getHeight() - 25); love.graphics.setFont(DEFAULT_FONT) love.graphics.setColor(255, 255, 255); end end function self:update(dt) if love.mouse.getY() > love.graphics.getHeight() - HEIGHT then highlighted = math.floor(love.mouse.getX() / stepWidth); else highlighted = -1; end end function self:setCurrentCommit(commit) currentStep = calculateTimelineIndex(commit); end function self:setCurrentDate(ndate) date = ndate; end function self:toggle() visible = not visible; end function self:getCommitAt(x, y) if y > love.graphics.getHeight() - HEIGHT then return calculateCommitIndex(x); end end function self:resize(nx, ny) stepWidth = (nx - MARGIN_LEFT - MARGIN_RIGHT) / steps; end return self; end return Timeline;
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local TEXT_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 15); local DEFAULT_FONT = love.graphics.newFont(12); local MARGIN_LEFT = 10; local MARGIN_RIGHT = 10; local HEIGHT = 30; local TOTAL_STEPS = 128; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local Timeline = {}; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Timeline.new(visible, totalCommits, date) local self = {}; local steps = totalCommits < TOTAL_STEPS and totalCommits or TOTAL_STEPS; local stepWidth = (love.graphics.getWidth() - MARGIN_LEFT - MARGIN_RIGHT) / steps; local currentStep = 0; local highlighted = -1; local w, h = 2, -5; --- -- Calculates which timestep the user has clicked on and returns the -- index of the commit which has been mapped to that location. -- @param x - The clicked x-position -- local function calculateCommitIndex(x) return math.floor(totalCommits / (steps / math.floor((x / stepWidth)))); end --- -- Maps a certain commit to a timestep. -- local function calculateTimelineIndex(cindex) return math.floor((cindex / totalCommits) * (steps - 1) + 1); end function self:draw() if not visible then return end for i = 1, steps do if i == highlighted then love.graphics.setColor(200, 0, 0); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2.1); elseif i == currentStep then love.graphics.setColor(80, 80, 80); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2); else love.graphics.setColor(50, 50, 50); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w, h); end end love.graphics.setColor(100, 100, 100); love.graphics.setFont(TEXT_FONT); love.graphics.print(date, love.graphics.getWidth() * 0.5 - TEXT_FONT:getWidth(date) * 0.5, love.graphics.getHeight() - 25); love.graphics.setFont(DEFAULT_FONT) love.graphics.setColor(255, 255, 255); end function self:update(dt) if love.mouse.getY() > love.graphics.getHeight() - HEIGHT then highlighted = math.floor(love.mouse.getX() / stepWidth); else highlighted = -1; end end function self:setCurrentCommit(commit) currentStep = calculateTimelineIndex(commit); end function self:setCurrentDate(ndate) date = ndate; end function self:toggle() visible = not visible; end function self:getCommitAt(x, y) if y > love.graphics.getHeight() - HEIGHT then return calculateCommitIndex(x); end end function self:resize(nx, ny) stepWidth = (nx - MARGIN_LEFT - MARGIN_RIGHT) / steps; end return self; end return Timeline;
Fix issue with timeline label being drawn multiple times each frame
Fix issue with timeline label being drawn multiple times each frame The code for drawing was accidentally placed in the for loop which draws the single time line steps, therefore causing it to be drawn multiple times.
Lua
mit
rm-code/logivi
2c6140ba58ab3cddba59a3640bc5539869fdb246
mod_register_web/mod_register_web.lua
mod_register_web/mod_register_web.lua
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "util.http"; function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource("templates/"..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[math.random(1, #ops)]; local x, y = math.random(1, 9) repeat y = math.random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request = event.request; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form) local prepped_username = nodeprep(form.username); if usermanager.user_exists(prepped_username, module.host) then return nil, "user-exists"; end return usermanager.create_user(prepped_username, form.password, module.host); end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(form, function (ok, err) if ok then local register_ok, register_err = register_user(form); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; POST = handle_form; }; });
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "util.http"; function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource("templates/"..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[math.random(1, #ops)]; local x, y = math.random(1, 9) repeat y = math.random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request = event.request; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form) local prepped_username = nodeprep(form.username); if usermanager.user_exists(prepped_username, module.host) then return nil, "user-exists"; end return usermanager.create_user(prepped_username, form.password, module.host); end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(form, function (ok, err) if ok then local register_ok, register_err = register_user(form); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; POST = handle_form; }; });
mod_register_web: Indentation fix
mod_register_web: Indentation fix
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
9bbf0621e01c33661c13fb99d7f634f51e56637d
src/System.lua
src/System.lua
local P = {} local Log = require 'Log' function P.quote(...) local function quote(arg) return string.format('%q', tostring(arg)) end return table.concat(table.imap({...}, quote), ' ') end function P.expand(...) return P.pread('*a', 'printf "%s" '..P.quote(...), '%s') end function P.mkpath(...) local sep = '/' local path = {} for _, c in ipairs({...}) do table.insert(path, c) end return table.concat(path, sep) end function P.exec(cmdline, ...) Log.debug2(cmdline, ...) local command = string.format(cmdline, ...) local status = os.execute(command) return status == 0, status % 0xFF end function P.popen(cmdline, ...) Log.debug2(cmdline, ...) local prog = string.format(cmdline, ...) return assert(io.popen(prog)) end function P.pread(format, cmdline, ...) local file = P.popen(cmdline, ...) local out = file:read(format) file:close() return out end function P.getenv(vars) local o = {} for _, v in ipairs(vars) do local value = os.getenv(v) assert(value and #value > 0, string.format("the environment variable '%s' is not set", v)) table.insert(o, value) end return o end function P.rmrf(...) return P.exec('rm -rf %s', P.quote(...)) end function P.mkdir(...) return P.exec('mkdir -p %s', P.quote(...)) end function P.exists(path) return P.exec('test -e "%s"', path) end function P.file_exists(path) return P.exec('test -f "%s"', path) end function P.dir_exists(path) return P.exec('test -d "%s"', path) end function P.is_empty(path) return P.pread('*l', 'cd "%s" && echo *', path) == '*' end return P
local P = {} local Log = require 'Log' function P.quote(...) local function quote(arg) return string.format('%q', tostring(arg)) end return table.concat(table.imap({...}, quote), ' ') end function P.expand(...) return P.pread('*a', 'printf "%s" '..P.quote(...), '%s') end function P.mkpath(...) local sep = '/' local path = {} for _, c in ipairs({...}) do table.insert(path, c) end return table.concat(path, sep) end function P.exec(cmdline, ...) Log.debug2(cmdline, ...) local command = string.format(cmdline, ...) local status = os.execute(command) -- handling API change in Lua 5.2 if type(status) == 'number' then return status == 0, status % 0xFF else return status or false end end function P.popen(cmdline, ...) Log.debug2(cmdline, ...) local prog = string.format(cmdline, ...) return assert(io.popen(prog)) end function P.pread(format, cmdline, ...) local file = P.popen(cmdline, ...) local out = file:read(format) file:close() return out end function P.getenv(vars) local o = {} for _, v in ipairs(vars) do local value = os.getenv(v) assert(value and #value > 0, string.format("the environment variable '%s' is not set", v)) table.insert(o, value) end return o end function P.rmrf(...) return P.exec('rm -rf %s', P.quote(...)) end function P.mkdir(...) return P.exec('mkdir -p %s', P.quote(...)) end function P.exists(path) return P.exec('test -e "%s"', path) end function P.file_exists(path) return P.exec('test -f "%s"', path) end function P.dir_exists(path) return P.exec('test -d "%s"', path) end function P.is_empty(path) return P.pread('*l', 'cd "%s" && echo *', path) == '*' end return P
Fix for os.execute return value change in Lua 5.2
Fix for os.execute return value change in Lua 5.2
Lua
mit
bazurbat/jagen
3ab3815449b9da26e5fc1e3758fe2b95de364fd9
scripts/shaderc.lua
scripts/shaderc.lua
-- -- Copyright 2010-2017 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- project "glslang" kind "StaticLib" local GLSLANG = path.join(BGFX_DIR, "3rdparty/glslang") configuration { "vs2012" } defines { "atoll=_atoi64", "strtoll=_strtoi64", "strtoull=_strtoui64", } configuration { "vs*" } buildoptions { "/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition } configuration { "not vs*" } buildoptions { "-Wno-ignored-qualifiers", "-Wno-inconsistent-missing-override", "-Wno-missing-field-initializers", "-Wno-reorder", "-Wno-shadow", "-Wno-sign-compare", "-Wno-undef", "-Wno-unknown-pragmas", "-Wno-unused-parameter", "-Wno-unused-variable", } configuration { "osx" } buildoptions { "-Wno-c++11-extensions", "-Wno-unused-const-variable", } configuration { "linux-*" } buildoptions { "-Wno-unused-but-set-variable", } configuration {} includedirs { GLSLANG, } files { path.join(GLSLANG, "glslang/**.cpp"), path.join(GLSLANG, "glslang/**.h"), path.join(GLSLANG, "hlsl/**.cpp"), path.join(GLSLANG, "hlsl/**.h"), path.join(GLSLANG, "SPIRV/**.cpp"), path.join(GLSLANG, "SPIRV/**.h"), path.join(GLSLANG, "OGLCompilersDLL/**.cpp"), path.join(GLSLANG, "OGLCompilersDLL/**.h"), } removefiles { path.join(GLSLANG, "glslang/OSDependent/Unix/main.cpp"), path.join(GLSLANG, "glslang/OSDependent/Windows/main.cpp"), } configuration { "windows" } removefiles { path.join(GLSLANG, "glslang/OSDependent/Unix/**.cpp"), path.join(GLSLANG, "glslang/OSDependent/Unix/**.h"), } configuration { "not windows" } removefiles { path.join(GLSLANG, "glslang/OSDependent/Windows/**.cpp"), path.join(GLSLANG, "glslang/OSDependent/Windows/**.h"), } configuration {} project "shaderc" kind "ConsoleApp" local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer") local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp") includedirs { path.join(GLSL_OPTIMIZER, "src"), } links { "bx", } configuration { "Release" } flags { "Optimize", } removeflags { -- GCC 4.9 -O2 + -fno-strict-aliasing don't work together... "OptimizeSpeed", } configuration { "vs*" } includedirs { path.join(GLSL_OPTIMIZER, "src/glsl/msvc"), } defines { -- glsl-optimizer "__STDC__", "__STDC_VERSION__=199901L", "strdup=_strdup", "alloca=_alloca", "isascii=__isascii", } buildoptions { "/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. } configuration { "mingw-*" } targetextension ".exe" configuration { "mingw* or linux or osx" } buildoptions { "-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used. "-Wno-unused-parameter", } removebuildoptions { "-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it. } configuration { "osx" } links { "Cocoa.framework", } configuration { "vs*" } includedirs { path.join(GLSL_OPTIMIZER, "include/c99"), } configuration { "vs20* or mingw*" } links { "psapi", } configuration {} defines { -- fcpp "NINCLUDE=64", "NWORK=65536", "NBUFF=65536", "OLD_PREPROCESSOR=0", } includedirs { path.join(BX_DIR, "include"), path.join(BGFX_DIR, "include"), path.join(BGFX_DIR, "3rdparty/dxsdk/include"), FCPP_DIR, path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"), path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"), path.join(BGFX_DIR, "3rdparty/glslang"), -- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"), path.join(GLSL_OPTIMIZER, "include"), path.join(GLSL_OPTIMIZER, "src/mesa"), path.join(GLSL_OPTIMIZER, "src/mapi"), path.join(GLSL_OPTIMIZER, "src/glsl"), } files { path.join(BGFX_DIR, "tools/shaderc/**.cpp"), path.join(BGFX_DIR, "tools/shaderc/**.h"), path.join(BGFX_DIR, "src/vertexdecl.**"), path.join(BGFX_DIR, "src/shader_spirv.**"), path.join(FCPP_DIR, "**.h"), path.join(FCPP_DIR, "cpp1.c"), path.join(FCPP_DIR, "cpp2.c"), path.join(FCPP_DIR, "cpp3.c"), path.join(FCPP_DIR, "cpp4.c"), path.join(FCPP_DIR, "cpp5.c"), path.join(FCPP_DIR, "cpp6.c"), path.join(FCPP_DIR, "cpp6.c"), path.join(GLSL_OPTIMIZER, "src/mesa/**.c"), path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"), path.join(GLSL_OPTIMIZER, "src/mesa/**.h"), path.join(GLSL_OPTIMIZER, "src/glsl/**.c"), path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/**.h"), path.join(GLSL_OPTIMIZER, "src/util/**.c"), path.join(GLSL_OPTIMIZER, "src/util/**.h"), } removefiles { path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"), path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"), } links { "glslang", } if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then removefiles { path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), } end dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") ) end configuration { "osx or linux*" } links { "pthread", } configuration {} strip()
-- -- Copyright 2010-2017 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- project "glslang" kind "StaticLib" local GLSLANG = path.join(BGFX_DIR, "3rdparty/glslang") configuration { "vs2012" } defines { "atoll=_atoi64", "strtoll=_strtoi64", "strtoull=_strtoui64", } configuration { "vs*" } buildoptions { "/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition "/wd4100", -- error C4100: 'inclusionDepth' : unreferenced formal parameter } configuration { "not vs*" } buildoptions { "-Wno-ignored-qualifiers", "-Wno-inconsistent-missing-override", "-Wno-missing-field-initializers", "-Wno-reorder", "-Wno-shadow", "-Wno-sign-compare", "-Wno-undef", "-Wno-unknown-pragmas", "-Wno-unused-parameter", "-Wno-unused-variable", } configuration { "osx" } buildoptions { "-Wno-c++11-extensions", "-Wno-unused-const-variable", } configuration { "linux-*" } buildoptions { "-Wno-unused-but-set-variable", } configuration {} includedirs { GLSLANG, } files { path.join(GLSLANG, "glslang/**.cpp"), path.join(GLSLANG, "glslang/**.h"), path.join(GLSLANG, "hlsl/**.cpp"), path.join(GLSLANG, "hlsl/**.h"), path.join(GLSLANG, "SPIRV/**.cpp"), path.join(GLSLANG, "SPIRV/**.h"), path.join(GLSLANG, "OGLCompilersDLL/**.cpp"), path.join(GLSLANG, "OGLCompilersDLL/**.h"), } removefiles { path.join(GLSLANG, "glslang/OSDependent/Unix/main.cpp"), path.join(GLSLANG, "glslang/OSDependent/Windows/main.cpp"), } configuration { "windows" } removefiles { path.join(GLSLANG, "glslang/OSDependent/Unix/**.cpp"), path.join(GLSLANG, "glslang/OSDependent/Unix/**.h"), } configuration { "not windows" } removefiles { path.join(GLSLANG, "glslang/OSDependent/Windows/**.cpp"), path.join(GLSLANG, "glslang/OSDependent/Windows/**.h"), } configuration {} project "shaderc" kind "ConsoleApp" local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer") local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp") includedirs { path.join(GLSL_OPTIMIZER, "src"), } links { "bx", } configuration { "Release" } flags { "Optimize", } removeflags { -- GCC 4.9 -O2 + -fno-strict-aliasing don't work together... "OptimizeSpeed", } configuration { "vs*" } includedirs { path.join(GLSL_OPTIMIZER, "src/glsl/msvc"), } defines { -- glsl-optimizer "__STDC__", "__STDC_VERSION__=199901L", "strdup=_strdup", "alloca=_alloca", "isascii=__isascii", } buildoptions { "/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. } configuration { "mingw-*" } targetextension ".exe" configuration { "mingw* or linux or osx" } buildoptions { "-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used. "-Wno-unused-parameter", } removebuildoptions { "-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it. } configuration { "osx" } links { "Cocoa.framework", } configuration { "vs*" } includedirs { path.join(GLSL_OPTIMIZER, "include/c99"), } configuration { "vs20* or mingw*" } links { "psapi", } configuration {} defines { -- fcpp "NINCLUDE=64", "NWORK=65536", "NBUFF=65536", "OLD_PREPROCESSOR=0", } includedirs { path.join(BX_DIR, "include"), path.join(BGFX_DIR, "include"), path.join(BGFX_DIR, "3rdparty/dxsdk/include"), FCPP_DIR, path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"), path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"), path.join(BGFX_DIR, "3rdparty/glslang"), -- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"), path.join(GLSL_OPTIMIZER, "include"), path.join(GLSL_OPTIMIZER, "src/mesa"), path.join(GLSL_OPTIMIZER, "src/mapi"), path.join(GLSL_OPTIMIZER, "src/glsl"), } files { path.join(BGFX_DIR, "tools/shaderc/**.cpp"), path.join(BGFX_DIR, "tools/shaderc/**.h"), path.join(BGFX_DIR, "src/vertexdecl.**"), path.join(BGFX_DIR, "src/shader_spirv.**"), path.join(FCPP_DIR, "**.h"), path.join(FCPP_DIR, "cpp1.c"), path.join(FCPP_DIR, "cpp2.c"), path.join(FCPP_DIR, "cpp3.c"), path.join(FCPP_DIR, "cpp4.c"), path.join(FCPP_DIR, "cpp5.c"), path.join(FCPP_DIR, "cpp6.c"), path.join(FCPP_DIR, "cpp6.c"), path.join(GLSL_OPTIMIZER, "src/mesa/**.c"), path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"), path.join(GLSL_OPTIMIZER, "src/mesa/**.h"), path.join(GLSL_OPTIMIZER, "src/glsl/**.c"), path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/**.h"), path.join(GLSL_OPTIMIZER, "src/util/**.c"), path.join(GLSL_OPTIMIZER, "src/util/**.h"), } removefiles { path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"), path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"), path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"), path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"), } links { "glslang", } if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then removefiles { path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), } end dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") ) end configuration { "osx or linux*" } links { "pthread", } configuration {} strip()
FIxed VS build.
FIxed VS build.
Lua
bsd-2-clause
emoon/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,fluffyfreak/bgfx,Synxis/bgfx,bkaradzic/bgfx,Synxis/bgfx,fluffyfreak/bgfx,attilaz/bgfx,jpcy/bgfx,Synxis/bgfx,jdryg/bgfx,bkaradzic/bgfx,jpcy/bgfx,fluffyfreak/bgfx,emoon/bgfx,mendsley/bgfx,fluffyfreak/bgfx,septag/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,attilaz/bgfx,septag/bgfx,septag/bgfx,mendsley/bgfx,jpcy/bgfx,mendsley/bgfx,jdryg/bgfx,jpcy/bgfx,mmicko/bgfx,bkaradzic/bgfx,attilaz/bgfx,jdryg/bgfx,emoon/bgfx,mmicko/bgfx,bkaradzic/bgfx,MikePopoloski/bgfx,mmicko/bgfx,MikePopoloski/bgfx,jdryg/bgfx
cf9b9faa433f230a63cf9a8c1a56cbd256b1c5dd
core/packagemanager.lua
core/packagemanager.lua
local lfs = require("lfs") local catalogueURL = "https://raw.githubusercontent.com/sile-typesetter/sile-packages/master/packages.lua" local packageHome = tostring(SYSTEM_SILE_PATH) .. "/packagemanager/" local catalogueHome = packageHome .. "catalogue.lua" local installedCatalogue = packageHome .. "installed.lua" local http = require("ssl.https") local recentlyUpdated = false local recentlyReloaded = false local origcpath = package.cpath -- for idempotence local origpath = package.path SILE.PackageManager = { installed = {}, Catalogue = {} } local function loadInSandbox(untrusted_code) if _ENV then -- simple Lua 5.2 version check local env = {} local untrusted_function, message = load(untrusted_code, nil, 't', env) if not untrusted_function then return nil, message end return pcall(untrusted_function) else if untrusted_code:byte(1) == 27 then return nil, "binary bytecode prohibited" end local untrusted_function, message = load(untrusted_code) if not untrusted_function then return nil, message end -- luacheck: globals setfenv env -- (At least there is in Lua 5.1) setfenv(untrusted_function, env) return pcall(untrusted_function) end end local function dumpTable(tbl) if type(tbl) == 'table' then local str = '{ ' for k, v in pairs(tbl) do if type(k) ~= 'number' then k = '"'..k..'"' end str = str .. '['..k..'] = ' .. dumpTable(v) .. ',' end return str .. '} ' else -- This only works because we are only storing strings! return '"' .. tostring(tbl) .. '"' end end local function fixupPaths() local paths = "" local cpaths = "" for pkg, _ in pairs(SILE.PackageManager.installed) do paths = paths .. packageHome .. pkg .. '/?.lua;' cpaths = cpaths .. packageHome .. pkg .. "/?."..SHARED_LIB_EXT.. ";" end package.path = origpath:gsub("?.lua", "?.lua;"..paths, 1) package.cpath = origcpath .. ";" .. cpaths end local function saveInstalled() local dump = dumpTable(SILE.PackageManager.installed) local file, err = io.open(installedCatalogue, "w") if err then SU.error("Could not write installed package list at"..installedCatalogue..": "..err) end file:write("return "..dump) file:close() fixupPaths() end local function updateCatalogue () if not lfs.attributes(packageHome) then if not lfs.mkdir(packageHome) then SU.error("Error making package manager home directory: "..packageHome) end end print("Loading catalogue from "..catalogueURL) local result, statuscode, _ = http.request(catalogueURL) if statuscode ~= 200 then SU.error("Could not load catalogue from "..catalogueURL..": "..statuscode) end local file, err = io.open(catalogueHome, "w") if err then SU.error("Could not write package catalogue at"..catalogueHome..": "..err) end print("Writing "..(#result).." bytes to "..catalogueHome) file:write(result) file:close() recentlyUpdated = true recentlyReloaded = false end local function loadInstalledCatalogue() local file = io.open(installedCatalogue, "r") if file ~= nil then local contents = file:read("*all") local success, res = loadInSandbox(contents) if not success then SU.error("Error loading installed package list: "..res) end SILE.PackageManager.installed = res end end local function reloadCatalogue() local file = io.open(catalogueHome, "r") if file ~= nil then local contents = file:read("*all") local success, res = loadInSandbox(contents) if not success then SU.error("Error loading package catalogue: "..res) end SILE.PackageManager.Catalogue = res end loadInstalledCatalogue() print("Package catalogue reloaded") recentlyReloaded = true end -- These functions are global so they can be used from the REPL -- luacheck: ignore updatePackage -- luacheck: ignore installPackage function updatePackage(packageName, branch) local target = packageHome .. packageName -- Are we already there? if SILE.PackageManager.installed[packageName] == branch and branch ~= "master" then print("Nothing to do!") return true end local cwd = lfs.currentdir() local _, err = lfs.chdir(target) if err then SU.warn("Package directory "..target.." went away! Trying again...") SILE.PackageManager.installed[packageName] = nil saveInstalled() installPackage(packageName) end local ret = os.execute("git pull") if not ret then SU.error("Error updating repository for package "..packageName..": "..ret) end ret = os.execute("git checkout "..branch) if not ret then SU.error("Error updating repository for package "..packageName..": "..ret) end lfs.chdir(cwd) SILE.PackageManager.installed[packageName] = branch saveInstalled() end function installPackage(packageName) if not recentlyUpdated then updateCatalogue() end if not recentlyReloaded then reloadCatalogue() end if not SILE.PackageManager.Catalogue[packageName] then -- Add support for URL-based package names later. SU.error("Can't install "..packageName..": package not known") end local metadata = SILE.PackageManager.Catalogue[packageName] -- Check dependencies if metadata.depends then for _, pkg in ipairs(metadata.depends) do if not SILE.PackageManager.installed[pkg] then print(packageName.." requires "..pkg..", installing that...") installPackage(pkg) end end end -- Clone repo in temp directory if metadata.repository then local branch = metadata.version or "master" local target = packageHome .. packageName if lfs.attributes(target) then updatePackage(packageName, branch) else local ret = os.execute("git clone -c advice.detachedHead=false -b "..branch.." "..metadata.repository.." "..target) if not ret then -- This should return status code but it's returning true for me... SU.error("Error cloning repository for package "..packageName..": "..ret) end end SILE.PackageManager.installed[packageName] = branch saveInstalled() end end -- Set up the world loadInstalledCatalogue() fixupPaths()
local lfs = require("lfs") local catalogueURL = "https://raw.githubusercontent.com/sile-typesetter/sile-packages/master/packages.lua" local packageHome = tostring(SYSTEM_SILE_PATH) .. "/packagemanager/" local catalogueHome = packageHome .. "catalogue.lua" local installedCatalogue = packageHome .. "installed.lua" local http = require("ssl.https") local recentlyUpdated = false local recentlyReloaded = false local origcpath = package.cpath -- for idempotence local origpath = package.path SILE.PackageManager = { installed = {}, Catalogue = {} } local function loadInSandbox(untrusted_code) if _ENV then -- simple Lua 5.2 version check local env = {} local untrusted_function, message = load(untrusted_code, nil, 't', env) if not untrusted_function then return nil, message end return pcall(untrusted_function) else if untrusted_code:byte(1) == 27 then return nil, "binary bytecode prohibited" end local untrusted_function, message = load(untrusted_code) if not untrusted_function then return nil, message end -- luacheck: globals setfenv env -- (At least there is in Lua 5.1) setfenv(untrusted_function, env) return pcall(untrusted_function) end end local function dumpTable(tbl) if type(tbl) == 'table' then local str = '{ ' for k, v in pairs(tbl) do if type(k) ~= 'number' then k = '"'..k..'"' end str = str .. '['..k..'] = ' .. dumpTable(v) .. ',' end return str .. '} ' else -- This only works because we are only storing strings! return '"' .. tostring(tbl) .. '"' end end local function fixupPaths() local paths = "" local cpaths = "" for pkg, _ in pairs(SILE.PackageManager.installed) do paths = paths .. packageHome .. pkg .. '/?.lua;' cpaths = cpaths .. packageHome .. pkg .. "/?."..SHARED_LIB_EXT.. ";" end if paths:len() >= 1 then package.path = paths .. ";" .. origpath end if cpaths:len() >= 1 then package.cpath = cpaths .. ";" .. origcpath end end local function saveInstalled() local dump = dumpTable(SILE.PackageManager.installed) local file, err = io.open(installedCatalogue, "w") if err then SU.error("Could not write installed package list at"..installedCatalogue..": "..err) end file:write("return "..dump) file:close() fixupPaths() end local function updateCatalogue () if not lfs.attributes(packageHome) then if not lfs.mkdir(packageHome) then SU.error("Error making package manager home directory: "..packageHome) end end print("Loading catalogue from "..catalogueURL) local result, statuscode, _ = http.request(catalogueURL) if statuscode ~= 200 then SU.error("Could not load catalogue from "..catalogueURL..": "..statuscode) end local file, err = io.open(catalogueHome, "w") if err then SU.error("Could not write package catalogue at"..catalogueHome..": "..err) end print("Writing "..(#result).." bytes to "..catalogueHome) file:write(result) file:close() recentlyUpdated = true recentlyReloaded = false end local function loadInstalledCatalogue() local file = io.open(installedCatalogue, "r") if file ~= nil then local contents = file:read("*all") local success, res = loadInSandbox(contents) if not success then SU.error("Error loading installed package list: "..res) end SILE.PackageManager.installed = res end end local function reloadCatalogue() local file = io.open(catalogueHome, "r") if file ~= nil then local contents = file:read("*all") local success, res = loadInSandbox(contents) if not success then SU.error("Error loading package catalogue: "..res) end SILE.PackageManager.Catalogue = res end loadInstalledCatalogue() print("Package catalogue reloaded") recentlyReloaded = true end -- These functions are global so they can be used from the REPL -- luacheck: ignore updatePackage -- luacheck: ignore installPackage function updatePackage(packageName, branch) local target = packageHome .. packageName -- Are we already there? if SILE.PackageManager.installed[packageName] == branch and branch ~= "master" then print("Nothing to do!") return true end local cwd = lfs.currentdir() local _, err = lfs.chdir(target) if err then SU.warn("Package directory "..target.." went away! Trying again...") SILE.PackageManager.installed[packageName] = nil saveInstalled() installPackage(packageName) end local ret = os.execute("git pull") if not ret then SU.error("Error updating repository for package "..packageName..": "..ret) end ret = os.execute("git checkout "..branch) if not ret then SU.error("Error updating repository for package "..packageName..": "..ret) end lfs.chdir(cwd) SILE.PackageManager.installed[packageName] = branch saveInstalled() end function installPackage(packageName) if not recentlyUpdated then updateCatalogue() end if not recentlyReloaded then reloadCatalogue() end if not SILE.PackageManager.Catalogue[packageName] then -- Add support for URL-based package names later. SU.error("Can't install "..packageName..": package not known") end local metadata = SILE.PackageManager.Catalogue[packageName] -- Check dependencies if metadata.depends then for _, pkg in ipairs(metadata.depends) do if not SILE.PackageManager.installed[pkg] then print(packageName.." requires "..pkg..", installing that...") installPackage(pkg) end end end -- Clone repo in temp directory if metadata.repository then local branch = metadata.version or "master" local target = packageHome .. packageName if lfs.attributes(target) then updatePackage(packageName, branch) else local ret = os.execute("git clone -c advice.detachedHead=false -b "..branch.." "..metadata.repository.." "..target) if not ret then -- This should return status code but it's returning true for me... SU.error("Error cloning repository for package "..packageName..": "..ret) end end SILE.PackageManager.installed[packageName] = branch saveInstalled() end end -- Set up the world loadInstalledCatalogue() fixupPaths()
fix(packages): Stop legacy package manager from adding empty paths
fix(packages): Stop legacy package manager from adding empty paths
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
c231e6bc25b1ccb55adb105fc5487ef35f0eea0c
examples/Lua-cURL/browser.lua
examples/Lua-cURL/browser.lua
----------------------------------------------------------------------------- -- A Browser Class for easy Web Automation with Lua-cURL -- Author: Kai Uwe Jesussek -- RCS ID: $Id: browser.lua,v 0.1 2011/03/11 23:55:20 kai Exp $ ----------------------------------------------------------------------------- local cURL = require("lcurl.cURL") local string = require("string") local table = require("table") local base = _G USERAGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" --windows xp internet explorer 6.0 --this function joins 2 urls (absolute or relative) function url_join(_base, _url) assert(type(_url) == "string") if _base == nil or _base == "" then return _url end assert(type(_base) == "string") local base = url_split(_base) local url = url_split(_url) local protocol = base.protocol local host = base.host local path = "" local port = "" if url.protocol ~= nil then protocol = url.protocol if url.path ~= nil then path = url.path end if url.port ~= nil and url.port ~= "" then port = url.port end if url.host ~= nil then host = url.host end else if _url:sub(1,2) == "//" then --set host and path host, port, path = _url:match("^//([^;/%?]+)(:?%d*)(/?.*)") if path == nil then path = "" end elseif _url:sub(1,1) == "/" then port = base.port --replace path path = _url else --combine paths :( path = base.path:match("^(.*)/[^/]*") port = base.port if path ~= nil then path = path .. "/" .. _url else path = _url end end end local ret = protocol .. "://" .. host .. port .. path return ret end --this function splits an url into its parts function url_split(_url) --print(_url) local ret = {} --test ipv6 ret.protocol, ret.host, ret.port, ret.path = _url:match("^(https?)://(%[[0-9a-fA-F:]+%])(:?%d*)(.*)$") if ret.host == nil then --fall back to ipv4 ret.protocol, ret.host, ret.port, ret.path = _url:match("^(https?)://([^:/]+)(:?%d*)(.*)$") end return ret end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary -- taken from Lua Socket and added underscore to ignore (MIT-License) ----------------------------------------------------------------------------- function escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary -- taken from Lua Socket ----------------------------------------------------------------------------- function unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end -- from encodes a key, value dictionary table function tblencode (_arguments) local ret = "" if _arguments == nil or next(_arguments) == nil then -- no _arguments or empty _arguments? return ret end --iterate over each key -> value pairs and urlencode them for key, vals in pairs(_arguments) do if type(vals) ~= "table" then vals = {vals} end for i,val in ipairs(vals) do ret = ret .. "&"..key.. "=" ..escape(val) end end --cut off leadin '&' return string.sub(ret,2) end --function helper for result --taken from luasocket page (MIT-License) local function build_w_cb(t) return function(s,len) table.insert(t, s) return len,nil end end --function helper for headers --taken from luasocket page (MIT-License) local function h_build_w_cb(t) return function(s,len) --stores the received data in the table t --prepare header data name, value = s:match("(.-): (.+)") if name and value then t.headers[name] = value:gsub("[\n\r]", "") else code, codemessage = string.match(s, "^HTTP/.* (%d+) (.+)$") if code and codemessage then t.code = tonumber(code) t.codemessage = codemessage:gsub("[\n\r]", "") end end return len,nil end end --the browser easy to use interface browser = {} function browser:new(_share) if _share == nil then _share = cURL.share_init() _share:setopt_share("COOKIE") _share:setopt_share("DNS") end local object = { url = nil, share = _share} setmetatable(object, {__index = browser}) return object end --this function sets the proxy variables for the prepare function function browser:setProxy(_proxy, _proxytype) self.proxy = _proxy self.proxytype = _proxytype print("setting proxy", self.proxy, self.proxytype) end --this function prepares a request function browser:prepare(post_data, urlencoded) local req = cURL.easy_init() req:setopt_share(self.share) req:setopt_url(self.url) req:setopt_useragent(USERAGENT) if self.proxy ~= nil and self.proxytype ~= nil then req:setopt_proxy(self.proxy) req:setopt_proxytype(self.proxytype) end if self.caInfoPath ~= nil then req:setopt_cainfo(self.caInfoPath) end if post_data ~= nil then if urlencoded and type(post_data) == "table" then post_data = tblencode(post_data) end if type(post_data) == "string" then req:setopt_post(1) req:setopt_postfields(post_data) req:setopt_postfieldsize(#post_data) else req:post(post_data) end end return req end --this function sets the url function browser:setUrl(url) --appends a leading / to url if needed if self.url and self.url:match("^(https?://[^/]+)$") then self.url = self.url .. "/" end self.url = url_join(self.url or "", url) end --opens a webpage :) only the first parameter is required function browser:open(url, post_data, redirect, urlencoded) local redirect = redirect or true local urlencoded = urlencoded == nil local ret = {} response_body = {} ret.headers = {} self:setUrl(url) local req = self:prepare(post_data, urlencoded) req:perform({headerfunction=h_build_w_cb(ret), writefunction=build_w_cb(response_body)}) self:setUrl(url) ret.body = table.concat(response_body) if redirect and ret.headers and (ret.headers.Location or ret.headers.location) and (ret.code == 301 or ret.code == 302) then return self:open(url_join(self.url, ret.headers.Location or ret.headers.location), nil, extra_headers, redirect) end return ret end --opens a webpage :) only the first and second parameters are required function browser:save(url, filename, post_data) local ret = {} ret.headers = {} self:setUrl(url) local req = self:prepare(post_data, false) file = io.open(filename) req:perform({headerfunction=h_build_w_cb(ret), writefunction=function(str) file:write(str) end }) file:close() end function browser:setCaInfo(path) self.caInfoPath = path end --[[ usage examples: -- b = browser:new() -- resp = b:open("http://www.html-kit.com/tools/cookietester/") -- print(resp.body) -- table.foreach(resp.headers, print) --]] b = browser:new() resp = b:open("http://www.html-kit.com/tools/cookietester/") print(resp.body) table.foreach(resp.headers, print)
----------------------------------------------------------------------------- -- A Browser Class for easy Web Automation with Lua-cURL -- Author: Kai Uwe Jesussek -- RCS ID: $Id: browser.lua,v 0.1 2011/03/11 23:55:20 kai Exp $ ----------------------------------------------------------------------------- local cURL = require("lcurl.cURL") local string = require("string") local table = require("table") local base = _G USERAGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" --windows xp internet explorer 6.0 --this function joins 2 urls (absolute or relative) function url_join(_base, _url) assert(type(_url) == "string") if _base == nil or _base == "" then return _url end assert(type(_base) == "string") local base = url_split(_base) local url = url_split(_url) local protocol = base.protocol local host = base.host local path = "" local port = "" if url.protocol ~= nil then protocol = url.protocol if url.path ~= nil then path = url.path end if url.port ~= nil and url.port ~= "" then port = url.port end if url.host ~= nil then host = url.host end else if _url:sub(1,2) == "//" then --set host and path host, port, path = _url:match("^//([^;/%?]+)(:?%d*)(/?.*)") if path == nil then path = "" end elseif _url:sub(1,1) == "/" then port = base.port --replace path path = _url else --combine paths :( path = base.path:match("^(.*)/[^/]*") port = base.port if path ~= nil then path = path .. "/" .. _url else path = _url end end end local ret = protocol .. "://" .. host .. port .. path return ret end --this function splits an url into its parts function url_split(_url) --print(_url) local ret = {} --test ipv6 ret.protocol, ret.host, ret.port, ret.path = _url:match("^(https?)://(%[[0-9a-fA-F:]+%])(:?%d*)(.*)$") if ret.host == nil then --fall back to ipv4 ret.protocol, ret.host, ret.port, ret.path = _url:match("^(https?)://([^:/]+)(:?%d*)(.*)$") end return ret end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary -- taken from Lua Socket and added underscore to ignore (MIT-License) ----------------------------------------------------------------------------- function escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary -- taken from Lua Socket ----------------------------------------------------------------------------- function unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end -- from encodes a key, value dictionary table function tblencode (_arguments) local ret = "" if _arguments == nil or next(_arguments) == nil then -- no _arguments or empty _arguments? return ret end --iterate over each key -> value pairs and urlencode them for key, vals in pairs(_arguments) do if type(vals) ~= "table" then vals = {vals} end for i,val in ipairs(vals) do ret = ret .. "&"..key.. "=" ..escape(val) end end --cut off leadin '&' return string.sub(ret,2) end --function helper for result --taken from luasocket page (MIT-License) local function build_w_cb(t) return function(s) table.insert(t, s) return #s,nil end end --function helper for headers --taken from luasocket page (MIT-License) local function h_build_w_cb(t) return function(s) --stores the received data in the table t --prepare header data name, value = s:match("(.-): (.+)") if name and value then t.headers[name] = value:gsub("[\n\r]", "") else code, codemessage = string.match(s, "^HTTP/.* (%d+) (.+)$") if code and codemessage then t.code = tonumber(code) t.codemessage = codemessage:gsub("[\n\r]", "") end end return #s,nil end end --the browser easy to use interface browser = {} function browser:new(_share) if _share == nil then _share = cURL.share_init() _share:setopt_share("COOKIE") _share:setopt_share("DNS") end local object = { url = nil, share = _share} setmetatable(object, {__index = browser}) return object end --this function sets the proxy variables for the prepare function function browser:setProxy(_proxy, _proxytype) self.proxy = _proxy self.proxytype = _proxytype print("setting proxy", self.proxy, self.proxytype) end --this function prepares a request function browser:prepare(post_data, urlencoded) local req = cURL.easy_init() req:setopt_share(self.share) req:setopt_url(self.url) req:setopt_useragent(USERAGENT) if self.proxy ~= nil and self.proxytype ~= nil then req:setopt_proxy(self.proxy) req:setopt_proxytype(self.proxytype) end if self.caInfoPath ~= nil then req:setopt_cainfo(self.caInfoPath) end if post_data ~= nil then if urlencoded and type(post_data) == "table" then post_data = tblencode(post_data) end if type(post_data) == "string" then req:setopt_post(1) req:setopt_postfields(post_data) req:setopt_postfieldsize(#post_data) else req:post(post_data) end end return req end --this function sets the url function browser:setUrl(url) --appends a leading / to url if needed if self.url and self.url:match("^(https?://[^/]+)$") then self.url = self.url .. "/" end self.url = url_join(self.url or "", url) end --opens a webpage :) only the first parameter is required function browser:open(url, post_data, redirect, urlencoded) local redirect = redirect or true local urlencoded = urlencoded == nil local ret = {} response_body = {} ret.headers = {} self:setUrl(url) local req = self:prepare(post_data, urlencoded) req:perform({headerfunction=h_build_w_cb(ret), writefunction=build_w_cb(response_body)}) self:setUrl(url) ret.body = table.concat(response_body) if redirect and ret.headers and (ret.headers.Location or ret.headers.location) and (ret.code == 301 or ret.code == 302) then return self:open(url_join(self.url, ret.headers.Location or ret.headers.location), nil, extra_headers, redirect) end return ret end --opens a webpage :) only the first and second parameters are required function browser:save(url, filename, post_data) local ret = {} ret.headers = {} self:setUrl(url) local req = self:prepare(post_data, false) file = io.open(filename) req:perform({headerfunction=h_build_w_cb(ret), writefunction=function(str) file:write(str) end }) file:close() end function browser:setCaInfo(path) self.caInfoPath = path end --[[ usage examples: -- b = browser:new() -- resp = b:open("http://www.html-kit.com/tools/cookietester/") -- print(resp.body) -- table.foreach(resp.headers, print) --]]
Fix. Lua-cURL/browser.lua example compatibility with `lcurl.cURL`
Fix. Lua-cURL/browser.lua example compatibility with `lcurl.cURL`
Lua
mit
Lua-cURL/Lua-cURLv3,moteus/lua-lcurl,Lua-cURL/Lua-cURLv3,Lua-cURL/Lua-cURLv3,moteus/lua-lcurl
04621b505622a0690330e393b69ffd5626c46f54
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/api/now&full=true' table.insert(urls, url) end grl.fetch(urls, "radiofrance_now_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.stations then local url = 'http://www.' .. stations[index] .. '.fr/api/now&full=true' grl.warning ('Could not fetch ' .. url .. ' failed') grl.callback() return end local media = create_media(stations[index], json.stations[1]) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, station) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. 'hautdebit.mp3' media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks 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 * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/api/now&full=true' table.insert(urls, url) end grl.fetch(urls, "radiofrance_now_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.stations then local url = 'http://www.' .. stations[index] .. '.fr/api/now&full=true' grl.warning ('Could not fetch ' .. url .. ' failed') grl.callback() return end local media = create_media(stations[index], json.stations[1]) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, station) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end if id == 'franceinfo' then media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. '-32k.mp3' else media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. 'hautdebit.mp3' end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks return media end
radiofrance: Fix "France Info" URL
radiofrance: Fix "France Info" URL Another special case...
Lua
lgpl-2.1
MathieuDuponchelle/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,GNOME/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins
27f73b38a4ceccbd30001ad9f6e2bf77ae3fcb7e
config/nvim/lua/plugins/nvimtree.lua
config/nvim/lua/plugins/nvimtree.lua
local nnoremap = require("utils").nnoremap local view = require("nvim-tree.view") _G.NvimTreeConfig = {} vim.g.nvim_tree_follow = 1 vim.g.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "●", staged = "✓", unmerged = "", renamed = "➜", untracked = "★", deleted = "", ignored = "◌" }, folder = { arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "" }, lsp = { hint = "", info = "", warning = "", error = "" } } function NvimTreeConfig.find_toggle() if view.win_open() then view.close() else vim.cmd("NvimTreeFindFile") end end nnoremap("<leader>k", "<CMD>lua NvimTreeConfig.find_toggle()<CR>") view.width = 40
local nvimtree = require("nvim-tree") local nnoremap = require("utils").nnoremap local view = require("nvim-tree.view") _G.NvimTreeConfig = {} vim.g.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "●", staged = "✓", unmerged = "", renamed = "➜", untracked = "★", deleted = "", ignored = "◌" }, folder = { arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "" }, lsp = { hint = "", info = "", warning = "", error = "" } } function NvimTreeConfig.find_toggle() if view.win_open() then view.close() else vim.cmd("NvimTreeFindFile") end end nnoremap("<leader>k", "<CMD>lua NvimTreeConfig.find_toggle()<CR>") view.width = 40 nvimtree.setup { disable_netrw = true, hijack_netrw = true, auto_close = false, lsp_diagnostics = true, update_focused_file = { enable = true, update_cwd = false }, view = { width = 40, side = "left", auto_resize = true } }
fix(vim): fix nvim-tree config issues
fix(vim): fix nvim-tree config issues
Lua
mit
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
a99508fe9857d9f5c096973d9ca0c2c545eed606
core/inputs-texlike.lua
core/inputs-texlike.lua
SILE.inputs.TeXlike = {} local epnf = require( "epnf" ) local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 ) SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1 SILE.inputs.TeXlike.parser = function (_ENV) local _ = WS^0 local sep = lpeg.S(",;") * _ local quotedString = (P("\"") * C((1-lpeg.S("\""))^1) * P("\"")) local value = (quotedString + (1-lpeg.S(",;]"))^1 ) local myID = C( SILE.inputs.TeXlike.identifier + lpeg.P(1) ) / function (t) return t end local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset) local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1) local lineEndLineStartSpace = (lpeg.S(" ")^0 * lpeg.S("\r\n")^1 * lpeg.S(" ")^0)^-1 START "document"; document = V("stuff") * (-1 + E("Unexpected character at end of input")) text = (anything + C(WS))^1 / function(...) return table.concat({...}, "") end stuff = Cg(V"environment" + ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^-1) /function () return "" end) -- Don't bother telling me about comments + V("text") + V"bracketed_stuff" + V"command")^0 bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected")) command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0 * lineEndLineStartSpace)-P("\\end{") environment = P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}") * lineEndLineStartSpace * V("stuff") * (P("\\end{") * ( Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) + E("Environment mismatch") ) * (P("}") * _) + E("Environment begun but never ended")) end local linecache = {} local lno, col, lastpos local function resetCache() lno = 1 col = 1 lastpos = 0 linecache = { { lno = 1, pos = 1} } end local function getline( s, p ) start = 1 lno = 1 if p > lastpos then lno = linecache[#linecache].lno start = linecache[#linecache].pos + 1 col = 1 else for j = 1,#linecache-1 do if linecache[j+1].pos >= p then lno = linecache[j].lno col = p - linecache[j].pos return lno,col end end end for i = start, p do if string.sub( s, i, i ) == "\n" then lno = lno + 1 col = 1 linecache[#linecache+1] = { pos = i, lno = lno } lastpos = i end col = col + 1 end return lno, col end local function massage_ast(t,doc) -- Sort out pos if type(t) == "string" then return t end if t.pos then t.line, t.col = getline(doc, t.pos) end if t.id == "document" then return massage_ast(t[1],doc) end if t.id == "text" then return t[1] end if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end for k,v in ipairs(t) do if v.id == "stuff" then local val = massage_ast(v,doc) SU.splice(t, k,k, val) else t[k] = massage_ast(v,doc) end end return t end function SILE.inputs.TeXlike.process(fn) local fh = io.open(fn) resetCache() local doc = fh:read("*all") local t = SILE.inputs.TeXlike.docToTree(doc) local root = SILE.documentState.documentClass == nil if root then if not(t.tag == "document") then SU.error("Should begin with \\begin{document}") end SILE.inputs.common.init(fn, t) end SILE.process(t) if root and not SILE.preamble then SILE.documentState.documentClass:finish() end end local _parser function SILE.inputs.TeXlike.rebuildParser() _parser = epnf.define(SILE.inputs.TeXlike.parser) end SILE.inputs.TeXlike.rebuildParser() function SILE.inputs.TeXlike.docToTree(doc) local t = epnf.parsestring(_parser, doc) -- a document always consists of one stuff t = t[1][1] if not t then return end resetCache() t = massage_ast(t,doc) return t end
SILE.inputs.TeXlike = {} local epnf = require( "epnf" ) local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 ) SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1 SILE.inputs.TeXlike.parser = function (_ENV) local _ = WS^0 local sep = lpeg.S(",;") * _ local quotedString = (P("\"") * C((1-lpeg.S("\""))^1) * P("\"")) local value = (quotedString + (1-lpeg.S(",;]"))^1 ) local myID = C( SILE.inputs.TeXlike.identifier + lpeg.P(1) ) / function (t) return t end local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset) local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1) local lineEndLineStartSpace = (lpeg.S(" ")^0 * lpeg.S("\r\n")^1 * lpeg.S(" ")^0)^-1 local comment = ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^-1) /function () return "" end) START "document"; document = V("stuff") * (-1 + E("Unexpected character at end of input")) text = (anything + C(WS))^1 / function(...) return table.concat({...}, "") end stuff = Cg(V"environment" + comment + V("text") + V"bracketed_stuff" + V"command")^0 bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected")) command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0 * lineEndLineStartSpace)-P("\\end{") environment = comment^0 * P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}") * lineEndLineStartSpace * V("stuff") * (P("\\end{") * ( Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) + E("Environment mismatch") ) * (P("}") * _) + E("Environment begun but never ended")) end local linecache = {} local lno, col, lastpos local function resetCache() lno = 1 col = 1 lastpos = 0 linecache = { { lno = 1, pos = 1} } end local function getline( s, p ) start = 1 lno = 1 if p > lastpos then lno = linecache[#linecache].lno start = linecache[#linecache].pos + 1 col = 1 else for j = 1,#linecache-1 do if linecache[j+1].pos >= p then lno = linecache[j].lno col = p - linecache[j].pos return lno,col end end end for i = start, p do if string.sub( s, i, i ) == "\n" then lno = lno + 1 col = 1 linecache[#linecache+1] = { pos = i, lno = lno } lastpos = i end col = col + 1 end return lno, col end local function massage_ast(t,doc) -- Sort out pos if type(t) == "string" then return t end if t.pos then t.line, t.col = getline(doc, t.pos) end if t.id == "document" then return massage_ast(t[1],doc) end if t.id == "text" then return t[1] end if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end for k,v in ipairs(t) do if v.id == "stuff" then local val = massage_ast(v,doc) SU.splice(t, k,k, val) else t[k] = massage_ast(v,doc) end end return t end function SILE.inputs.TeXlike.process(fn) local fh = io.open(fn) resetCache() local doc = fh:read("*all") local t = SILE.inputs.TeXlike.docToTree(doc) local root = SILE.documentState.documentClass == nil if root then if not(t.tag == "document") then SU.error("Should begin with \\begin{document}") end SILE.inputs.common.init(fn, t) end SILE.process(t) if root and not SILE.preamble then SILE.documentState.documentClass:finish() end end local _parser function SILE.inputs.TeXlike.rebuildParser() _parser = epnf.define(SILE.inputs.TeXlike.parser) end SILE.inputs.TeXlike.rebuildParser() function SILE.inputs.TeXlike.docToTree(doc) local t = epnf.parsestring(_parser, doc) -- a document always consists of one stuff t = t[1][1] if not t then return end resetCache() t = massage_ast(t,doc) return t end
This seems to allow comments before the \begin{document}, fixes #99
This seems to allow comments before the \begin{document}, fixes #99
Lua
mit
alerque/sile,alerque/sile,simoncozens/sile,WAKAMAZU/sile_fe,neofob/sile,anthrotype/sile,anthrotype/sile,WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,alerque/sile,neofob/sile,alerque/sile,WAKAMAZU/sile_fe,anthrotype/sile,simoncozens/sile,anthrotype/sile,simoncozens/sile,neofob/sile,neofob/sile
d6b008dbcdc925d4bce0d2629304e92ef8771a09
sveta.lua
sveta.lua
-- sveta.lua -- -- -- space[4].enabled = 1 -- space[4].index[0].type = "HASH" -- space[4].index[0].unique = 1 -- space[4].index[0].key_field[0].fieldno = 0 -- space[4].index[0].key_field[0].type = "NUM" -- space[4].index[0].key_field[1].fieldno = 1 -- space[4].index[0].key_field[1].type = "STR" -- space[4].index[1].type = "AVLTREE" -- space[4].index[1].unique = 0 -- space[4].index[1].key_field[0].fieldno = 0 -- space[4].index[1].key_field[0].type = "NUM" -- space[4].index[1].key_field[1].fieldno = 3 -- space[4].index[1].key_field[1].type = "NUM" -- space[4].index[2].type = "AVLTREE" -- space[4].index[2].unique = 0 -- space[4].index[2].key_field[0].fieldno = 0 -- space[4].index[2].key_field[0].type = "NUM" -- space[4].index[2].key_field[1].fieldno = 4 -- space[4].index[2].key_field[1].type = "NUM" -- space[4].index[2].key_field[2].fieldno = 2 -- space[4].index[2].key_field[2].type = "NUM" -- -- tuple structure: -- uid, query, total_count, last_ts, 2_week_count, latest_counter(today), ... , earliest_counter(2 weeks ago) local space_no = 4 local delete_chunk = 100 local max_query_size = 1024 local seconds_per_day = 86400 local two_weeks = 14 local index_of_user_id = 0 local index_of_query = 1 local index_of_total_counter = 2 local index_of_last_ts = 3 local index_of_2_week_counter = 4 local index_of_latest_counter = 5 local index_of_earliest_counter = 18 local timeout = 0.005 local max_attempts = 5 function add_query(user_id, query) if string.len(query) > max_query_size then error("too long query") end uid = box.unpack('i', user_id) local tuple = box.update(space_no, {uid, query}, "+p=p+p+p", index_of_total_counter, 1, index_of_last_ts, box.time(), index_of_2_week_counter, 1, index_of_latest_counter, 1) if tuple == nil then local new_tuple = {} new_tuple[index_of_user_id] = uid new_tuple[index_of_query] = query new_tuple[index_of_total_counter] = 1 new_tuple[index_of_last_ts] = box.time() new_tuple[index_of_2_week_counter] = 1 new_tuple[index_of_latest_counter] = 1 for i=index_of_latest_counter+1,index_of_earliest_counter do new_tuple[i] = 0 end return box.insert(space_no, new_tuple) end return tuple end function delete_query(user_id, query) return box.delete(space_no, box.unpack('i', user_id), query) end function delete_all(user_id) uid = box.unpack('i', user_id) while true do -- delete by chuncks of dalete_chunk len local tuples = {box.select_limit(space_no, 1, 0, delete_chunk, uid)} if( table.getn(tuples) == 0 ) then break end for _, tuple in ipairs(tuples) do box.delete(space_no, uid, tuple[1]) end end end local function select_queries_by_index(uid, limit, index) resp = {} local i = 0 for tuple in box.space[space_no].index[index]:iterator(box.index.REQ, uid) do if i == lim then break end table.insert(resp, {tuple[index_of_user_id], tuple[index_of_query], tuple[index_of_total_counter], tuple[index_of_last_ts], tuple[index_of_2_week_counter]}) i = i + 1 end return unpack(resp) end function select_recent(user_id, limit) uid = box.unpack('i', user_id) lim = box.unpack('i', limit) return select_queries_by_index(uid, limit, 1) end function select_2_week_popular(user_id, limit) uid = box.unpack('i', user_id) lim = box.unpack('i', limit) return select_queries_by_index(uid, limit, 2) end local function move_counters(tuple) new_tuple = {} new_tuple[0] = box.unpack('i',tuple[0]) new_tuple[1] = tuple[1] for i = 2,index_of_earliest_counter do new_tuple[i] = box.unpack('i',tuple[i]) end new_tuple[index_of_2_week_counter] = new_tuple[index_of_2_week_counter] - new_tuple[index_of_earliest_counter] for i=index_of_earliest_counter,index_of_latest_counter+1,-1 do new_tuple[i] = new_tuple[i - 1] end new_tuple[index_of_latest_counter] = 0 return box.replace(space_no, new_tuple) end local function move_all_counters() local n = 0 print('start moving counters') local start_time = box.time() for t in box.space[space_no].index[0]:iterator(box.index.ALL) do local count = 0 while true do local status, result = pcall(move_counters, t) if status then --success break else --exception count = count + 1 if count == max_attempts then print('max attempts reached for moving counters for user ', t[0], ' query ', t[1]) break end box.fiber.sleep(timeout) end end n = n + 1 if n == 100 then box.fiber.sleep(timeout) n = 0 end end print('finish moving counters. elapsed ', box.time() - start_time, ' seconds') end local function move_all_counters_fiber() while true do local time = box.time() local sleep_time = math.ceil(time/seconds_per_day)*seconds_per_day - time + 1 print('sleep for ', sleep_time, ' seconds') box.fiber.sleep(sleep_time) move_all_counters() end end box.fiber.wrap(move_all_counters_fiber)
-- sveta.lua -- implements aggregation of abstract data by update date and number of updates -- grouping by id and data -- allows desc sorting by date or by (2_week_count + total_count), -- where 2_week_count is number of updates for last two weeks, -- this updates automatically by fiber every 24 hours -- -- -- space[4].enabled = 1 -- space[4].index[0].type = "HASH" -- space[4].index[0].unique = 1 -- space[4].index[0].key_field[0].fieldno = 0 -- space[4].index[0].key_field[0].type = "NUM" -- space[4].index[0].key_field[1].fieldno = 1 -- space[4].index[0].key_field[1].type = "STR" -- space[4].index[1].type = "AVLTREE" -- space[4].index[1].unique = 0 -- space[4].index[1].key_field[0].fieldno = 0 -- space[4].index[1].key_field[0].type = "NUM" -- space[4].index[1].key_field[1].fieldno = 3 -- space[4].index[1].key_field[1].type = "NUM" -- space[4].index[2].type = "AVLTREE" -- space[4].index[2].unique = 0 -- space[4].index[2].key_field[0].fieldno = 0 -- space[4].index[2].key_field[0].type = "NUM" -- space[4].index[2].key_field[1].fieldno = 4 -- space[4].index[2].key_field[1].type = "NUM" -- space[4].index[2].key_field[2].fieldno = 2 -- space[4].index[2].key_field[2].type = "NUM" -- -- tuple structure: -- uid, query, total_count, last_ts, 2_week_count, latest_counter(today), ... , earliest_counter(2 weeks ago) local space_no = 4 local delete_chunk = 100 local max_query_size = 1024 local seconds_per_day = 86400 local two_weeks = 14 local index_of_user_id = 0 local index_of_query = 1 local index_of_total_counter = 2 local index_of_last_ts = 3 local index_of_2_week_counter = 4 local index_of_latest_counter = 5 local index_of_earliest_counter = 18 local timeout = 0.005 local max_attempts = 5 function add_query(user_id, query) if string.len(query) > max_query_size then error("too long query") end uid = box.unpack('i', user_id) local tuple = box.update(space_no, {uid, query}, "+p=p+p+p", index_of_total_counter, 1, index_of_last_ts, box.time(), index_of_2_week_counter, 1, index_of_latest_counter, 1) if tuple == nil then local new_tuple = {} new_tuple[index_of_user_id] = uid new_tuple[index_of_query] = query new_tuple[index_of_total_counter] = 1 new_tuple[index_of_last_ts] = box.time() new_tuple[index_of_2_week_counter] = 1 new_tuple[index_of_latest_counter] = 1 for i=index_of_latest_counter+1,index_of_earliest_counter do new_tuple[i] = 0 end return box.insert(space_no, new_tuple) end return tuple end function delete_query(user_id, query) return box.delete(space_no, box.unpack('i', user_id), query) end function delete_all(user_id) uid = box.unpack('i', user_id) while true do -- delete by chuncks of dalete_chunk len local tuples = {box.select_limit(space_no, 1, 0, delete_chunk, uid)} if( #tuples == 0 ) then break end for _, tuple in ipairs(tuples) do box.delete(space_no, uid, tuple[1]) end end end local function select_queries_by_index(uid, limit, index) local resp = {} local i = 0 for tuple in box.space[space_no].index[index]:iterator(box.index.REQ, uid) do if i == limit then break end table.insert(resp, {tuple[index_of_user_id], tuple[index_of_query], tuple[index_of_total_counter], tuple[index_of_last_ts], tuple[index_of_2_week_counter]}) i = i + 1 end return unpack(resp) end function select_recent(user_id, limit) local uid = box.unpack('i', user_id) local lim = box.unpack('i', limit) return select_queries_by_index(uid, lim, 1) end function select_2_week_popular(user_id, limit) local uid = box.unpack('i', user_id) local lim = box.unpack('i', limit) return select_queries_by_index(uid, lim, 2) end local function move_counters(tuple) local new_tuple = {} new_tuple[0] = box.unpack('i',tuple[0]) new_tuple[1] = tuple[1] for i = 2,index_of_earliest_counter do new_tuple[i] = box.unpack('i',tuple[i]) end new_tuple[index_of_2_week_counter] = new_tuple[index_of_2_week_counter] - new_tuple[index_of_earliest_counter] for i=index_of_earliest_counter,index_of_latest_counter+1,-1 do new_tuple[i] = new_tuple[i - 1] end new_tuple[index_of_latest_counter] = 0 return box.replace(space_no, new_tuple) end local function move_all_counters() local n = 0 print('start moving counters') local start_time = box.time() for t in box.space[space_no].index[0]:iterator(box.index.ALL) do local count = 0 while true do local status, result = pcall(move_counters, t) if status then --success break else --exception count = count + 1 if count == max_attempts then print('max attempts reached for moving counters for user ', t[0], ' query ', t[1]) break end box.fiber.sleep(timeout) end end n = n + 1 if n == 100 then box.fiber.sleep(timeout) n = 0 end end print('finish moving counters. elapsed ', box.time() - start_time, ' seconds') end local function move_all_counters_fiber() while true do local time = box.time() local sleep_time = math.ceil(time/seconds_per_day)*seconds_per_day - time + 1 print('sleep for ', sleep_time, ' seconds') box.fiber.sleep(sleep_time) move_all_counters() end end box.fiber.wrap(move_all_counters_fiber)
sveta.lua: fix + small optimization
sveta.lua: fix + small optimization
Lua
bsd-2-clause
BHYCHIK/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua,mailru/tntlua
71eb855b21394219b8ccfcf292b3c9cf3bcd9636
src/extensions/cp/battery.lua
src/extensions/cp/battery.lua
--- === cp.battery === --- --- Provides access to various properties of the battery. Each of these properties --- is a `cp.prop`, so it can be watched for changes. For example: --- --- ```lua --- local battery = require("cp.battery") --- battery.powerSupply:watch(function(value) --- print("Now using "..value) --- end) --- ``` --- --- This will `print` "Now using AC Power" or "Now using Battery Power" whenever the --- power supply changes. --- --- By default the watcher initialises in a "stopped" state, and must be started for --- the `cp.prop` watchers to trigger. --- cp.battery.amperage <cp.prop: number; read-only> --- Constant --- Returns the amount of current flowing through the battery, in mAh. --- --- Notes: --- * A number containing the amount of current flowing through the battery. The value may be: --- ** Less than zero if the battery is being discharged (i.e. the computer is running on battery power) --- ** Zero if the battery is being neither charged nor discharded --- ** Greater than zero if the bettery is being charged --- cp.battery.capacity <cp.prop: number; read-only> --- Constant --- Returns the current capacity of the battery in mAh. --- --- Notes: --- * This is the measure of how charged the battery is, vs the value of `cp.battery.maxCapacity()`. --- cp.battery.cycles <cp.prop: number; read-only> --- Constant --- Returns the number of discharge cycles of the battery. --- --- Notes: --- * One cycle is a full discharge of the battery, followed by a full charge. This may also be an aggregate of many smaller discharge-then-charge cycles (e.g. 10 iterations of discharging the battery from 100% to 90% and then charging back to 100% each time, is considered to be one cycle). --- cp.battery.designCapacity <cp.prop: number; read-only> --- Constant --- Returns the design capacity of the battery in mAh. --- cp.battery.health <cp.prop: string; read-only> --- Constant --- Returns the health status of the battery; either "Good", "Fair" or "Poor", --- as determined by the Apple Smart Battery controller. --- cp.battery.healthCondition <cp.prop: string; read-only> --- Constant --- Returns the health condition status of the battery: --- `nil` if there are no health conditions to report, or a string containing either: --- * "Check Battery" --- * "Permanent Battery Failure" --- cp.battery.isCharged <cp.prop: boolean; read-only> --- Constant --- Checks if the battery is fully charged. --- cp.battery.isCharging <cp.prop: boolean; read-only> --- Constant --- Checks if the battery is currently charging. --- cp.battery.isFinishingCharge <cp.prop: boolean | string; read-only> --- Constant --- Checks if the battery is trickle charging; --- either `true` if trickle charging, `false` if charging faster, or `"n/a" if the battery is not charging at all. --- cp.battery.maxCapacity <cp.prop; number; read-only> --- Constant --- Returns the maximum capacity of the battery in mAh. --- --- Notes: --- * This may exceed the value of `cp.battery.designCapacity()` due to small variations in the production chemistry vs the design. --- cp.battery.otherBatteryInfo <cp.prop: table | nil; read-only> --- Constant --- Returns information about non-PSU batteries (e.g. bluetooth accessories). If none are found, `nil` is returned. --- cp.battery.percentage <cp.prop; string; read-only> --- Constant --- Returns the current source of power; either `"AC Power"`, `"Battery Power"` or `"Off Line"`. --- cp.battery.psuSerial <cp.prop: number; read-only> --- Constant --- Returns the serial number of the attached power supply, or `0` if not present. --- cp.battery.timeRemaining <cp.prop: number; read-only> --- Constant --- The amount of battery life remaining, in minuges. --- --- Notes: --- * The return value may be: --- ** Greater than zero to indicate the number of minutes remaining. --- ** `-1` if the remaining batttery life is being calculated. --- ** `-2` if there is unlimited time remaining (i.e. the system is on AC power). --- cp.battery.timeToFullCharge <cp.prop; number; read-only> --- Constant --- Returns the time remaining for the battery to be fully charged, in minutes, or `-`` if still being calculated. --- cp.battery.voltage <cp.prop: number; read-only> --- Constant --- Returns the current voltage of the battery in mV. --- cp.battery.watts <cp.prop: number; read-only> --- Constant --- Returns the power entering or leaving the battery, in W. --- Discharging will be less than zero, charging greater than zero. local require = require local log = require "hs.logger".new "cpBattery" local battery = require "hs.battery" local prop = require "cp.prop" local mod = {} -- EXCLUDED -> table -- Constant -- Table of excluded items. local EXCLUDED = { ["privateBluetoothBatteryInfo"] = true, ["getAll"] = true, ["psuSerialString"] = true, } --- cp.battery._watcher -> hs.battery.watcher object --- Variable --- The battery watcher. mod._watcher = battery.watcher.new(function() for key,value in pairs(mod) do if prop.is(value) then local ok, result = xpcall(function() value:update() end, debug.traceback) if not ok then log.ef("Error while updating '%s'", key, result) end end end end) --- cp.battery.start() -> none --- Function --- Starts the battery watcher. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.start() mod._watcher:start() end --- cp.battery.stop() -> none --- Function --- Stops the battery watcher. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.stop() mod._watcher:stop() end -- init() -> none -- Function -- Initialise the module. -- -- Parameters: -- * None -- -- Returns: -- * The module local function init() for key,value in pairs(battery) do if EXCLUDED[key] ~= true and type(value) == "function" then mod[key] = prop(value):label(string.format("cp.battery: %s", key)) end end return mod end return init()
--- === cp.battery === --- --- Provides access to various properties of the battery. Each of these properties --- is a `cp.prop`, so it can be watched for changes. For example: --- --- ```lua --- local battery = require("cp.battery") --- battery.powerSupply:watch(function(value) --- print("Now using "..value) --- end) --- ``` --- --- This will `print` "Now using AC Power" or "Now using Battery Power" whenever the --- power supply changes. --- --- By default the watcher initialises in a "stopped" state, and must be started for --- the `cp.prop` watchers to trigger. --- cp.battery.amperage <cp.prop: number; read-only> --- Constant --- Returns the amount of current flowing through the battery, in mAh. --- --- Notes: --- * A number containing the amount of current flowing through the battery. The value may be: --- ** Less than zero if the battery is being discharged (i.e. the computer is running on battery power) --- ** Zero if the battery is being neither charged nor discharded --- ** Greater than zero if the bettery is being charged --- cp.battery.capacity <cp.prop: number; read-only> --- Constant --- Returns the current capacity of the battery in mAh. --- --- Notes: --- * This is the measure of how charged the battery is, vs the value of `cp.battery.maxCapacity()`. --- cp.battery.cycles <cp.prop: number; read-only> --- Constant --- Returns the number of discharge cycles of the battery. --- --- Notes: --- * One cycle is a full discharge of the battery, followed by a full charge. This may also be an aggregate of many smaller discharge-then-charge cycles (e.g. 10 iterations of discharging the battery from 100% to 90% and then charging back to 100% each time, is considered to be one cycle). --- cp.battery.designCapacity <cp.prop: number; read-only> --- Constant --- Returns the design capacity of the battery in mAh. --- cp.battery.health <cp.prop: string; read-only> --- Constant --- Returns the health status of the battery; either "Good", "Fair" or "Poor", --- as determined by the Apple Smart Battery controller. --- cp.battery.healthCondition <cp.prop: string; read-only> --- Constant --- Returns the health condition status of the battery: --- `nil` if there are no health conditions to report, or a string containing either: --- * "Check Battery" --- * "Permanent Battery Failure" --- cp.battery.isCharged <cp.prop: boolean; read-only> --- Constant --- Checks if the battery is fully charged. --- cp.battery.isCharging <cp.prop: boolean; read-only> --- Constant --- Checks if the battery is currently charging. --- cp.battery.isFinishingCharge <cp.prop: boolean | string; read-only> --- Constant --- Checks if the battery is trickle charging; --- either `true` if trickle charging, `false` if charging faster, or `"n/a" if the battery is not charging at all. --- cp.battery.maxCapacity <cp.prop; number; read-only> --- Constant --- Returns the maximum capacity of the battery in mAh. --- --- Notes: --- * This may exceed the value of `cp.battery.designCapacity()` due to small variations in the production chemistry vs the design. --- cp.battery.otherBatteryInfo <cp.prop: table | nil; read-only> --- Constant --- Returns information about non-PSU batteries (e.g. bluetooth accessories). If none are found, `nil` is returned. --- cp.battery.percentage <cp.prop; string; read-only> --- Constant --- Returns the current source of power; either `"AC Power"`, `"Battery Power"` or `"Off Line"`. --- cp.battery.psuSerial <cp.prop: number; read-only> --- Constant --- Returns the serial number of the attached power supply, or `0` if not present. --- cp.battery.timeRemaining <cp.prop: number; read-only> --- Constant --- The amount of battery life remaining, in minuges. --- --- Notes: --- * The return value may be: --- ** Greater than zero to indicate the number of minutes remaining. --- ** `-1` if the remaining batttery life is being calculated. --- ** `-2` if there is unlimited time remaining (i.e. the system is on AC power). --- cp.battery.timeToFullCharge <cp.prop; number; read-only> --- Constant --- Returns the time remaining for the battery to be fully charged, in minutes, or `-`` if still being calculated. --- cp.battery.voltage <cp.prop: number; read-only> --- Constant --- Returns the current voltage of the battery in mV. --- cp.battery.watts <cp.prop: number; read-only> --- Constant --- Returns the power entering or leaving the battery, in W. --- Discharging will be less than zero, charging greater than zero. local require = require local log = require "hs.logger".new "cpBattery" local battery = require "hs.battery" local prop = require "cp.prop" local mod = {} -- EXCLUDED -> table -- Constant -- Table of excluded items. local EXCLUDED = { ["privateBluetoothBatteryInfo"] = true, ["getAll"] = true, ["psuSerialString"] = true, } --- cp.battery._watcher -> hs.battery.watcher object --- Variable --- The battery watcher. mod._watcher = battery.watcher.new(function() for key,value in pairs(mod) do if prop.is(value) then local ok, result = xpcall(function() value:update() end, debug.traceback) if not ok then log.ef("Error while updating '%s'", key, result) end end end end) --- cp.battery.start() -> none --- Function --- Starts the battery watcher. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.start() mod._watcher:start() end --- cp.battery.stop() -> none --- Function --- Stops the battery watcher. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.stop() mod._watcher:stop() end -- init() -> none -- Function -- Initialise the module. -- -- Parameters: -- * None -- -- Returns: -- * The module local function init() for key,value in pairs(battery) do if EXCLUDED[key] ~= true and type(value) == "function" then mod[key] = prop(function() return value() end):label(string.format("cp.battery: %s", key)) end end return mod end return init()
Fixed a bug that was breaking Disk Auto-mount Plugin
Fixed a bug that was breaking Disk Auto-mount Plugin - Hammerspoon recently changed `hs.battery` so its more strict in terms of valid arguments - so if you pass in arguments to a function that's expecting none, you'll now get a Lua error. `cp.prop` was passing in two arguments, which was breaking `cp.battery`. This fixes that. - Closes #3016
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
38fd48cbe6ca13b6dea9c1cc374a0875d5058ae0
UCDchecking/checking.lua
UCDchecking/checking.lua
local actions = { ["Chat"] = { {"s", "NoMuted"}, }, ["RobHouse"] = { {"a", "RobHouse", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["EnterHouse"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Jetpack"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoDead"}, }, ["JobVehicle"] = { {"a", "RobHouse", "AFK"}, {"ld", 3}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Builder"] = { {"a", "RobHouse", "AFK"}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoDead", "NoArrest", "NoJailed", "NoJetpack", "NoDead"} }, } function canPlayerDoAction(plr, action) if (not plr or not action or not actions[action] or not isElement(plr) or plr.type ~= "player" or plr.account.guest) then return false end local currentActivity = exports.UCDactions:getAction(plr) -- plr:getData("a") for _, dat in pairs(actions[action]) do for i, dat2 in pairs(dat) do if (dat[1] == "a" and dat2 == currentActivity) then exports.UCDdx:new(plr, "An activity you're doing blocks this action", 255, 0, 0) return false end if (dat[1] == "w") then if (plr.wantedLevel >= dat2) then exports.UCDdx:new(plr, "Your wanted level blocks this action", 255, 0, 0) return false end end if (dat[1] == "i" and plr.interior ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your interior blocks this action", 255, 0, 0) return false end if (dat[1] == "d" and plr.dimension ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your dimension blocks this action", 255, 0, 0) return false end if (dat[1] == "s") then if (dat2 == "NoVehicle" and plr.vehicle) then exports.UCDdx:new(plr, "Being in a vehicle blocks this action", 255, 0, 0) return false end if (dat2 == "NoDead" and plr.dead) then exports.UCDdx:new(plr, "Being dead blocks this action", 255, 0, 0) return false end if (dat2 == "NoJetpack" and plr:doesHaveJetpack()) then exports.UCDdx:new(plr, "Having a jetpack blocks this action", 255, 0, 0) return false end if (dat2 == "NoMuted" and plr.muted) then exports.UCDdx:new(plr, "Being muted blocks this action", 255, 0, 0) return false end if (dat2 == "NoArrest" and exports.UCDlaw:isPlayerArrested(plr)) then exports.UCDdx:new(plr, "Being arrested blocks this action", 255, 0, 0) return false end end end end return true end
local actions = { ["Chat"] = { {"s", "NoMuted"}, }, ["RobHouse"] = { {"a", "RobHouse", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["EnterHouse"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Jetpack"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoDead", "NoCustody"}, {"w", 1}, }, ["JobVehicle"] = { {"a", "RobHouse", "AFK"}, {"ld", 3}, {"i", 0}, {"d", 0}, {"w", 2}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Builder"] = { {"a", "RobHouse", "AFK"}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoDead", "NoArrest", "NoJailed", "NoJetpack", "NoDead", "NoCustody"}, }, } function canPlayerDoAction(plr, action) if (not plr or not action or not actions[action] or not isElement(plr) or plr.type ~= "player" or plr.account.guest) then return false end local currentActivity = exports.UCDactions:getAction(plr) -- plr:getData("a") for _, dat in pairs(actions[action]) do for i, dat2 in pairs(dat) do if (dat[1] == "a" and dat2 == currentActivity) then exports.UCDdx:new(plr, "An activity you're doing blocks this action", 255, 0, 0) return false end if (dat[1] == "w" and i ~= 1) then if (plr.wantedLevel >= dat2) then exports.UCDdx:new(plr, "Your wanted level blocks this action", 255, 0, 0) return false end end if (dat[1] == "i" and plr.interior ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your interior blocks this action", 255, 0, 0) return false end if (dat[1] == "d" and plr.dimension ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your dimension blocks this action", 255, 0, 0) return false end if (dat[1] == "s") then if (dat2 == "NoVehicle" and plr.vehicle) then exports.UCDdx:new(plr, "Being in a vehicle blocks this action", 255, 0, 0) return false end if (dat2 == "NoDead" and plr.dead) then exports.UCDdx:new(plr, "Being dead blocks this action", 255, 0, 0) return false end if (dat2 == "NoJetpack" and plr:doesHaveJetpack()) then exports.UCDdx:new(plr, "Having a jetpack blocks this action", 255, 0, 0) return false end if (dat2 == "NoMuted" and plr.muted) then exports.UCDdx:new(plr, "Being muted blocks this action", 255, 0, 0) return false end if (dat2 == "NoArrest" and exports.UCDlaw:isPlayerArrested(plr)) then exports.UCDdx:new(plr, "Being arrested blocks this action", 255, 0, 0) return false end if (dat2 == "NoJailed" and exports.UCDjail:isPlayerJailed(plr)) then exports.UCDdx:new(plr, "Being in jail blocks this action", 255, 0, 0) return false end if (dat2 == "NoCustody" and #exports.UCDlaw:getPlayerArrests(plr) > 0) then exports.UCDdx:new(plr, "Having players in your custody blocks this action", 255, 0, 0) return false end end end end return true end
UCDchecking
UCDchecking - Added custody check - Added jailed check - Fixed the wanted level check
Lua
mit
nokizorque/ucd,nokizorque/ucd
9d4ee7e9e1cd76cb7cc14beef2b1c792db36ce90
libs/sys/luasrc/sys/mtdow.lua
libs/sys/luasrc/sys/mtdow.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 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$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 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$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_IMAGE } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s write '%s' '%s'" % { self.MTD, self.IMAGEFIFO, devicename } ) end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
More mtdow fixes
More mtdow fixes
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci
bc1fc28e5ca0354b17612d6d3d8fdf63f434ab3e
core/harfbuzz-shaper.lua
core/harfbuzz-shaper.lua
if not SILE.shapers then SILE.shapers = { } end local hb = require("justenoughharfbuzz") local bit32 = require("bit32-compat") SILE.settings.declare({ name = "harfbuzz.subshapers", type = "string or nil", default = "", help = "Comma-separated shaper list to pass to Harfbuzz" }) SILE.require("core/base-shaper") local smallTokenSize = 20 -- Small words will be cached local shapeCache = {} local _key = function(options, text) return table.concat({ text, options.family, options.language, options.script, options.size, ("%d"):format(options.weight), options.style, options.variant, options.features, options.direction, options.filename },";") end local substwarnings = {} local usedfonts = {} SILE.shapers.harfbuzz = SILE.shapers.base { shapeToken = function (self, text, options) local items if #text < smallTokenSize then items = shapeCache[_key(options, text)]; if items then return items end end if #text < 1 then return {} end -- work around segfault in HB < 1.0.4 local face = SILE.font.cache(options, self.getFace) if not face then SU.error("Could not find requested font "..options.." or any suitable substitutes") end if not(options.filename) and face.family ~= options.family and not substwarnings[options.family] then substwarnings[options.family] = true SU.warn("Font family '"..options.family.."' not available, falling back to '"..face.family.."'") end usedfonts[face] = true items = { hb._shape(text, face.data, face.index, options.script, options.direction, options.language, options.size, options.features, SILE.settings.get("harfbuzz.subshapers") or "" ) } for i = 1, #items do local j = (i == #items) and #text or items[i+1].index items[i].text = text:sub(items[i].index+1, j) -- Lua strings are 1-indexed end if #text < smallTokenSize then shapeCache[_key(options, text)] = items end return items end, getFace = function(opts) local face = SILE.fontManager:face(opts) SU.debug("fonts", "Resolved font family '"..opts.family.."' -> "..(face and face.filename)) if not face.filename then SU.error("Couldn't find face '"..opts.family.."'") end if SILE.makeDeps then SILE.makeDeps:add(face.filename) end if bit32.rshift(face.index, 16) ~= 0 then SU.warn("GX feature in '"..opts.family.."' is not supported, fallback to regular font face.") face.index = bit32.band(face.index, 0xff) end local fh, err = io.open(face.filename, "rb") if err then SU.error("Can't open font file '"..face.filename.."': "..err) end face.data = fh:read("*all") return face end, preAddNodes = function(self, items, nnodeValue) -- Check for complex nodes for i=1, #items do if items[i].y_offset or items[i].x_offset or items[i].width ~= items[i].glyphAdvance then nnodeValue.complex = true; break end end end, addShapedGlyphToNnodeValue = function (self, nnodevalue, shapedglyph) if nnodevalue.complex then if not nnodevalue.items then nnodevalue.items = {} end nnodevalue.items[#nnodevalue.items+1] = shapedglyph end if not nnodevalue.glyphString then nnodevalue.glyphString = {} end if not nnodevalue.glyphNames then nnodevalue.glyphNames = {} end table.insert(nnodevalue.glyphString, shapedglyph.gid) table.insert(nnodevalue.glyphNames, shapedglyph.name) end, debugVersions = function() local ot = SILE.require("core/opentype-parser") print("Harfbuzz version: "..hb.version()) print("Shapers enabled: ".. table.concat({hb.shapers()}, ", ")) pcall( function () icu = require("justenoughicu") end) if icu then print("ICU support enabled") end print("") print("Fonts used:") for face,_ in pairs(usedfonts) do local font = ot.parseFont(face) local version = "Unknown version" if font and font.names and font.names[5] then for l,v in pairs(font.names[5]) do version = v[1]; break end end print(face.filename..":"..face.index, version) end end } SILE.shaper = SILE.shapers.harfbuzz
if not SILE.shapers then SILE.shapers = { } end local hb = require("justenoughharfbuzz") local bit32 = require("bit32-compat") SILE.settings.declare({ name = "harfbuzz.subshapers", type = "string or nil", default = "", help = "Comma-separated shaper list to pass to Harfbuzz" }) SILE.require("core/base-shaper") local smallTokenSize = 20 -- Small words will be cached local shapeCache = {} local _key = function(options, text) return table.concat({ text, options.family, options.language, options.script, options.size, ("%d"):format(options.weight), options.style, options.variant, options.features, options.direction, options.filename },";") end local substwarnings = {} local usedfonts = {} SILE.shapers.harfbuzz = SILE.shapers.base { shapeToken = function (self, text, options) local items if #text < smallTokenSize then items = shapeCache[_key(options, text)]; if items then return items end end local face = SILE.font.cache(options, self.getFace) if self:checkHBProblems(text, face) then return {} end if not face then SU.error("Could not find requested font "..options.." or any suitable substitutes") end if not(options.filename) and face.family ~= options.family and not substwarnings[options.family] then substwarnings[options.family] = true SU.warn("Font family '"..options.family.."' not available, falling back to '"..face.family.."'") end usedfonts[face] = true items = { hb._shape(text, face.data, face.index, options.script, options.direction, options.language, options.size, options.features, SILE.settings.get("harfbuzz.subshapers") or "" ) } for i = 1, #items do local j = (i == #items) and #text or items[i+1].index items[i].text = text:sub(items[i].index+1, j) -- Lua strings are 1-indexed end if #text < smallTokenSize then shapeCache[_key(options, text)] = items end return items end, getFace = function(opts) local face = SILE.fontManager:face(opts) SU.debug("fonts", "Resolved font family '"..opts.family.."' -> "..(face and face.filename)) if not face.filename then SU.error("Couldn't find face '"..opts.family.."'") end if SILE.makeDeps then SILE.makeDeps:add(face.filename) end if bit32.rshift(face.index, 16) ~= 0 then SU.warn("GX feature in '"..opts.family.."' is not supported, fallback to regular font face.") face.index = bit32.band(face.index, 0xff) end local fh, err = io.open(face.filename, "rb") if err then SU.error("Can't open font file '"..face.filename.."': "..err) end face.data = fh:read("*all") return face end, preAddNodes = function(self, items, nnodeValue) -- Check for complex nodes for i=1, #items do if items[i].y_offset or items[i].x_offset or items[i].width ~= items[i].glyphAdvance then nnodeValue.complex = true; break end end end, addShapedGlyphToNnodeValue = function (self, nnodevalue, shapedglyph) if nnodevalue.complex then if not nnodevalue.items then nnodevalue.items = {} end nnodevalue.items[#nnodevalue.items+1] = shapedglyph end if not nnodevalue.glyphString then nnodevalue.glyphString = {} end if not nnodevalue.glyphNames then nnodevalue.glyphNames = {} end table.insert(nnodevalue.glyphString, shapedglyph.gid) table.insert(nnodevalue.glyphNames, shapedglyph.name) end, debugVersions = function() local ot = SILE.require("core/opentype-parser") print("Harfbuzz version: "..hb.version()) print("Shapers enabled: ".. table.concat({hb.shapers()}, ", ")) pcall( function () icu = require("justenoughicu") end) if icu then print("ICU support enabled") end print("") print("Fonts used:") for face,_ in pairs(usedfonts) do local font = ot.parseFont(face) local version = "Unknown version" if font and font.names and font.names[5] then for l,v in pairs(font.names[5]) do version = v[1]; break end end print(face.filename..":"..face.index, version) end end, checkHBProblems = function (self, text, face) if hb.version_lessthan(1,0,4) and #text < 1 then return true end if hb.version_lessthan(2,3,0) and hb.get_table(face.data, face.index, "CFF "):len() > 0 and not substwarnings["CFF "] then SU.warn("Vertical spacing of CFF fonts may be subtly inconsistent between systems. Upgrade to Harfbuzz 2.3.0 if you need absolute consistency.") substwarnings["CFF "] = true end return false end } SILE.shaper = SILE.shapers.harfbuzz
improvement(shaper): Add warning where vertical metrics may differ
improvement(shaper): Add warning where vertical metrics may differ See #639 - if we fall back to Freetype to process CFF fonts, we may get subtly different metrics. We just warn the user and tell them how to fix it, because it's not usually a big deal (unless you're running tests).
Lua
mit
alerque/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile
bd6b5b50062264d79cad67626896f4d8c899f28f
mods/fishing/crafting.lua
mods/fishing/crafting.lua
----------------------------------------------------------------------------------------------- -- Fishing - Mossmanikin's version - Recipes 0.0.8 ----------------------------------------------------------------------------------------------- -- License (code & textures): WTFPL -- Contains code from: animal_clownfish, animal_fish_blue_white, fishing (original), stoneage -- Looked at code from: -- Dependencies: default, farming -- Supports: animal_clownfish, animal_fish_blue_white, animal_rat, mobs ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- Fishing Pole ----------------------------------------------------------------------------------------------- -- Wooden Fishing Pole minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "farming:string"}, {"group:stick", "", "farming:string"}, } }) if minetest.get_modpath("moreblocks") ~= nil then minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "moreblocks:rope" }, {"group:stick", "", "moreblocks:rope" }, } }) end if minetest.get_modpath("ropes") ~= nil then minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "ropes:rope" }, {"group:stick", "", "ropes:rope" }, } }) end -- Mithril Fishing Pole if minetest.get_modpath("moreore") ~= nil then minetest.register_craft({ output = "fishing:pole_perfect", recipe = { {"", "", "moreoress:mithril_ingot" }, {"", "moreoress:mithril_ingot", "mobs:spider_cobweb" }, {"moreoress:mithril_ingot", "", "mobs:spider_cobweb" }, } }) end ----------------------------------------------------------------------------------------------- -- Roasted Fish ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:fish", recipe = "fishing:fish_raw", cooktime = 2, }) ----------------------------------------------------------------------------------------------- -- Wheat Seed ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "shapeless", output = "farming:seed_wheat", recipe = {"farming:wheat"}, }) ----------------------------------------------------------------------------------------------- -- Sushi ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "shapeless", output = "fishing:sushi", recipe = {"fishing:fish_raw", "farming:seed_wheat", "flowers:seaweed" }, }) minetest.register_craft({ type = "shapeless", output = "fishing:sushi", recipe = {"fishing:fish_raw", "farming:seed_wheat", "seaplants:kelpgreen" }, }) ----------------------------------------------------------------------------------------------- -- Roasted Shark ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:shark_cooked", recipe = "fishing:shark", cooktime = 2, }) ----------------------------------------------------------------------------------------------- -- Roasted Pike ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:pike_cooked", recipe = "fishing:pike", cooktime = 2, })
----------------------------------------------------------------------------------------------- -- Fishing - Mossmanikin's version - Recipes 0.0.8 ----------------------------------------------------------------------------------------------- -- License (code & textures): WTFPL -- Contains code from: animal_clownfish, animal_fish_blue_white, fishing (original), stoneage -- Looked at code from: -- Dependencies: default, farming -- Supports: animal_clownfish, animal_fish_blue_white, animal_rat, mobs ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- Fishing Pole ----------------------------------------------------------------------------------------------- -- Wooden Fishing Pole minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "farming:string"}, {"group:stick", "", "farming:string"}, } }) if minetest.get_modpath("moreblocks") ~= nil then minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "moreblocks:rope" }, {"group:stick", "", "moreblocks:rope" }, } }) end if minetest.get_modpath("ropes") ~= nil then minetest.register_craft({ output = "fishing:pole", recipe = { {"", "", "group:stick" }, {"", "group:stick", "ropes:rope" }, {"group:stick", "", "ropes:rope" }, } }) end -- Mithril Fishing Pole if minetest.get_modpath("moreores") ~= nil then minetest.register_craft({ output = "fishing:pole_perfect", recipe = { {"", "", "moreores:mithril_ingot" }, {"", "moreores:mithril_ingot", "mobs:spider_cobweb" }, {"moreores:mithril_ingot", "", "mobs:spider_cobweb" }, } }) end ----------------------------------------------------------------------------------------------- -- Roasted Fish ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:fish", recipe = "fishing:fish_raw", cooktime = 2, }) ----------------------------------------------------------------------------------------------- -- Wheat Seed ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "shapeless", output = "farming:seed_wheat", recipe = {"farming:wheat"}, }) ----------------------------------------------------------------------------------------------- -- Sushi ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "shapeless", output = "fishing:sushi", recipe = {"fishing:fish_raw", "farming:seed_wheat", "flowers:seaweed" }, }) minetest.register_craft({ type = "shapeless", output = "fishing:sushi", recipe = {"fishing:fish_raw", "farming:seed_wheat", "seaplants:kelpgreen" }, }) ----------------------------------------------------------------------------------------------- -- Roasted Shark ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:shark_cooked", recipe = "fishing:shark", cooktime = 2, }) ----------------------------------------------------------------------------------------------- -- Roasted Pike ----------------------------------------------------------------------------------------------- minetest.register_craft({ type = "cooking", output = "fishing:pike_cooked", recipe = "fishing:pike", cooktime = 2, })
Fix perfect fishing pole recipe
Fix perfect fishing pole recipe
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server
b984513ca7aea8f0e83337a5807dfc953058b5ff
xmake/rules/utils/inherit_links/inherit_links.lua
xmake/rules/utils/inherit_links/inherit_links.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file inherit_links.lua -- -- add values from target options function _add_values_from_targetopts(values, target, name) for _, opt in ipairs(target:orderopts()) do table.join2(values, table.wrap(opt:get(name))) end end -- add values from target packages function _add_values_from_targetpkgs(values, target, name) for _, pkg in ipairs(target:orderpkgs()) do -- uses them instead of the builtin configs if exists extra package config -- e.g. `add_packages("xxx", {links = "xxx"})` local configinfo = target:pkgconfig(pkg:name()) if configinfo and configinfo[name] then table.join2(values, configinfo[name]) else -- uses the builtin package configs table.join2(values, pkg:get(name)) end end end -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) _add_values_from_targetopts(values, target, name) _add_values_from_targetpkgs(values, target, name) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then if targetkind == "shared" then target:add(name, values, {public = true}) else target:add(name, values, {interface = true}) end end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file inherit_links.lua -- -- add values from target options function _add_values_from_targetopts(values, target, name) for _, opt in ipairs(target:orderopts()) do table.join2(values, table.wrap(opt:get(name))) end end -- add values from target packages function _add_values_from_targetpkgs(values, target, name) for _, pkg in ipairs(target:orderpkgs()) do -- uses them instead of the builtin configs if exists extra package config -- e.g. `add_packages("xxx", {links = "xxx"})` local configinfo = target:pkgconfig(pkg:name()) if configinfo and configinfo[name] then table.join2(values, configinfo[name]) else -- uses the builtin package configs table.join2(values, pkg:get(name)) end end end -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) _add_values_from_targetopts(values, target, name) _add_values_from_targetpkgs(values, target, name) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then target:add(name, values, {public = true}) end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end
fix inherit links for static target
fix inherit links for static target
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
5a9629f72966b300be2f4dad1b5042e7b7c572f4
test/test_rotate.lua
test/test_rotate.lua
require 'image' torch.setdefaulttensortype('torch.FloatTensor') torch.setnumthreads(16) local function test_rotate(src, mode) torch.manualSeed(11) local mean_dist = 0.0 for i = 1, 10 do local theta = torch.uniform(0, 2 * math.pi) local d1, d2, d3, d4 -- rotate if mode then d1 = image.rotate(src, theta, mode) d2 = src.new():resizeAs(src) image.rotate(d2, src, theta, mode) else d1 = image.rotate(src, theta) d2 = src.new():resizeAs(src) image.rotate(d2, src, theta) end -- revert local revert = 2 * math.pi - theta if mode then d3 = image.rotate(d1, revert, mode) d4 = src.new():resizeAs(src) image.rotate(d4, d2, revert, mode) else d3 = image.rotate(d1, revert) d4 = src.new():resizeAs(src) image.rotate(d4, d2, revert) end -- diff if src:dim() == 3 then local cs = image.crop(src, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) local c3 = image.crop(d3, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) local c4 = image.crop(d4, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) mean_dist = mean_dist + cs:dist(c3) mean_dist = mean_dist + cs:dist(c4) elseif src:dim() == 2 then local cs = image.crop(src, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) local c3 = image.crop(d3, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) local c4 = image.crop(d4, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) mean_dist = mean_dist + cs:dist(c3) mean_dist = mean_dist + cs:dist(c4) end if i == 1 then --[[ image.display(src) image.display(d1) image.display(d2) image.display(d3) image.display(d4) --]] end end if mode then print("mode = " .. mode .. ", mean dist: " .. mean_dist / (10 * 2)) else print("mode = nil, mean dist: " .. mean_dist / (10 * 2)) end end local src = image.scale(image.lena(), 128, 128, 'bilinear') print("** dim3") test_rotate(src, nil) test_rotate(src, 'simple') test_rotate(src, 'bilinear') print("** dim2") src = src:select(1, 1) test_rotate(src, nil) test_rotate(src, 'simple') test_rotate(src, 'bilinear')
require 'image' torch.setdefaulttensortype('torch.FloatTensor') torch.setnumthreads(16) local function test_rotate(src, mode) torch.manualSeed(11) local mean_dist = 0.0 for i = 1, 10 do local theta = torch.uniform(0, 2 * math.pi) local d1, d2, d3, d4 -- rotate if mode then d1 = image.rotate(src, theta, mode) d2 = src.new():resizeAs(src) image.rotate(d2, src, theta, mode) else d1 = image.rotate(src, theta) d2 = src.new():resizeAs(src) image.rotate(d2, src, theta) end -- revert local revert = 2 * math.pi - theta if mode then d3 = image.rotate(d1, revert, mode) d4 = src.new():resizeAs(src) image.rotate(d4, d2, revert, mode) else d3 = image.rotate(d1, revert) d4 = src.new():resizeAs(src) image.rotate(d4, d2, revert) end -- diff if src:dim() == 3 then local cs = image.crop(src, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) local c3 = image.crop(d3, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) local c4 = image.crop(d4, src:size(2) / 4, src:size(3) / 4, src:size(2) / 4 * 3, src:size(3) / 4 * 3) mean_dist = mean_dist + cs:dist(c3) mean_dist = mean_dist + cs:dist(c4) elseif src:dim() == 2 then local cs = image.crop(src, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) local c3 = image.crop(d3, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) local c4 = image.crop(d4, src:size(1) / 4, src:size(2) / 4, src:size(1) / 4 * 3, src:size(2) / 4 * 3) mean_dist = mean_dist + cs:dist(c3) mean_dist = mean_dist + cs:dist(c4) end --[[ if i == 1 then image.display(src) image.display(d1) image.display(d2) image.display(d3) image.display(d4) end --]] end if mode then print("mode = " .. mode .. ", mean dist: " .. mean_dist / (10 * 2)) else print("mode = nil, mean dist: " .. mean_dist / (10 * 2)) end end local src = image.scale(image.lena(), 128, 128, 'bilinear') print("** dim3") test_rotate(src, nil) test_rotate(src, 'simple') test_rotate(src, 'bilinear') print("** dim2") src = src:select(1, 1) test_rotate(src, nil) test_rotate(src, 'simple') test_rotate(src, 'bilinear')
Indentation fixes
Indentation fixes
Lua
bsd-3-clause
torch/image,Moodstocks/image
fd614e60aaf27f467972c16734e5203bd78e36e4
src/framework/basic.lua
src/framework/basic.lua
--[[ Description: Internal objects extensions Author: M.Wan Date: 04/26/2014 ]] -- mark as deprecated function Deprecate(className) assert(false, "Deprecated class: " .. className) end -- return type string of the instance function GetType(instance) if type(instance) == "table" then if instance.__className == nil then return tolua.type(instance) end return instance.__className elseif type(instance) == "userdata" then return tolua.type(instance) else return type(instance) end end -- return instance function pointer function MakeScriptHandler(target, selector, ...) local args = {...} return function(...) -- the varadic params here are sent by the event automatically, append our own args after them. local internalArgs = {...} for _, arg in ipairs(args) do table.insert(internalArgs, arg) end return selector(target, unpack(internalArgs)) end end -- call a function after delay function CallFunctionAsync(target, selector, delay, ...) local args = {...} local handlerId = nil local handlerFunction = function() selector(target, unpack(args)) cc.Director:getInstance():getScheduler():unscheduleScriptEntry(handlerId) end handlerId = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handlerFunction, delay, false) end -- switch scene function ReplaceScene(scene, params) if type(scene) == "string" then scene = _G[scene] end local newScene = scene["create"](scene, params) local currentScene = cc.Director:getInstance():getRunningScene() if currentScene then cc.Director:getInstance():replaceScene(newScene) else cc.Director:getInstance():runWithScene(newScene) end end -- check whether fall in the random area, such as fallInRandom(3, 7) means whether it falls in 3/7. function FallInRandom(numerator, denominator) local randomNum = math.random(1, denominator) return randomNum <= numerator end -- return an array which contains all UTF-8 substrings from a string, from the first character. function GenerateAllUTF8Substrings(text) if type(text) ~= "string" then return nil end local function isChinese(index) -- the high 4 bits of UTF-8 Chinese is 1110 local byte = string.byte(text, index) byte = bit:_rshift(byte, 4) if byte == 0xE then return true end return false end local strings = {} local index = 1 while index <= #text do if isChinese(index) then index = index + 3 else index = index + 1 end local substr = string.sub(text, 1, index - 1) table.insert(strings, substr) end return strings end -- create frame animation function CreateAnimation(frameName, frameCount, timeline, seperator) seperator = seperator or "" local frames = {} for i = 1, frameCount do local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame(frameName .. seperator .. tostring(i) .. ".png") table.insert(frames, frame) end local animation = cc.Animation:createWithSpriteFrames(frames, timeline) local animate = cc.Animate:create(animation) return animate end -- use coroutine to run multiple actions -- warning: you have to use this function in a coroutine -- invoke this as CoPerformActions(target1, action1[, target2, action2] ...) function CoPerformActions(...) local co = coroutine.running() assert(co, "CoPerformActions should only be used in a coroutine") local actions = {...} local maxDuration = -1 local maxDurationTarget = nil for i = 1, #actions, 2 do local target = actions[i] local action = actions[i + 1] local duration = action:getDuration() -- seek the longest-duration action target if duration > maxDuration then maxDuration = duration maxDurationTarget = target end target:runAction(action) end -- wait for the longest action local coAction = cc.Sequence:create( cc.DelayTime:create(maxDuration), cc.CallFunc:create(function() coroutine.resume(co) end) ) maxDurationTarget:runAction(coAction) coroutine.yield() end
--[[ Description: Internal objects extensions Author: M.Wan Date: 04/26/2014 ]] -- mark as deprecated function Deprecate(className) assert(false, "Deprecated class: " .. className) end -- return type string of the instance function GetType(instance) if type(instance) == "table" then if instance.__className == nil then return tolua.type(instance) end return instance.__className elseif type(instance) == "userdata" then return tolua.type(instance) else return type(instance) end end -- return instance function pointer function MakeScriptHandler(target, selector, ...) local args = {...} return function(...) -- the varadic params here are sent by the event automatically, append our own args after them. local internalArgs = {...} for _, arg in ipairs(args) do table.insert(internalArgs, arg) end return selector(target, unpack(internalArgs)) end end -- call a function after delay function CallFunctionAsync(target, selector, delay, ...) local args = {...} local handlerId = nil local handlerFunction = function() selector(target, unpack(args)) cc.Director:getInstance():getScheduler():unscheduleScriptEntry(handlerId) end handlerId = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handlerFunction, delay, false) end -- switch scene function ReplaceScene(scene, params) if type(scene) == "string" then scene = _G[scene] end local newScene = nil if params and type(params) == "table" then newScene = scene["createWithParams"](scene, params) else newScene = scene["create"](scene) end local currentScene = cc.Director:getInstance():getRunningScene() if currentScene then cc.Director:getInstance():replaceScene(newScene) else cc.Director:getInstance():runWithScene(newScene) end end -- check whether fall in the random area, such as fallInRandom(3, 7) means whether it falls in 3/7. function FallInRandom(numerator, denominator) local randomNum = math.random(1, denominator) return randomNum <= numerator end -- return an array which contains all UTF-8 substrings from a string, from the first character. function GenerateAllUTF8Substrings(text) if type(text) ~= "string" then return nil end local function isChinese(index) -- the high 4 bits of UTF-8 Chinese is 1110 local byte = string.byte(text, index) byte = bit:_rshift(byte, 4) if byte == 0xE then return true end return false end local strings = {} local index = 1 while index <= #text do if isChinese(index) then index = index + 3 else index = index + 1 end local substr = string.sub(text, 1, index - 1) table.insert(strings, substr) end return strings end -- create frame animation function CreateAnimation(frameName, frameCount, timeline, seperator) seperator = seperator or "" local frames = {} for i = 1, frameCount do local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame(frameName .. seperator .. tostring(i) .. ".png") table.insert(frames, frame) end local animation = cc.Animation:createWithSpriteFrames(frames, timeline) local animate = cc.Animate:create(animation) return animate end -- use coroutine to run multiple actions -- warning: you have to use this function in a coroutine -- invoke this as CoPerformActions(target1, action1[, target2, action2] ...) function CoPerformActions(...) local co = coroutine.running() assert(co, "CoPerformActions should only be used in a coroutine") local actions = {...} local maxDuration = -1 local maxDurationTarget = nil for i = 1, #actions, 2 do local target = actions[i] local action = actions[i + 1] local duration = action:getDuration() -- seek the longest-duration action target if duration > maxDuration then maxDuration = duration maxDurationTarget = target end target:runAction(action) end -- wait for the longest action local coAction = cc.Sequence:create( cc.DelayTime:create(maxDuration), cc.CallFunc:create(function() coroutine.resume(co) end) ) maxDurationTarget:runAction(coAction) coroutine.yield() end
bug fixing
bug fixing
Lua
apache-2.0
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
56a0c48580f231aa73b0a4a577fe048afcbcafac
Server/Plugins/APIDump/Hooks/OnBlockSpread.lua
Server/Plugins/APIDump/Hooks/OnBlockSpread.lua
return { HOOK_BLOCK_SPREAD = { CalledWhen = "Called when a block spreads based on world conditions", DefaultFnName = "OnBlockSpread", -- also used as pagename Desc = [[ This hook is called when a block spreads.</p> <p> The spread carries with it the type of its source - whether it's a block spreads. It also carries the identification of the actual source. The exact type of the identification depends on the source kind: <table> <tr><th>Source</th><th>Notes</th></tr> <tr><td>ssFireSpread</td><td>Fire spreading</td></tr> <tr><td>ssGrassSpread</td><td>Grass spreading</td></tr> <tr><td>ssMushroomSpread</td><td>Mushroom spreading</td></tr> <tr><td>ssMycelSpread</td><td>Mycel spreading</td></tr> <tr><td>ssVineSpread</td><td>Vine spreading</td></tr> </table></p> ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "Source", Type = "eSpreadSource", Notes = "Source of the spread. See the table above." }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called, and finally Cuberite will process the spread. If the function returns true, no other callback is called for this event and the spread will not occur. ]], }, -- HOOK_BLOCK_SPREAD }
return { HOOK_BLOCK_SPREAD = { CalledWhen = "Called when a block spreads based on world conditions", DefaultFnName = "OnBlockSpread", -- also used as pagename Desc = [[ This hook is called when a block spreads.</p> <p> The spread carries with it the type of its source - whether it's a block spreads. It also carries the identification of the actual source. The exact type of the identification depends on the source kind: <table> <tr><th>Source</th><th>Notes</th></tr> <tr><td>ssFireSpread</td><td>Fire spreading</td></tr> <tr><td>ssGrassSpread</td><td>Grass spreading</td></tr> <tr><td>ssMushroomSpread</td><td>Mushroom spreading</td></tr> <tr><td>ssMycelSpread</td><td>Mycel spreading</td></tr> <tr><td>ssVineSpread</td><td>Vine spreading</td></tr> </table></p> ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "Source", Type = "eSpreadSource", Notes = "Source of the spread. See the table above." }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called, and finally Cuberite will process the spread. If the function returns true, no other callback is called for this event and the spread will not occur. ]], Examples = { { Title = "Stop fire spreading", Desc = "Stops fire from spreading, but does not remove any player-placed fire.", Code = [[ function OnBlockSpread(World, BlockX, Blocky, BlockZ, source) if (source == ssFireSpread) then -- Return true to block the fire spreading. return true end -- We don't care about any other events, let them continue. return false end -- Add the callback. cPluginManager:AddHook(cPluginManager.HOOK_BLOCK_SPREAD, OnBlockSpread); ]], }, }, }, -- HOOK_BLOCK_SPREAD }
Added additional examples to the documentation for HOOK_BLOCK_SPREAD. (#3277)
Added additional examples to the documentation for HOOK_BLOCK_SPREAD. (#3277) Fixes issue #3274
Lua
apache-2.0
mc-server/MCServer,mc-server/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,Frownigami1/cuberite,Altenius/cuberite,kevinr/cuberite,johnsoch/cuberite,nounoursheureux/MCServer,nounoursheureux/MCServer,Altenius/cuberite,kevinr/cuberite,Frownigami1/cuberite,Frownigami1/cuberite,kevinr/cuberite,kevinr/cuberite,mc-server/MCServer,Frownigami1/cuberite,nounoursheureux/MCServer,kevinr/cuberite,Altenius/cuberite,Altenius/cuberite,mc-server/MCServer,johnsoch/cuberite,Altenius/cuberite,mc-server/MCServer,nounoursheureux/MCServer,johnsoch/cuberite,johnsoch/cuberite,Frownigami1/cuberite,kevinr/cuberite,mc-server/MCServer,johnsoch/cuberite
ec95b893d61cf481bb7214342a245085b21c0947
extension/client/proxy.lua
extension/client/proxy.lua
local serverFactory = require 'serverFactory' local debuggerFactory = require 'debugerFactory' local fs = require 'bee.filesystem' local inject = require 'inject' local server local client local seq = 0 local initReq local m = {} local function getVersion(dir) local json = require 'json' local package = json.decode(assert(io.open((dir / 'package.json'):string()):read 'a')) return package.version end local function getDbgPath() if WORKDIR:filename():string() ~= 'extension' then return WORKDIR end return fs.path(os.getenv 'USERPROFILE') / '.vscode' / 'extensions' / ('actboy168.lua-debug-' .. getVersion(WORKDIR)) end local function getUnixPath(pid) local path = getDbgPath() / "windows" / "tmp" fs.create_directories(path) return path / ("pid_%d.tmp"):format(pid) end local function newSeq() seq = seq + 1 return seq end local function response_initialize(req) client.send { type = 'response', seq = newSeq(), command = 'initialize', request_seq = req.seq, success = true, body = require 'capabilities', } end local function response_error(req, msg) client.send { type = 'response', seq = newSeq(), command = req.command, request_seq = req.seq, success = false, message = msg, } end local function request_runinterminal(args) client.send { type = 'request', --seq = newSeq(), command = 'runInTerminal', arguments = args } end local function attach_process(pkg, pid) if not inject.injectdll(pid , (WORKDIR / "windows" / "x86" / "debugger-inject.dll"):string() , (WORKDIR / "windows" / "x64" / "debugger-inject.dll"):string() ) then return false end local path = getUnixPath(pid) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } server.send(initReq) server.send(pkg) return true end local function proxy_attach(pkg) local args = pkg.arguments if args.processId then if not attach_process(pkg, args.processId) then response_error(pkg, ('Cannot attach process `%d`.'):format(args.processId)) end return end if args.processName then local pids = inject.query_process(args.processName) if #pids == 0 then response_error(pkg, ('Cannot found process `%s`.'):format(args.processName)) return elseif #pids > 1 then response_error(pkg, ('There are %d processes `%s`.'):format(#pids, args.processName)) return end if not attach_process(pkg, pids[1]) then response_error(pkg, ('Cannot attach process `%s` `%d`.'):format(args.processName, pids[1])) end return end server = serverFactory { protocol = 'tcp', address = args.ip == 'localhost' and '127.0.0.1' or args.ip, port = args.port, client = true } server.send(initReq) server.send(pkg) end local function proxy_launch(pkg) local args = pkg.arguments if args.runtimeExecutable then local process = debuggerFactory.create_process(args) if not process then response_error(pkg, 'launch failed') return end local path = getUnixPath(process:get_id()) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } else local path = getUnixPath(inject.current_pid()) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } if args.console == 'integratedTerminal' or args.console == 'externalTerminal' then local arguments = debuggerFactory.create_terminal(args, getDbgPath(), path) if not arguments then response_error(pkg, 'launch failed') return end request_runinterminal(arguments) else if not debuggerFactory.create_luaexe(args, getDbgPath(), path) then response_error(pkg, 'launch failed') return end end end server.send(initReq) server.send(pkg) end function m.send(pkg) if server then if pkg.type == 'response' and pkg.command == 'runInTerminal' then return end server.send(pkg) elseif not initReq then if pkg.type == 'request' and pkg.command == 'initialize' then pkg.__norepl = true initReq = pkg response_initialize(pkg) else response_error(pkg, 'not initialized') end else if pkg.type == 'request' then if pkg.command == 'attach' then proxy_attach(pkg) elseif pkg.command == 'launch' then proxy_launch(pkg) else response_error(pkg, 'error request') end end end end function m.update() if server then while true do local pkg = server.recv() if pkg then client.send(pkg) else break end end end end function m.init(io) client = io end return m
local serverFactory = require 'serverFactory' local debuggerFactory = require 'debugerFactory' local fs = require 'bee.filesystem' local inject = require 'inject' local server local client local seq = 0 local initReq local m = {} local function getVersion(dir) local json = require 'json' local package = json.decode(assert(io.open((dir / 'package.json'):string()):read 'a')) return package.version end local function getDbgPath() if WORKDIR:filename():string() ~= 'extension' then return WORKDIR end return fs.path(os.getenv 'USERPROFILE') / '.vscode' / 'extensions' / ('actboy168.lua-debug-' .. getVersion(WORKDIR)) end local function getUnixPath(pid) local path = getDbgPath() / "windows" / "tmp" fs.create_directories(path) return path / ("pid_%d.tmp"):format(pid) end local function newSeq() seq = seq + 1 return seq end local function response_initialize(req) client.send { type = 'response', seq = newSeq(), command = 'initialize', request_seq = req.seq, success = true, body = require 'capabilities', } end local function response_error(req, msg) client.send { type = 'response', seq = newSeq(), command = req.command, request_seq = req.seq, success = false, message = msg, } end local function request_runinterminal(args) client.send { type = 'request', --seq = newSeq(), command = 'runInTerminal', arguments = args } end local function attach_process(pkg, pid) if not inject.injectdll(pid , (WORKDIR / "windows" / "x86" / "debugger-inject.dll"):string() , (WORKDIR / "windows" / "x64" / "debugger-inject.dll"):string() ) then return false end local path = getUnixPath(pid) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } server.send(initReq) server.send(pkg) return true end local function proxy_attach(pkg) local args = pkg.arguments if args.processId then if not attach_process(pkg, args.processId) then response_error(pkg, ('Cannot attach process `%d`.'):format(args.processId)) end return end if args.processName then local pids = inject.query_process(args.processName) if #pids == 0 then response_error(pkg, ('Cannot found process `%s`.'):format(args.processName)) return elseif #pids > 1 then response_error(pkg, ('There are %d processes `%s`.'):format(#pids, args.processName)) return end if not attach_process(pkg, pids[1]) then response_error(pkg, ('Cannot attach process `%s` `%d`.'):format(args.processName, pids[1])) end return end server = serverFactory { protocol = 'tcp', address = args.ip == 'localhost' and '127.0.0.1' or args.ip, port = args.port, client = true } server.send(initReq) server.send(pkg) end local function proxy_launch(pkg) local args = pkg.arguments if args.runtimeExecutable then local process = debuggerFactory.create_process(args) if not process then response_error(pkg, 'launch failed') return end if args.ip and args.port then server = serverFactory { protocol = 'tcp', address = args.ip == 'localhost' and '127.0.0.1' or args.ip, port = args.port, client = true } else local path = getUnixPath(process:get_id()) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } end else local path = getUnixPath(inject.current_pid()) fs.remove(path) server = serverFactory { protocol = 'unix', address = path:string() } if args.console == 'integratedTerminal' or args.console == 'externalTerminal' then local arguments = debuggerFactory.create_terminal(args, getDbgPath(), path) if not arguments then response_error(pkg, 'launch failed') return end request_runinterminal(arguments) else if not debuggerFactory.create_luaexe(args, getDbgPath(), path) then response_error(pkg, 'launch failed') return end end end server.send(initReq) server.send(pkg) end function m.send(pkg) if server then if pkg.type == 'response' and pkg.command == 'runInTerminal' then return end server.send(pkg) elseif not initReq then if pkg.type == 'request' and pkg.command == 'initialize' then pkg.__norepl = true initReq = pkg response_initialize(pkg) else response_error(pkg, 'not initialized') end else if pkg.type == 'request' then if pkg.command == 'attach' then proxy_attach(pkg) elseif pkg.command == 'launch' then proxy_launch(pkg) else response_error(pkg, 'error request') end end end end function m.update() if server then while true do local pkg = server.recv() if pkg then client.send(pkg) else break end end end end function m.init(io) client = io end return m
Fixes #44
Fixes #44
Lua
mit
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
d4eca1df6fd8111dae69289c6fa11d195da2f70b
lua/autorun/client/sbep_dupe_fix.lua
lua/autorun/client/sbep_dupe_fix.lua
SBEP = SBEP or {} --fill table from file --not run on execution as you don't always need to fix dupes --is a console command in case you made changes and want to try it real-time function SBEP_LoadReplaceTable() print("Loading Filename Changes") local repTab = {} local tableString = file.Read("SBEP/Smallbridge Filename Changes.txt") local tableRows = string.Explode("\n",tableString) for _,row in pairs(tableRows) do --returns the pair of strings matched by this pattern --currently only finds models, if we change entity names as well this will need changing old,new = string.match(row, "^[ \t]*(models/[0-9A-Za-z/, _-]*.mdl)[ \t]*|[ \t]*(models/[0-9A-Za-z/, _-]*.mdl)[ \t]*$") if (old and new) then repTab[old] = new end end SBEP_ReplaceTable = repTab SBEP.ReplaceTable = repTab end SBEP.LoadReplaceTable = SBEP_LoadReplaceTable concommand.Add("SBEP_LoadReplaceTable",SBEP.LoadReplaceTable) --replaces all instances of models in the replace table with function SBEP_FixDupe(_,_,arg) --if the replace table hasn't been made yet, remake it if not SBEP.ReplaceTable then SBEP.LoadReplaceTable() end --print("FixDupe called") local filePath = table.concat(arg,' ') --print("File Path = ",filePath) local fileString = file.Read(filePath) for old,new in pairs(SBEP.ReplaceTable) do --print("Replacing "..old.." with "..new) fileString = string.Replace(fileString,old,new) fileString = string.Replace(fileString,string.lower(old),new) end file.Write(filePath,fileString) print(filePath.." fixed.") end SBEP.FixDupe = SBEP_FixDupe concommand.Add("SBEP_FixDupe",SBEP.FixDupe) function SBEP_RecursiveFix(_,_,args) --print("Recursive Fix Called") local dir = table.concat(args,' ') --print("Directories Found: ") local dirs = file.FindDir(dir.."/*") --PrintTable(dirs) for _,dirPath in pairs(dirs) do SBEP_RecursiveFix(nil,nil,{dir.."/"..dirPath}) end --print("Files Found: ") local files = file.Find(dir.."/*.txt", "DATA") -- OR should it be GAME ? --PrintTable(files) for _,filePath in pairs(files) do SBEP.FixDupe(nil,nil,{dir.."/"..filePath}) end end SBEP.RecursiveFix = SBEP_RecursiveFix concommand.Add("SBEP_FixDupeFolder",SBEP.RecursiveFix) function SBEP_FixAllDupes() --print("Fix Dupes Called") SBEP.RecursiveFix(nil,nil,{"adv_duplicator"}) end SBEP.FixAllDupes = SBEP_FixAllDupes concommand.Add("SBEP_FixAllDupes",SBEP.FixAllDupes)
SBEP = SBEP or {} --fill table from file --not run on execution as you don't always need to fix dupes --is a console command in case you made changes and want to try it real-time function SBEP_LoadReplaceTable() print("Loading Filename Changes") local repTab = {} local tableString = file.Read("Smallbridge Filename Changes.txt", "GAME") local tableRows = string.Explode("\n",tableString) for _,row in pairs(tableRows) do --returns the pair of strings matched by this pattern --currently only finds models, if we change entity names as well this will need changing old,new = string.match(row, "^[ \t]*(models/[0-9A-Za-z/, _-]*.mdl)[ \t]*|[ \t]*(models/[0-9A-Za-z/, _-]*.mdl)[ \t]*$") if (old and new) then repTab[old] = new end end SBEP_ReplaceTable = repTab SBEP.ReplaceTable = repTab end SBEP.LoadReplaceTable = SBEP_LoadReplaceTable concommand.Add("SBEP_LoadReplaceTable",SBEP.LoadReplaceTable) --replaces all instances of models in the replace table with function SBEP_FixDupe(_,_,arg) --if the replace table hasn't been made yet, remake it if not SBEP.ReplaceTable then SBEP.LoadReplaceTable() end --print("FixDupe called") local filePath = table.concat(arg,' ') --print("File Path = ",filePath) local fileString = file.Read(filePath) if fileString then for old,new in pairs(SBEP.ReplaceTable) do --print("Replacing "..old.." with "..new) fileString = string.Replace(fileString,old,new) fileString = string.Replace(fileString,string.lower(old),new) end print(filePath.." fixed.") file.Write(filePath,fileString) else print(filePath.." is broken, can't do anything") end end SBEP.FixDupe = SBEP_FixDupe concommand.Add("SBEP_FixDupe",SBEP.FixDupe) function SBEP_RecursiveFix(_,_,args) local dir = table.concat(args,' ') --print("\nRecursive Fix Called, we are in: "..dir) local files = file.Find(dir.."/*.txt", "DATA") if files then --print("Files Found: ") --PrintTable(files) for _,filePath in pairs(files) do SBEP.FixDupe(nil,nil,{dir.."/"..filePath}) end end local files, directories = file.Find(dir.."/*","DATA") if directories then --print("Directories Found: ") --PrintTable(directories) for _,dirPath in pairs(directories) do SBEP_RecursiveFix(nil,nil,{dir.."/"..dirPath}) end end end SBEP.RecursiveFix = SBEP_RecursiveFix concommand.Add("SBEP_FixDupeFolder",SBEP.RecursiveFix) function SBEP_FixAllDupes() --print("Fix Dupes Called") SBEP.RecursiveFix(nil,nil,{"adv_duplicator"}) print("Done!") end SBEP.FixAllDupes = SBEP_FixAllDupes concommand.Add("SBEP_FixAllDupes",SBEP.FixAllDupes)
Fixed the adv.dupe model fixer
Fixed the adv.dupe model fixer
Lua
apache-2.0
SnakeSVx/sbep
5349fca7a5f7f60846ee7bd33f2866d78a719df9
quiz/hello.lua
quiz/hello.lua
local math = require("math") math.randomseed(os.time()) local f = function(...) local t = string.format(...) return t:gsub(' *>>>', '>>>') end local hello = {} local _ = function(text, req) if req then return req:_(text) else return text end end local task = function(req) return _([[What does Python print if you enter the following commands?]], req) end local shortrand = function() local t = {} local l = math.random(3, 7) for i = 1, l do table.insert(t, math.random(65, 90)) -- A-Z end return string.char(t) end function hello.print1(req) local val = math.random(0, 100) return f('>>> print(%i)', val), f('%i', val), f('(%i)', val), f('print(%i)', val), f('"%i"', val), task(req) end function hello.print_sum(req) local val = math.random(10, 100) return f([[>>> a = %i >>> b = a >>> print(a+b)]], val), f('%i', val * 2), f('%i', val), f('a+b', val), f('"a+b"', val), task(req) end function hello.division_int(req) local a = math.random(60, 100) local b = math.random(10, 50) local result = math.floor(a / b) return f(">>> print(%i // %i)", a, b), f('%i', result), f('%i', result + 1), f('%i', result - 1), f('%i', result - 2), task(req) end function hello.division_float(req) local result = 0.5 * math.random(2, 5) local b = math.random(10, 50) local a = result * b return f(">>> print(%i.0 / %i.0)", a, b), f('%0.1f', result), f('%0.1f', result - 0.5), f('%0.1f', result + 0.5), f('%0.1f', result * 2), task(req) end function hello.mod(req) local a = math.random(60, 100) local b = math.random(10, 50) local result = a % b return f(">>> print(%i %% %i)", a, b), f('%i', result), f('%i', result + 1), f('%i', result - 1), f('%i', a), task(req) end function hello.start_file(req) local target_file = 'p' .. math.random(10, 50) .. '.py' return f("Filename: %s", target_file), f('python %s', target_file), f('%s', target_file), f('C:\\\\ %s', target_file), f(':) %s :)', target_file), _([[How to execute Python script from command line?]], req) end function hello.python_org(req) return '', 'python.org', 'python.com', 'python.ru', 'kodomo.fbb.msu.ru', _("What is the Python's official site?", req) end function hello.python_exit(req) return '', 'exit()', 'exit', 'quit', 'stop()', _("How to interrupt interactive Python session?", req) end function hello.python_far_ctrl_o(req) return '', 'Ctrl+O', 'Ctrl+Q', 'F' .. math.random(1, 5), 'F' .. math.random(6, 10), _([[How to view Python output if it has been shadowed by FAR blue window?]], req) end function hello.raw_input(req) local v = 'v' .. math.random(0, 9) return '', f('>>> %s = raw_input()\n123\n>>>print(%s)', v, v), f('>>> %s = raw_input()\n123\n>>>%s', v, v), f('>>> %s = int(raw_input()\n123\n>>>%s', v, v), f('>>> %s = str(raw_input())\n123\n>>>%s', v, v), _("Which Python code produces output 123?", req) end function hello.sqrt(req) local result = math.random(10, 20) return f('>>> print(%i ** 0.5)', result ^ 2), f('%i', result), f('%i', result * 0.5), f('%i', result / 0.5), f('Error:'), task(req) end function hello.pow10(req) local val = math.random(5, 15) return f('>>> print(len(str(10 ** %i)))', val), f('%i', val + 1), f('%i', val), f('%i', val + 2), f('%i', val + 3), task(req) end function hello.pow10f(req) local val = math.random(5, 15) return f('>>> print(len(str(10.0 ** %i)))', val), f('%i', val + 3), f('%i', val + 1), f('%i', val), f('%i', val + 2), task(req) end function hello.minusminus(req) local a = math.random(11, 15) local b = math.random(1, 5) return f('>>> print(-%i - %i)', a, b), f('%i', -a - b), f('%i', a - b), f('%i', -a - b + 1), f('%i', -a - b + 2), task(req) end function hello.lastdigit(req) local a = math.random(1110, 9999) return f('>>> print(%i %% 10)', a), f('%i', a % 10), f('%i', a % 100), f('%i', a % 1000), f('%i', -a % 10), task(req) end function hello.last2digits(req) local a = math.random(1110, 9999) return f('>>> print(%i %% 100)', a), f('%i', a % 100), f('%i', a % 10), f('%i', a % 1000), f('%i', -a % 10), task(req) end function hello.stringcat(req) local s = shortrand() return f('>>> print("%s" + "%s")', s, s), f('%s', s .. s), f('%s', s), f(''), f('Error'), task(req) end function hello.stringcatnumber(req) local s = shortrand() local i = math.random(3, 7) return f('>>> print("%s" + %i)', s, i), f('Error'), f('%s', s .. i), f('%s', string.rep(s, i)), f('%i', i), task(req) end function hello.stringmulnumber(req) local s = shortrand() local i = math.random(3, 7) return f('>>> print("%s" * %i)', s, i), f('%s', string.rep(s, i)), f('Error'), f('%s', s .. i), f('%i', i), task(req) end return hello
local math = require("math") math.randomseed(os.time()) local f = function(...) local t = string.format(...) return t:gsub(' *>>>', '>>>') end local hello = {} local _ = function(text, req) if req then return req:_(text) else return text end end local task = function(req) return _([[What does Python print if you enter the following commands?]], req) end local shortrand = function() local t = {} local l = math.random(3, 7) for i = 1, l do table.insert(t, math.random(65, 90)) -- A-Z end local unPack = unpack or table.unpack return string.char(unPack(t)) end function hello.print1(req) local val = math.random(0, 100) return f('>>> print(%i)', val), f('%i', val), f('(%i)', val), f('print(%i)', val), f('"%i"', val), task(req) end function hello.print_sum(req) local val = math.random(10, 100) return f([[>>> a = %i >>> b = a >>> print(a+b)]], val), f('%i', val * 2), f('%i', val), f('a+b', val), f('"a+b"', val), task(req) end function hello.division_int(req) local a = math.random(60, 100) local b = math.random(10, 50) local result = math.floor(a / b) return f(">>> print(%i // %i)", a, b), f('%i', result), f('%i', result + 1), f('%i', result - 1), f('%i', result - 2), task(req) end function hello.division_float(req) local result = 0.5 * math.random(2, 5) local b = math.random(10, 50) local a = result * b return f(">>> print(%i.0 / %i.0)", a, b), f('%0.1f', result), f('%0.1f', result - 0.5), f('%0.1f', result + 0.5), f('%0.1f', result * 2), task(req) end function hello.mod(req) local a = math.random(60, 100) local b = math.random(10, 50) local result = a % b return f(">>> print(%i %% %i)", a, b), f('%i', result), f('%i', result + 1), f('%i', result - 1), f('%i', a), task(req) end function hello.start_file(req) local target_file = 'p' .. math.random(10, 50) .. '.py' return f("Filename: %s", target_file), f('python %s', target_file), f('%s', target_file), f('C:\\\\ %s', target_file), f(':) %s :)', target_file), _([[How to execute Python script from command line?]], req) end function hello.python_org(req) return '', 'python.org', 'python.com', 'python.ru', 'kodomo.fbb.msu.ru', _("What is the Python's official site?", req) end function hello.python_exit(req) return '', 'exit()', 'exit', 'quit', 'stop()', _("How to interrupt interactive Python session?", req) end function hello.python_far_ctrl_o(req) return '', 'Ctrl+O', 'Ctrl+Q', 'F' .. math.random(1, 5), 'F' .. math.random(6, 10), _([[How to view Python output if it has been shadowed by FAR blue window?]], req) end function hello.raw_input(req) local v = 'v' .. math.random(0, 9) return '', f('>>> %s = raw_input()\n123\n>>>print(%s)', v, v), f('>>> %s = raw_input()\n123\n>>>%s', v, v), f('>>> %s = int(raw_input()\n123\n>>>%s', v, v), f('>>> %s = str(raw_input())\n123\n>>>%s', v, v), _("Which Python code produces output 123?", req) end function hello.sqrt(req) local result = math.random(10, 20) return f('>>> print(%i ** 0.5)', result ^ 2), f('%i', result), f('%i', result * 0.5), f('%i', result / 0.5), f('Error:'), task(req) end function hello.pow10(req) local val = math.random(5, 15) return f('>>> print(len(str(10 ** %i)))', val), f('%i', val + 1), f('%i', val), f('%i', val + 2), f('%i', val + 3), task(req) end function hello.pow10f(req) local val = math.random(5, 15) return f('>>> print(len(str(10.0 ** %i)))', val), f('%i', val + 3), f('%i', val + 1), f('%i', val), f('%i', val + 2), task(req) end function hello.minusminus(req) local a = math.random(11, 15) local b = math.random(1, 5) return f('>>> print(-%i - %i)', a, b), f('%i', -a - b), f('%i', a - b), f('%i', -a - b + 1), f('%i', -a - b + 2), task(req) end function hello.lastdigit(req) local a = math.random(1110, 9999) return f('>>> print(%i %% 10)', a), f('%i', a % 10), f('%i', a % 100), f('%i', a % 1000), f('%i', -a % 10), task(req) end function hello.last2digits(req) local a = math.random(1110, 9999) return f('>>> print(%i %% 100)', a), f('%i', a % 100), f('%i', a % 10), f('%i', a % 1000), f('%i', -a % 10), task(req) end function hello.stringcat(req) local s = shortrand() return f('>>> print("%s" + "%s")', s, s), f('%s', s .. s), f('%s', s), f(''), f('Error'), task(req) end function hello.stringcatnumber(req) local s = shortrand() local i = math.random(3, 7) return f('>>> print("%s" + %i)', s, i), f('Error'), f('%s', s .. i), f('%s', string.rep(s, i)), f('%i', i), task(req) end function hello.stringmulnumber(req) local s = shortrand() local i = math.random(3, 7) return f('>>> print("%s" * %i)', s, i), f('%s', string.rep(s, i)), f('Error'), f('%s', s .. i), f('%i', i), task(req) end return hello
fix function shortrand() (quiz hello)
fix function shortrand() (quiz hello)
Lua
mit
starius/kodomoquiz
0e30fb16f829b85c28c5254e2af312742670ae9b
SVUI_!Core/system/_reports/artifact.lua
SVUI_!Core/system/_reports/artifact.lua
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; 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 assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; local LAD = LibStub("LibArtifactData-1.0"); --[[ ########################################################## UTILITIES ########################################################## ]]-- local percColors = { "|cff0CD809", "|cffE8DA0F", "|cffFF9000", "|cffD80909" } local function GetArtifactData() local artID = LAD:GetActiveArtifactID() if not artID then return false end local data artID, data = LAD:GetArtifactInfo(artID) if not artID then return false end return true, data.numRanksPurchased, data.power, data.maxPower , data.numRanksPurchasable end local function SetTooltipText(report) Reports:SetDataTip(report) local isEquipped, rank, currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() Reports.ToolTip:AddLine(L["Artifact Power"]) Reports.ToolTip:AddLine(" ") if isEquipped then local calc1 = (currentPower / powerToNextLevel) * 100; Reports.ToolTip:AddDoubleLine(L["Rank:"], (" %d "):format(rank), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %s / %s (%d%%)"):format(currentPower, powerToNextLevel, calc1), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %s "):format(powerToNextLevel - currentPower), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Points to Spend:"], format(" %s ", pointsToSpend), 1, 1, 1) else Reports.ToolTip:AddDoubleLine(L["No Artifact"]) end end local function FormatPower(rank, currentPower, powerForNextPoint, pointsToSpend) local calc1 = (currentPower / powerForNextPoint) * 100; local currentText = ("Traits: %d (%s%d%%|r)"):format(rank, percColors[calc1 >= 75 and 1 or (calc1 >= 50 and calc1 < 75) and 2 or (calc1 >= 25 and calc1 < 50) and 3 or (calc1 >= 0 and calc1 < 25) and 4], calc1); return currentText end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Artifact"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD"}; Report.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () Report.Populate(self) end) end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() end local isEquipped,rank,currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() if isEquipped then local text = FormatPower(rank, currentPower,powerToNextLevel,pointsToSpend); self.text:SetText(text) else self.text:SetText(L["No Artifact"]) end end Report.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end Report.OnInit = function(self) if(not self.InnerData) then self.InnerData = {} end Report.Populate(self) end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Artifact Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD"}; ReportBar.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () ReportBar.Populate(self) end) end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end local bar = self.barframe.bar; local isEquipped, rank, currentPower, powerToNextLevel, pointsToSpend = GetArtifactData() if isEquipped then bar:SetMinMaxValues(0, powerToNextLevel) bar:SetValue(currentPower) bar:SetStatusBarColor(0.9, 0.64, 0.37) local toSpend = "" if pointsToSpend>0 then toSpend = " (+"..pointsToSpend..")" end self.text:SetText(rank..toSpend) self.barframe:Show() else bar:SetMinMaxValues(0, 1) bar:SetValue(0) self.text:SetText(L["No Artifact"]) end end ReportBar.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end ReportBar.OnInit = function(self) if(not self.InnerData) then self.InnerData = {} end ReportBar.Populate(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end end
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; 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 assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; local LAD = LibStub("LibArtifactData-1.0"); --[[ ########################################################## UTILITIES ########################################################## ]]-- local percColors = { "|cff0CD809", "|cffE8DA0F", "|cffFF9000", "|cffD80909" } local function GetArtifactData() local artID = LAD:GetActiveArtifactID() if not artID then return false end local data artID, data = LAD:GetArtifactInfo(artID) if not artID then return false end return true, data.numRanksPurchased, data.power, data.maxPower , data.numRanksPurchasable end local function SetTooltipText(report) Reports:SetDataTip(report) local isEquipped, rank, currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() Reports.ToolTip:AddLine(L["Artifact Power"]) Reports.ToolTip:AddLine(" ") if isEquipped then local calc1 = (currentPower / powerToNextLevel) * 100; Reports.ToolTip:AddDoubleLine(L["Rank:"], (" %d "):format(rank), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %s / %s (%d%%)"):format(BreakUpLargeNumbers(currentPower), BreakUpLargeNumbers(powerToNextLevel), calc1), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %s "):format(BreakUpLargeNumbers(powerToNextLevel - currentPower)), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Points to Spend:"], format(" %s ", pointsToSpend), 1, 1, 1) else Reports.ToolTip:AddDoubleLine(L["No Artifact"]) end end local function FormatPower(rank, currentPower, powerForNextPoint, pointsToSpend) local calc1 = (currentPower / powerForNextPoint) * 100; local currentText = ("Traits: %d (%s%d%%|r)"):format(rank, percColors[calc1 >= 75 and 1 or (calc1 >= 50 and calc1 < 75) and 2 or (calc1 >= 25 and calc1 < 50) and 3 or (calc1 >= 0 and calc1 < 25) and 4], calc1); return currentText end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Artifact"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD"}; Report.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () Report.Populate(self) end) end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() end local isEquipped,rank,currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() if isEquipped then local text = FormatPower(rank, currentPower,powerToNextLevel,pointsToSpend); self.text:SetText(text) else self.text:SetText(L["No Artifact"]) end end Report.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end Report.OnInit = function(self) if(not self.InnerData) then self.InnerData = {} end Report.Populate(self) end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Artifact Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD"}; ReportBar.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () ReportBar.Populate(self) end) end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end local bar = self.barframe.bar; local isEquipped, rank, currentPower, powerToNextLevel, pointsToSpend = GetArtifactData() if isEquipped then bar:SetMinMaxValues(0, powerToNextLevel) bar:SetValue(currentPower) bar:SetStatusBarColor(0.9, 0.64, 0.37) local toSpend = "" if pointsToSpend>0 then toSpend = " (+"..pointsToSpend..")" end self.text:SetText(rank..toSpend) self.barframe:Show() else bar:SetMinMaxValues(0, 1) bar:SetValue(0) self.text:SetText(L["No Artifact"]) end end ReportBar.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end ReportBar.OnInit = function(self) if(not self.InnerData) then self.InnerData = {} end ReportBar.Populate(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end end
#121 - Fixed large numbers.
#121 - Fixed large numbers.
Lua
mit
finalsliver/supervillain-ui,FailcoderAddons/supervillain-ui
5e3135d458d1a884fd55598280c75af868d9fe8e
vanilla/v/router.lua
vanilla/v/router.lua
-- perf local error = error local tconcat = table.concat local function tappend(t, v) t[#t+1] = v end local simple_route = require 'vanilla.v.routes.simple' -- init Router and set routes local Router = {} function Router:new(request) local instance = { routes = {simple_route:new(request)} } setmetatable(instance, {__index = self}) return instance end function Router:addRoute(route, only_one) if route ~= nil then if only_one then self.routes = {} end tappend(self.routes, route) end end function Router:removeRoute(route_name) for i,route in ipairs(self.routes) do if (tostring(route) == route_name) then self.routes[i] = false end end end function Router:getRoutes() return self.routes end function Router:getCurrentRoute() return self.current_route end function Router:getCurrentRouteName() return tostring(self.current_route) end local function route_match(route) return route:match() end function Router:route() if #self.routes >= 1 then local alive_route_num = 0 local route_err = {} for k,route in ipairs(self.routes) do if route then alive_route_num = alive_route_num + 1 local ok, controller_name_or_error, action = pcall(route_match, route) if ok and package.searchpath(ngx.var.document_root .. '/application/controllers.' .. controller_name_or_error, '/?.lua;/?/init.lua') ~=nil and type(require('controllers.' .. controller_name_or_error)[action]) == 'function' then -- if ok and controller_name_or_error then self.current_route = route return controller_name_or_error, action else route_err[k] = controller_name_or_error end end end error({ code = 201, msg = { Routes_No_Match = alive_route_num .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}}) end error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}}) end return Router
-- perf local error = error local tconcat = table.concat local function tappend(t, v) t[#t+1] = v end local simple_route = require 'vanilla.v.routes.simple' -- init Router and set routes local Router = {} function Router:new(request) local instance = { routes = {simple_route:new(request)} } setmetatable(instance, {__index = self}) return instance end function Router:addRoute(route, only_one) if route ~= nil then if only_one then self.routes = {} end tappend(self.routes, route) end end function Router:removeRoute(route_name) for i,route in ipairs(self.routes) do if (tostring(route) == route_name) then self.routes[i] = false end end end function Router:getRoutes() return self.routes end function Router:getCurrentRoute() return self.current_route end function Router:getCurrentRouteName() return tostring(self.current_route) end local function route_match(route) return route:match() end function Router:route() if #self.routes >= 1 then local alive_route_num = 0 local route_err = {} for k,route in ipairs(self.routes) do if route then alive_route_num = alive_route_num + 1 local ok, controller_name_or_error, action = pcall(route_match, route) if ok and controller_name_or_error ~= nil and package.searchpath(ngx.var.document_root .. '/application/controllers.' .. controller_name_or_error, '/?.lua;/?/init.lua') ~= nil and type(require('controllers.' .. controller_name_or_error)[action]) == 'function' then -- if ok and controller_name_or_error then self.current_route = route return controller_name_or_error, action else route_err[k] = controller_name_or_error end end end error({ code = 201, msg = { Routes_No_Match = alive_route_num .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}}) end error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}}) end return Router
fix a route bug when restful router return a nil value
fix a route bug when restful router return a nil value
Lua
mit
idevz/vanilla,idevz/vanilla
19021504983bc64b5e56fe35d3b280b95bb50fac
net/xmppcomponent_listener.lua
net/xmppcomponent_listener.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local hosts = _G.hosts; local t_concat = table.concat; local lxp = require "lxp"; local logger = require "util.logger"; local config = require "core.configmanager"; local connlisteners = require "net.connlisteners"; local cm_register_component = require "core.componentmanager".register_component; local cm_deregister_component = require "core.componentmanager".deregister_component; local uuid_gen = require "util.uuid".generate; local sha1 = require "util.hashes".sha1; local st = require "util.stanza"; local init_xmlhandlers = require "core.xmlhandlers"; local sessions = {}; local log = logger.init("componentlistener"); local component_listener = { default_port = 5347; default_mode = "*a"; default_interface = config.get("*", "core", "component_interface") or "127.0.0.1" }; local xmlns_component = 'jabber:component:accept'; --- Callbacks/data for xmlhandlers to handle streams for us --- local stream_callbacks = { default_ns = xmlns_component }; function stream_callbacks.error(session, error, data, data2) log("warn", "Error processing component stream: "..tostring(error)); if error == "no-stream" then session:close("invalid-namespace"); elseif error == "xml-parse-error" and data == "unexpected-element-close" then session.log("warn", "Unexpected close of '%s' tag", data2); session:close("xml-not-well-formed"); else session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(error)); session:close("xml-not-well-formed"); end end function stream_callbacks.streamopened(session, attr) if config.get(attr.to, "core", "component_module") ~= "component" then -- Trying to act as a component domain which -- hasn't been configured session:close{ condition = "host-unknown", text = tostring(attr.to).." does not match any configured external components" }; return; end -- Store the original host (this is used for config, etc.) session.user = attr.to; -- Set the host for future reference session.host = config.get(attr.to, "core", "component_address") or attr.to; -- Note that we don't create the internal component -- until after the external component auths successfully session.streamid = uuid_gen(); session.notopen = nil; session.send(st.stanza("stream:stream", { xmlns=xmlns_component, ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.host }):top_tag()); end function stream_callbacks.streamclosed(session) session.send("</stream:stream>"); session.notopen = true; end local core_process_stanza = core_process_stanza; function stream_callbacks.handlestanza(session, stanza) -- Namespaces are icky. if not stanza.attr.xmlns and stanza.name == "handshake" then stanza.attr.xmlns = xmlns_component; end return core_process_stanza(session, stanza); end --- Closing a component connection local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'}; local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" }; local function session_close(session, reason) local log = session.log or log; if session.conn then if session.notopen then session.send("<?xml version='1.0'?>"); session.send(st.stanza("stream:stream", default_stream_attr):top_tag()); end if reason then if type(reason) == "string" then -- assume stream error log("info", "Disconnecting component, <stream:error> is: %s", reason); session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' })); elseif type(reason) == "table" then if reason.condition then local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up(); if reason.text then stanza:tag("text", stream_xmlns_attr):text(reason.text):up(); end if reason.extra then stanza:add_child(reason.extra); end log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza)); session.send(stanza); elseif reason.name then -- a stanza log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason)); session.send(reason); end end end session.send("</stream:stream>"); session.conn:close(); component_listener.ondisconnect(session.conn, "stream error"); end end --- Component connlistener function component_listener.onincoming(conn, data) local session = sessions[conn]; if not session then local _send = conn.write; session = { type = "component", conn = conn, send = function (data) return _send(conn, tostring(data)); end }; sessions[conn] = session; -- Logging functions -- local conn_name = "jcp"..tostring(conn):match("[a-f0-9]+$"); session.log = logger.init(conn_name); session.close = session_close; session.log("info", "Incoming Jabber component connection"); local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "\1"); session.parser = parser; session.notopen = true; function session.data(conn, data) local ok, err = parser:parse(data); if ok then return; end session:close("xml-not-well-formed"); end session.dispatch_stanza = stream_callbacks.handlestanza; end if data then session.data(conn, data); end end function component_listener.ondisconnect(conn, err) local session = sessions[conn]; if session then (session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err)); if session.host then log("debug", "Deregistering component"); cm_deregister_component(session.host); hosts[session.host].connected = nil; end sessions[conn] = nil; for k in pairs(session) do session[k] = nil; end session = nil; end end connlisteners.register('xmppcomponent', component_listener);
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local hosts = _G.hosts; local t_concat = table.concat; local lxp = require "lxp"; local logger = require "util.logger"; local config = require "core.configmanager"; local connlisteners = require "net.connlisteners"; local cm_register_component = require "core.componentmanager".register_component; local cm_deregister_component = require "core.componentmanager".deregister_component; local uuid_gen = require "util.uuid".generate; local sha1 = require "util.hashes".sha1; local st = require "util.stanza"; local init_xmlhandlers = require "core.xmlhandlers"; local sessions = {}; local log = logger.init("componentlistener"); local component_listener = { default_port = 5347; default_mode = "*a"; default_interface = config.get("*", "core", "component_interface") or "127.0.0.1" }; local xmlns_component = 'jabber:component:accept'; --- Callbacks/data for xmlhandlers to handle streams for us --- local stream_callbacks = { default_ns = xmlns_component }; local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams"; function stream_callbacks.error(session, error, data, data2) log("warn", "Error processing component stream: "..tostring(error)); if error == "no-stream" then session:close("invalid-namespace"); elseif error == "parse-error" then session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(data)); session:close("xml-not-well-formed"); elseif error == "stream-error" then local condition, text = "undefined-condition"; for child in data:children() do if child.attr.xmlns == xmlns_xmpp_streams then if child.name ~= "text" then condition = child.name; else text = child:get_text(); end if condition ~= "undefined-condition" and text then break; end end end text = condition .. (text and (" ("..text..")") or ""); session.log("info", "Session closed by remote with error: %s", text); session:close(nil, text); end end function stream_callbacks.streamopened(session, attr) if config.get(attr.to, "core", "component_module") ~= "component" then -- Trying to act as a component domain which -- hasn't been configured session:close{ condition = "host-unknown", text = tostring(attr.to).." does not match any configured external components" }; return; end -- Store the original host (this is used for config, etc.) session.user = attr.to; -- Set the host for future reference session.host = config.get(attr.to, "core", "component_address") or attr.to; -- Note that we don't create the internal component -- until after the external component auths successfully session.streamid = uuid_gen(); session.notopen = nil; session.send(st.stanza("stream:stream", { xmlns=xmlns_component, ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.host }):top_tag()); end function stream_callbacks.streamclosed(session) session.send("</stream:stream>"); session.notopen = true; end local core_process_stanza = core_process_stanza; function stream_callbacks.handlestanza(session, stanza) -- Namespaces are icky. if not stanza.attr.xmlns and stanza.name == "handshake" then stanza.attr.xmlns = xmlns_component; end return core_process_stanza(session, stanza); end --- Closing a component connection local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'}; local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" }; local function session_close(session, reason) local log = session.log or log; if session.conn then if session.notopen then session.send("<?xml version='1.0'?>"); session.send(st.stanza("stream:stream", default_stream_attr):top_tag()); end if reason then if type(reason) == "string" then -- assume stream error log("info", "Disconnecting component, <stream:error> is: %s", reason); session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' })); elseif type(reason) == "table" then if reason.condition then local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up(); if reason.text then stanza:tag("text", stream_xmlns_attr):text(reason.text):up(); end if reason.extra then stanza:add_child(reason.extra); end log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza)); session.send(stanza); elseif reason.name then -- a stanza log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason)); session.send(reason); end end end session.send("</stream:stream>"); session.conn:close(); component_listener.ondisconnect(session.conn, "stream error"); end end --- Component connlistener function component_listener.onincoming(conn, data) local session = sessions[conn]; if not session then local _send = conn.write; session = { type = "component", conn = conn, send = function (data) return _send(conn, tostring(data)); end }; sessions[conn] = session; -- Logging functions -- local conn_name = "jcp"..tostring(conn):match("[a-f0-9]+$"); session.log = logger.init(conn_name); session.close = session_close; session.log("info", "Incoming Jabber component connection"); local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "\1"); session.parser = parser; session.notopen = true; function session.data(conn, data) local ok, err = parser:parse(data); if ok then return; end session:close("xml-not-well-formed"); end session.dispatch_stanza = stream_callbacks.handlestanza; end if data then session.data(conn, data); end end function component_listener.ondisconnect(conn, err) local session = sessions[conn]; if session then (session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err)); if session.host then log("debug", "Deregistering component"); cm_deregister_component(session.host); hosts[session.host].connected = nil; end sessions[conn] = nil; for k in pairs(session) do session[k] = nil; end session = nil; end end connlisteners.register('xmppcomponent', component_listener);
net.xmppcomponent_listener: Fix to correctly handle stream errors from components
net.xmppcomponent_listener: Fix to correctly handle stream errors from components
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
f47cfbd8695e62f082c94c5c1c758a0472abfd0c
libremap-agent/luasrc/libremap/plugins/olsr.lua
libremap-agent/luasrc/libremap/plugins/olsr.lua
--[[ Copyright 2013 Patrick Grimm <patrick@lunatiki.de> Copyright 2013-2014 André Gaul <gaul@web-yard.de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local json = require 'luci.json' local nixio = require 'nixio' local string = require 'string' local uci = (require 'uci').cursor() local utl = require 'luci.util' local libremap = require 'luci.libremap' local util = require 'luci.libremap.util' -- get jsoninfo function fetch_jsoninfo(ip, port, cmd) local resp = utl.exec('echo /'..cmd..' | nc '..ip..' '..port) return json.decode(resp) end -- reverse lookup with stripping of mid. function lookup_olsr_ip(ip, version) if version==4 then local inet = 'inet' elseif version==6 then local inet = 'inet6' else error('ip version '..version..' unknown.') end -- get name local name = nixio.getnameinfo(ip, inet) if name ~= nil then -- remove 'midX.' from name return string.gsub(name, 'mid[0-9]*\.', '') else return nil end end -- get links for specified ip version (4 or 6) function fetch_links(version) -- set variables that depend on ip version if version==4 then local ip = '127.0.0.1' -- for jsoninfo local type = 'olsr4' -- type of alias/link elseif version==6 then local ip = '::1' local type = 'olsr6' else error('ip version '..version..' unknown.') end -- retrieve data from jsoninfo local olsr_links = fetch_jsoninfo(ip, '9090', 'links') -- init return values local aliases = {} local links = {} -- step through olsr_links for _, link in ipairs(olsr_links) do local ip_local = link['localIP'] local ip_remote = link['remoteIP'] -- unused at the moment: --local name_local = lookup_olsr_ip(ip_local, version) --local name_remote = lookup_olsr_ip(ip_remote, version) -- insert aliases aliases[ip_local] = 1 -- process link quality local quality = link['linkQuality'] -- TODO: process quality properly if quality<0 then quality = 0 elseif quality>1 then quality = 1 elseif not (quality>=0 and quality<=1) then quality = 0 end -- insert links links[#links+1] = { type = type, alias_local = ip_local, alias_remote = ip_remote, quality = quality, attributes = link } end -- fill in aliases local aliases_arr = {} for alias, _ in ipairs(aliases) do aliases_arr[#aliases_arr+1] = { type = type, alias = alias } end return aliases, links end -- appent array b to array a function append(a, b) local a = a or {} for _, v in ipairs(b) do a[#a+1] = v end return a end -- insert olsr info into doc function insert(doc) -- init fields in doc (if not yet present) doc.aliases = doc.aliases or {} doc.links = doc.links or {} -- get used ip version(s) from config local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion") local versions = {} if IpVersion == '4' then versions = {4} elseif IpVersion == '6' then versions = {6} elseif IpVersion == '6and4' then versions = {6, 4} end -- fetch links for used ip versions for _, version in pairs(versions) do local aliases, links = fetch_links(version) append(doc.aliases, aliases) append(doc.links, links) end end return { insert = insert }
--[[ Copyright 2013 Patrick Grimm <patrick@lunatiki.de> Copyright 2013-2014 André Gaul <gaul@web-yard.de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local json = require 'luci.json' local nixio = require 'nixio' local string = require 'string' local uci = (require 'uci').cursor() local utl = require 'luci.util' local libremap = require 'luci.libremap' local util = require 'luci.libremap.util' -- get jsoninfo function fetch_jsoninfo(ip, port, cmd) local resp = utl.exec('echo /'..cmd..' | nc '..ip..' '..port) return json.decode(resp) end -- reverse lookup with stripping of mid. function lookup_olsr_ip(ip, version) if version==4 then local inet = 'inet' elseif version==6 then local inet = 'inet6' else error('ip version '..version..' unknown.') end -- get name local name = nixio.getnameinfo(ip, inet) if name ~= nil then -- remove 'midX.' from name return string.gsub(name, 'mid[0-9]*\.', '') else return nil end end -- get links for specified ip version (4 or 6) function fetch_links(version) -- set variables that depend on ip version if version==4 then local ip = '127.0.0.1' -- for jsoninfo local type = 'olsr4' -- type of alias/link elseif version==6 then local ip = '::1' local type = 'olsr6' else error('ip version '..version..' unknown.') end -- retrieve data from jsoninfo local jsoninfo = fetch_jsoninfo(ip, '9090', 'links') if not jsoninfo or not jsoninfo.links then return {}, {} end local olsr_links = jsoninfo.links -- init return values local aliases = {} local links = {} -- step through olsr_links for _, link in ipairs(olsr_links) do local ip_local = link['localIP'] local ip_remote = link['remoteIP'] -- unused at the moment: --local name_local = lookup_olsr_ip(ip_local, version) --local name_remote = lookup_olsr_ip(ip_remote, version) -- insert aliases aliases[ip_local] = 1 -- process link quality local quality = link['linkQuality'] -- TODO: process quality properly if quality<0 then quality = 0 elseif quality>1 then quality = 1 elseif not (quality>=0 and quality<=1) then quality = 0 end -- insert links links[#links+1] = { type = type, alias_local = ip_local, alias_remote = ip_remote, quality = quality, attributes = link } end -- fill in aliases local aliases_arr = {} for alias, _ in ipairs(aliases) do aliases_arr[#aliases_arr+1] = { type = type, alias = alias } end return aliases, links end -- appent array b to array a function append(a, b) local a = a or {} for _, v in ipairs(b) do a[#a+1] = v end return a end -- insert olsr info into doc function insert(doc) -- init fields in doc (if not yet present) doc.aliases = doc.aliases or {} doc.links = doc.links or {} -- get used ip version(s) from config local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion") local versions = {} if IpVersion == '4' then versions = {4} elseif IpVersion == '6' then versions = {6} elseif IpVersion == '6and4' then versions = {6, 4} end -- fetch links for used ip versions for _, version in pairs(versions) do local aliases, links = fetch_links(version) append(doc.aliases, aliases) append(doc.links, links) end end return { insert = insert }
fix jsoninfo in olsr plugin
fix jsoninfo in olsr plugin
Lua
apache-2.0
libremap/libremap-agent-openwrt,rogerpueyo/libremap-agent-openwrt,libre-mesh/libremap-agent
1de1820baaa69dd0fa34cf743518ca6d5c96da99
examples/modularize.lua
examples/modularize.lua
#! /usr/bin/env lua -- -- nanovg-demo.lua -- Copyright (C) 2015 Adrian Perez <aperez@igalia.com> -- -- Distributed under terms of the MIT license. -- local eol = require("eol") local eol_load = eol.load local eol_type = eol.type local _setmetatable = setmetatable local _rawget = rawget local _rawset = rawset local _type = type -- -- Makes functions available (and memoized) in the "nvg" table, -- plus types in the "nvg.types" table. Note that prefixes are -- added automatically when looking up items from the library. -- local function modularize(lib) local type_prefix local func_prefix local library_name if _type(lib) == "table" then library_name = lib.library or lib[1] func_prefix = lib.function_prefix or lib.prefix or "" type_prefix = lib.type_prefix or lib.prefix or "" else library_name = lib func_prefix = "" type_prefix = "" end local library = eol_load(library_name) return _setmetatable({ __library = library, types = _setmetatable({ __library = library }, { __index = function (self, key) local t = _rawget(self, key) if t == nil then t = eol_type(library, type_prefix .. key) _rawset(self, key, t or false) end return t end, }), }, { __index = function (self, key) local f = _rawget(self, key) if f == nil then f = library[func_prefix .. key] _rawset(self, key, f or false) end return f end, }); end return modularize
#! /usr/bin/env lua -- -- modularize.lua -- Copyright (C) 2015 Adrian Perez <aperez@igalia.com> -- -- Distributed under terms of the MIT license. -- local eol = require("eol") local eol_load = eol.load local eol_type = eol.type local _setmetatable = setmetatable local _rawget = rawget local _rawset = rawset local _type = type -- -- Makes functions and types available (and memoized) in a table, -- Prefixes are added automatically when looking up items from the -- library, and different prefixes can be specified for functions -- and types. -- -- Usage example: -- -- png = require "modularize" { -- "libpng", prefix = "png_", type_prefix = "png_" -- } -- -- color = png.types.color_8() -- color.red = 255 -- color.green = 127 -- -- print(png.get_header_ver(nil)) -- local function modularize(lib) local type_prefix local func_prefix local library_name if _type(lib) == "table" then library_name = lib.library or lib[1] func_prefix = lib.function_prefix or lib.prefix or "" type_prefix = lib.type_prefix or lib.prefix or "" else library_name = lib func_prefix = "" type_prefix = "" end local library = eol_load(library_name) return _setmetatable({ __library = library, types = _setmetatable({ __library = library }, { __index = function (self, key) local t = _rawget(self, key) if t == nil then t = eol_type(library, type_prefix .. key) _rawset(self, key, t or false) end return t end, }), }, { __index = function (self, key) local f = _rawget(self, key) if f == nil then f = library[func_prefix .. key] _rawset(self, key, f or false) end return f end, }); end return modularize
examples: Fix header of modularize.lua script
examples: Fix header of modularize.lua script The script still included the old header, from when the code was extracted out of nanovg-demo.lua; this patch fixes that.
Lua
mit
aperezdc/eris,aperezdc/lua-eol,aperezdc/lua-eol,aperezdc/eris
2bac44f26a9b6edb1662dc97f0d555fba79bca93
gfx.lua
gfx.lua
local ffi = require 'ffi' local uuid = require 'uuid' local base64 = require 'base64' require 'pl.text'.format_operator() require 'image' local itorch = require 'itorch._env' require 'itorch.bokeh' local util = require 'itorch.util' -- Example: require 'image';itorch.image(image.scale(image.lena(),16,16)) function itorch.image(img, opts) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') if torch.type(img) == 'string' then -- assume that it is path if img:sub(#img-3) == '.svg' then return itorch.svg(img) else img = image.load(img, 3) -- TODO: revamp this to just directly load the blob, infer file prefix, and send. end end if torch.isTensor(img) or torch.type(img) == 'table' then opts = opts or {padding=2} opts.input = img local imgDisplay = image.toDisplayTensor(opts) if imgDisplay:dim() == 2 then imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2)) end local tmp = os.tmpname() .. '.png' image.save(tmp, imgDisplay) ------------------------------------------------------------- -- load the image back as binary blob local f = assert(torch.DiskFile(tmp,'r',true)):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() os.execute('rm -f ' .. tmp) ------------------------------------------------------------ local content = {} content.source = 'itorch' content.data = {} content.data['text/plain'] = 'Console does not support images' content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size)) content.metadata = { } content.metadata['image/png'] = {width = imgDisplay:size(3), height = imgDisplay:size(2)} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) else error('unhandled type in itorch.image:' .. torch.type(img)) end end local audio_template = [[ <div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div> ]] -- Example: itorch.audio('hello.mp3') function itorch.audio(fname) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac', 'mp3, wav, ogg, aac files supported. But found extension: ' .. ext) -- load the audio as binary blob local f = assert(torch.DiskFile(fname,'r',true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local base64audio = base64.encode(ffi.string(torch.data(buf), size)) local div_id = uuid.new() local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = audio_template % { div_id = div_id, extension = ext, base64audio = base64audio }; content.metadata = {} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end local video_template = [[ <div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div> ]] -- Example: itorch.video('hello.mp4') function itorch.video(fname) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) if ext == 'ogv' then ext = 'ogg' end assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm', 'mp4, ogg, webm files supported. But found extension: ' .. ext) -- load the video as binary blob local f = assert(torch.DiskFile(fname,'r',true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local base64video = base64.encode(ffi.string(torch.data(buf), size)) local div_id = uuid.new() local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = video_template % { div_id = div_id, extension = ext, base64video = base64video }; content.metadata = {} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end function itorch.lena() itorch.image(image.lena()) end local html_template = [[ <script type="text/javascript"> $(function() { $("#${window_id}").html('${html_content}'); // clear any previous plot in window_id }); </script> <div id="${div_id}"></div> ]] local function escape_js(s) -- single quite s = s:gsub("'","\'") -- double quote s = s:gsub('"','\"') -- backslash s = s:gsub("\\","\\\\") -- newline s = s:gsub("\n","\\n") -- carriage return s = s:gsub("\r","\\r") -- tab s = s:gsub("\t","\\t") -- backspace s = s:gsub("\b","\\b") -- form feed s = s:gsub("\f","\\f") return s end function itorch.html(html, window_id) html = escape_js(html) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') local div_id = uuid.new() window_id = window_id or div_id local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = html_template % { html_content = html, window_id = window_id, div_id = div_id }; content.metadata = {} -- send displayData local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end function itorch.svg(filename) -- first check if file exists. if paths.filep(filename) then local f = io.open(filename) local str = f:read("*all") f:close() return itorch.html(str) else -- try rendering as raw string return itorch.html(filename) end end local ok,err = pcall(function() require 'xlua' end) if ok then local progress_warning = false local last = os.clock() xlua.progress = function(i, n) -- make progress bar really slow in itorch if os.clock() - last > 15 then -- 15 seconds print('Progress: ' .. i .. ' / ' .. n) last = os.clock() end -- local m = util.msg('clear_output', itorch._msg) -- m.content = {} -- m.content.wait = true -- m.content.display = true -- util.ipyEncodeAndSend(itorch._iopub, m) -- itorch.html(progress_template % {}) end end return itorch;
local ffi = require 'ffi' local uuid = require 'uuid' local base64 = require 'base64' require 'pl.text'.format_operator() require 'image' local itorch = require 'itorch._env' require 'itorch.bokeh' local util = require 'itorch.util' -- Example: require 'image';itorch.image(image.scale(image.lena(),16,16)) function itorch.image(img, opts) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') if torch.type(img) == 'string' then -- assume that it is path if img:sub(#img-3) == '.svg' then return itorch.svg(img) else img = image.load(img, 3) -- TODO: revamp this to just directly load the blob, infer file prefix, and send. end end if torch.isTensor(img) or torch.type(img) == 'table' then opts = opts or {padding=2} opts.input = img local imgDisplay = image.toDisplayTensor(opts) if imgDisplay:dim() == 2 then imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2)) end local tmp = os.tmpname() .. '.png' image.save(tmp, imgDisplay) ------------------------------------------------------------- -- load the image back as binary blob local f = assert(torch.DiskFile(tmp,'r',true)):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() os.execute('rm -f ' .. tmp) ------------------------------------------------------------ local content = {} content.source = 'itorch' content.data = {} content.data['text/plain'] = 'Console does not support images' content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size)) content.metadata = { } content.metadata['image/png'] = {width = imgDisplay:size(3), height = imgDisplay:size(2)} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) else error('unhandled type in itorch.image:' .. torch.type(img)) end end local audio_template = [[ <div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div> ]] -- Example: itorch.audio('hello.mp3') function itorch.audio(fname) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac', 'mp3, wav, ogg, aac files supported. But found extension: ' .. ext) -- load the audio as binary blob local f = assert(torch.DiskFile(fname,'r',true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local base64audio = base64.encode(ffi.string(torch.data(buf), size)) local div_id = uuid.new() local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = audio_template % { div_id = div_id, extension = ext, base64audio = base64audio }; content.metadata = {} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end local video_template = [[ <div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div> ]] -- Example: itorch.video('hello.mp4') function itorch.video(fname) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) if ext == 'ogv' then ext = 'ogg' end assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm', 'mp4, ogg, webm files supported. But found extension: ' .. ext) -- load the video as binary blob local f = assert(torch.DiskFile(fname,'r',true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); local size = f:position()-1 f:seek(1) local buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local base64video = base64.encode(ffi.string(torch.data(buf), size)) local div_id = uuid.new() local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = video_template % { div_id = div_id, extension = ext, base64video = base64video }; content.metadata = {} local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end function itorch.lena() itorch.image(image.lena()) end local html_template = [[ <script type="text/javascript"> $(function() { $("#${window_id}").html('${html_content}'); // clear any previous plot in window_id }); </script> <div id="${div_id}"></div> ]] local function escape_js(s) -- backslash s = s:gsub("\\","\\\\") -- single quite s = s:gsub("'","\'") -- double quote s = s:gsub('"','\"') -- newline s = s:gsub("\n","\\n") -- carriage return s = s:gsub("\r","\\r") -- tab s = s:gsub("\t","\\t") -- backspace s = s:gsub("\b","\\b") -- form feed s = s:gsub("\f","\\f") return s end function itorch.html(html, window_id) html = escape_js(html) assert(itorch._iopub,'itorch._iopub socket not set') assert(itorch._msg,'itorch._msg not set') local div_id = uuid.new() window_id = window_id or div_id local content = {} content.source = 'itorch' content.data = {} content.data['text/html'] = html_template % { html_content = html, window_id = window_id, div_id = div_id }; content.metadata = {} -- send displayData local m = util.msg('display_data', itorch._msg) m.content = content util.ipyEncodeAndSend(itorch._iopub, m) return window_id end function itorch.svg(filename) -- first check if file exists. if paths.filep(filename) then local f = io.open(filename) local str = f:read("*all") f:close() return itorch.html(str) else -- try rendering as raw string return itorch.html(filename) end end local ok,err = pcall(function() require 'xlua' end) if ok then local progress_warning = false local last = os.clock() xlua.progress = function(i, n) -- make progress bar really slow in itorch if os.clock() - last > 15 then -- 15 seconds print('Progress: ' .. i .. ' / ' .. n) last = os.clock() end -- local m = util.msg('clear_output', itorch._msg) -- m.content = {} -- m.content.wait = true -- m.content.display = true -- util.ipyEncodeAndSend(itorch._iopub, m) -- itorch.html(progress_template % {}) end end return itorch;
Fix JS escaping in itorch.html()
Fix JS escaping in itorch.html() We need to escape backslash first. Otherwise, other special chars are handled incorrectly – backslash that is a result of escaping is escaped as well and that's not what we want.
Lua
bsd-3-clause
facebook/iTorch,facebook/iTorch
3484d7d8458276c5bb5fd63de0b7aa733acff43c
xmake/modules/package/tools/cmake.lua
xmake/modules/package/tools/cmake.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 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file cmake.lua -- -- imports import("core.base.option") import("lib.detect.find_file") -- get configs function _get_configs(package, configs) local configs = configs or {} local vs_runtime = package:config("vs_runtime") if vs_runtime then table.insert(configs, '-DCMAKE_CXX_FLAGS_DEBUG="/' .. vs_runtime .. 'd"') table.insert(configs, '-DCMAKE_CXX_FLAGS_RELEASE="/' .. vs_runtime .. '"') table.insert(configs, '-DCMAKE_C_FLAGS_DEBUG="/' .. vs_runtime .. 'd"') table.insert(configs, '-DCMAKE_C_FLAGS_RELEASE="/' .. vs_runtime .. '"') end return configs end -- install package function install(package, configs) -- enter build directory os.mkdir("build/install") local oldir = os.cd("build") -- init arguments local argv = {"-DCMAKE_INSTALL_PREFIX=" .. path.absolute("install")} if is_plat("windows") and is_arch("x64") then table.insert(argv, "-A") table.insert(argv, "x64") end for name, value in pairs(_get_configs(package, configs)) do value = tostring(value):trim() if type(name) == "number" then if value ~= "" then table.insert(argv, value) end else table.insert(argv, "--" .. name .. "=" .. value) end end table.insert(argv, '..') -- generate build file os.vrunv("cmake", argv) -- do build and install if is_host("windows") then local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!") os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32") local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj" if os.isfile(projfile) then os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release") os.cp("install/lib", package:installdir()) os.cp("install/include", package:installdir()) else os.cp("**.lib", package:installdir("lib")) os.cp("**.dll", package:installdir("lib")) os.cp("**.exp", package:installdir("lib")) end else os.vrun("make -j4") os.vrun("make install") os.cp("install/lib", package:installdir()) os.cp("install/include", package:installdir()) end os.cd(oldir) 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 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file cmake.lua -- -- imports import("core.base.option") import("lib.detect.find_file") -- get configs function _get_configs(package, configs) local configs = configs or {} if package:plat() == "windows" then local vs_runtime = package:config("vs_runtime") if vs_runtime then table.insert(configs, '-DCMAKE_CXX_FLAGS_DEBUG="/' .. vs_runtime .. 'd"') table.insert(configs, '-DCMAKE_CXX_FLAGS_RELEASE="/' .. vs_runtime .. '"') table.insert(configs, '-DCMAKE_C_FLAGS_DEBUG="/' .. vs_runtime .. 'd"') table.insert(configs, '-DCMAKE_C_FLAGS_RELEASE="/' .. vs_runtime .. '"') end end return configs end -- install package function install(package, configs) -- enter build directory os.mkdir("build/install") local oldir = os.cd("build") -- init arguments local argv = {"-DCMAKE_INSTALL_PREFIX=" .. path.absolute("install")} if is_plat("windows") and is_arch("x64") then table.insert(argv, "-A") table.insert(argv, "x64") end for name, value in pairs(_get_configs(package, configs)) do value = tostring(value):trim() if type(name) == "number" then if value ~= "" then table.insert(argv, value) end else table.insert(argv, "--" .. name .. "=" .. value) end end table.insert(argv, '..') -- generate build file os.vrunv("cmake", argv) -- do build and install if is_host("windows") then local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!") os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32") local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj" if os.isfile(projfile) then os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release") os.cp("install/lib", package:installdir()) os.cp("install/include", package:installdir()) else os.cp("**.lib", package:installdir("lib")) os.cp("**.dll", package:installdir("lib")) os.cp("**.exp", package:installdir("lib")) end else os.vrun("make -j4") os.vrun("make install") os.cp("install/lib", package:installdir()) os.cp("install/include", package:installdir()) end os.cd(oldir) end
fix get configs for cmake
fix get configs for cmake
Lua
apache-2.0
waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
de253ecbd45a583021d25fb87fb88a96ba1d04c1
core/portmanager.lua
core/portmanager.lua
local config = require "core.configmanager"; local certmanager = require "core.certmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table = table; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type, tonumber, ipairs, pairs = type, tonumber, ipairs, pairs; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode, ssl = listener.default_mode or "*a"; for interface in bind_interfaces do for port in bind_ports do port = tonumber(port); if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else -- Create SSL context for this service/port if service_info.encryption == "ssl" then local ssl_config = config.get("*", config_prefix.."ssl"); ssl = certmanager.create_context(service_info.name.." port "..port, "server", ssl_config and (ssl_config[port] or (ssl_config.certificate and ssl_config))); end -- Start listening on interface+port local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name, service_info) for name, interface, port, n, active_service in active_services:iter(service_name or service_info and service_info.name, nil, nil, nil) do if service_info == nil or active_service.service == service_info then close(interface, port); end end log("info", "Deactivated service '%s'", service_name or service_info.name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) log("debug", "Unregistering service: %s", service_name); local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end deactivate(nil, service_info); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
local config = require "core.configmanager"; local certmanager = require "core.certmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table = table; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type, tonumber, ipairs, pairs = type, tonumber, ipairs, pairs; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode, ssl = listener.default_mode or "*a"; for interface in bind_interfaces do for port in bind_ports do port = tonumber(port); if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local err; -- Create SSL context for this service/port if service_info.encryption == "ssl" then local ssl_config = config.get("*", config_prefix.."ssl"); ssl, err = certmanager.create_context(service_info.name.." port "..port, "server", ssl_config and (ssl_config[port] or (ssl_config.certificate and ssl_config))); if not ssl then log("error", "Error binding encrypted port for %s: %s", service_info.name, error_to_friendly_message(service_name, port, err) or "unknown error"); end end if not err then -- Start listening on interface+port local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name, service_info) for name, interface, port, n, active_service in active_services:iter(service_name or service_info and service_info.name, nil, nil, nil) do if service_info == nil or active_service.service == service_info then close(interface, port); end end log("info", "Deactivated service '%s'", service_name or service_info.name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) log("debug", "Unregistering service: %s", service_name); local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end deactivate(nil, service_info); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
portmanager: Show a friendly error message when initializing SSL fails (thanks MattJ for the entire patch that I fixed one line in)
portmanager: Show a friendly error message when initializing SSL fails (thanks MattJ for the entire patch that I fixed one line in)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
70dfaab45895ebb5db74522a44b1e375d0f7065f
share/lua/website/theonion.lua
share/lua/website/theonion.lua
-- libquvi-scripts -- Copyright (C) 2010-2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "theonion%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "theonion" local p = quvi.fetch(self.page_url) self.title = p:match("<title>(.-) |") or error("no match: media title") self.id = p:match('afns_video_id = "(.-)";') or error("no match: media ID") local s = p:match('http://www.theonion.com/video/(.-),') or error("no match: path") s = string.format( "http://videos.theonion.com/onion_video/auto/%s/%s-iphone.m4v", self.id, s) self.url = {s} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "theonion%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video/.-,%d+/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "theonion" self.id = self.page_url:match(',(%d+)/') or error('no match: media ID') local u = string.format('http://theonion.com/videos/embed/%s.json', self.id) local c = quvi.fetch(u, {fetch_type='config'}) self.title = c:match('"title":%s+"(.-)"') or error('no match: media title') self.thumbnail_url = c:match('"thumbnail":%s+"(.-)"') or '' self.url = {c:match('"video_url":%s+"(.-)"') or error('no match: media stream URL')} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: theonion.lua
FIX: theonion.lua
Lua
lgpl-2.1
DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts
8f66de12c190952e23e6d7c41a52b2868c203beb
modules/luci-base/luasrc/http.lua
modules/luci-base/luasrc/http.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler nil by default to let .content() work self.filehandler = nil -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";") local p = ";" .. name .. "=(.-);" local i, j, value = c:find(p) return value and urldecode(value) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback -- If input has already been parsed then any files are either in temporary files -- or are in self.message.params[key] if self.parsed_input then for param, value in pairs(self.message.params) do repeat -- We're only interested in files if (not value["file"]) then break end -- If we were able to write to temporary file if (value["fd"]) then fd = value["fd"] local eof = false repeat filedata = fd:read(1024) if (filedata:len() < 1024) then eof = true end callback({ name=value["name"], file=value["file"] }, filedata, eof) until (eof) fd:close() value["fd"] = nil -- We had to read into memory else -- There should only be one numbered value in table - the data for k, v in ipairs(value) do callback({ name=value["name"], file=value["file"] }, v, true) end end until true end end end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function content() return context.request:content() end function formvalue(name, noparse) return context.request:formvalue(name, noparse) end function formvaluetable(prefix) return context.request:formvaluetable(prefix) end function getcookie(name) return context.request:getcookie(name) end -- or the environment table itself. function getenv(name) return context.request:getenv(name) end function setfilehandler(callback) return context.request:setfilehandler(callback) end function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end function source() return context.request.input end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end if not context.headers["x-frame-options"] then header("X-Frame-Options", "SAMEORIGIN") end if not context.headers["x-xss-protection"] then header("X-XSS-Protection", "1; mode=block") end if not context.headers["x-content-type-options"] then header("X-Content-Type-Options", "nosniff") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end function splice(fd, size) coroutine.yield(6, fd, size) end function redirect(url) if url == "" then url = "/" end status(302, "Found") header("Location", url) close() end function build_querystring(q) local s = { "?" } for k, v in pairs(q) do if #s > 1 then s[#s+1] = "&" end s[#s+1] = urldecode(k) s[#s+1] = "=" s[#s+1] = urldecode(v) end return table.concat(s, "") end urldecode = util.urldecode urlencode = util.urlencode function write_json(x) util.serialize_json(x, write) end
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local lhttp = require "lucihttp" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler nil by default to let .content() work self.filehandler = nil -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) return lhttp.header_attribute("cookie; " .. (self:getenv("HTTP_COOKIE") or ""), name) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback if not self.parsed_input then return end -- If input has already been parsed then uploads are stored as unlinked -- temporary files pointed to by open file handles in the parameter -- value table. Loop all params, and invoke the file callback for any -- param with an open file handle. local name, value for name, value in pairs(self.message.params) do if type(value) == "table" then while value.fd do local data = value.fd:read(1024) local eof = (not data or data == "") callback(value, data, eof) if eof then value.fd:close() value.fd = nil end end end end end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function content() return context.request:content() end function formvalue(name, noparse) return context.request:formvalue(name, noparse) end function formvaluetable(prefix) return context.request:formvaluetable(prefix) end function getcookie(name) return context.request:getcookie(name) end -- or the environment table itself. function getenv(name) return context.request:getenv(name) end function setfilehandler(callback) return context.request:setfilehandler(callback) end function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end function source() return context.request.input end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end if not context.headers["x-frame-options"] then header("X-Frame-Options", "SAMEORIGIN") end if not context.headers["x-xss-protection"] then header("X-XSS-Protection", "1; mode=block") end if not context.headers["x-content-type-options"] then header("X-Content-Type-Options", "nosniff") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end function splice(fd, size) coroutine.yield(6, fd, size) end function redirect(url) if url == "" then url = "/" end status(302, "Found") header("Location", url) close() end function build_querystring(q) local s, n, k, v = {}, 1, nil, nil for k, v in pairs(q) do s[n+0] = (n == 1) and "?" or "&" s[n+1] = util.urlencode(k) s[n+2] = "=" s[n+3] = util.urlencode(v) n = n + 4 end return table.concat(s, "") end urldecode = util.urldecode urlencode = util.urlencode function write_json(x) util.serialize_json(x, write) end
luci-base: refactor luci.http
luci-base: refactor luci.http - Rewrite getcookie() to use liblucihttp header value parsing - Rewrite setfilehandler() to use local variables and have cleaner code - Fix build_querystring() to actually *en*code the given params Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
kuoruan/lede-luci,nmav/luci,rogerpueyo/luci,openwrt/luci,Noltari/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,remakeelectric/luci,nmav/luci,981213/luci-1,wongsyrone/luci-1,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,Noltari/luci,wongsyrone/luci-1,chris5560/openwrt-luci,981213/luci-1,kuoruan/lede-luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,Noltari/luci,wongsyrone/luci-1,rogerpueyo/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,kuoruan/luci,kuoruan/lede-luci,Noltari/luci,Noltari/luci,openwrt/luci,rogerpueyo/luci,chris5560/openwrt-luci,hnyman/luci,remakeelectric/luci,981213/luci-1,wongsyrone/luci-1,hnyman/luci,lbthomsen/openwrt-luci,artynet/luci,remakeelectric/luci,remakeelectric/luci,artynet/luci,lbthomsen/openwrt-luci,hnyman/luci,rogerpueyo/luci,hnyman/luci,openwrt/luci,rogerpueyo/luci,wongsyrone/luci-1,nmav/luci,nmav/luci,kuoruan/lede-luci,nmav/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,rogerpueyo/luci,remakeelectric/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,kuoruan/luci,981213/luci-1,981213/luci-1,openwrt-es/openwrt-luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,rogerpueyo/luci,wongsyrone/luci-1,kuoruan/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,981213/luci-1,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,remakeelectric/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,nmav/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,nmav/luci,kuoruan/lede-luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,hnyman/luci,remakeelectric/luci,artynet/luci,Noltari/luci,artynet/luci,chris5560/openwrt-luci,kuoruan/luci,openwrt/luci,artynet/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,rogerpueyo/luci,Noltari/luci,wongsyrone/luci-1,Noltari/luci,artynet/luci,remakeelectric/luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/luci,kuoruan/luci,Noltari/luci,981213/luci-1,nmav/luci
3e0dcbda6c0913c0e8915f7b296175db25a54414
nyagos.d/brace.lua
nyagos.d/brace.lua
share.org_brace_filter = nyagos.filter nyagos.filter = function(cmdline) if share.org_brace_filter then local cmdline_ = share.org_brace_filter(cmdline) if cmdline_ then cmdline = cmdline_ end end local save={} cmdline = cmdline:gsub("((['\"])[^%2]*%2)", function(s,_) local i=#save+1 save[i] = s return '\a('..i..')' end) repeat local last = true cmdline = cmdline:gsub("(%S*)(%b{})(%S*)", function(left,mid,right) local contents = string.sub(mid,2,-2) local result local init = 1 while true do local comma=string.find(contents,",",init,true) local value=left .. string.sub(contents,init,(comma or 0)-1) .. right if result then result = result .. " " .. value else result = value end if not comma then break end init = comma + 1 end if init > 1 then last = false return result else return nil end end) until last cmdline = cmdline:gsub("\a%((%d+)%)",function(s) return save[s+0] end) return cmdline end
share.org_brace_filter = nyagos.filter nyagos.filter = function(cmdline) if share.org_brace_filter then local cmdline_ = share.org_brace_filter(cmdline) if cmdline_ then cmdline = cmdline_ end end local save={} cmdline = cmdline:gsub('"[^"]*"', function(s) local i=#save+1 save[i] = s return '\a('..i..')' end) cmdline = cmdline:gsub("'[^']*'", function(s) local i=#save+1 save[i] = s return '\a('..i..')' end) repeat local last = true cmdline = cmdline:gsub("(%S*)(%b{})(%S*)", function(left,mid,right) local contents = string.sub(mid,2,-2) local result local init = 1 while true do local comma=string.find(contents,",",init,true) local value=left .. string.sub(contents,init,(comma or 0)-1) .. right if result then result = result .. " " .. value else result = value end if not comma then break end init = comma + 1 end if init > 1 then last = false return result else return nil end end) until last cmdline = cmdline:gsub("\a%((%d+)%)",function(s) return save[s+0] end) return cmdline end
Fix: brace expansion "{a,b,c}" worked even in quotated strings
Fix: brace expansion "{a,b,c}" worked even in quotated strings
Lua
bsd-3-clause
tyochiai/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos,nocd5/nyagos
0c4c013e63da9965d97eee07125e9087b20da070
util/timer.lua
util/timer.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local ns_addtimer = require "net.server".addtimer; local event = require "net.server".event; local event_base = require "net.server".event_base; local get_time = os.time; local t_insert = table.insert; local t_remove = table.remove; local ipairs, pairs = ipairs, pairs; local type = type; local data = {}; local new_data = {}; module "timer" local _add_task; if not event then function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end ns_addtimer(function() local current_time = get_time(); if #new_data > 0 then for _, d in pairs(new_data) do t_insert(data, d); end new_data = {}; end for i, d in pairs(data) do local t, func = d[1], d[2]; if t <= current_time then data[i] = nil; local r = func(current_time); if type(r) == "number" then _add_task(r, func); end end end end); else local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1; function _add_task(delay, func) event_base:addevent(nil, event.EV_TIMEOUT, function () local ret = func(); if ret then _add_task(ret, func); else return EVENT_LEAVE; end end , delay); end end add_task = _add_task; return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local ns_addtimer = require "net.server".addtimer; local event = require "net.server".event; local event_base = require "net.server".event_base; local get_time = os.time; local t_insert = table.insert; local t_remove = table.remove; local ipairs, pairs = ipairs, pairs; local type = type; local data = {}; local new_data = {}; module "timer" local _add_task; if not event then function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end ns_addtimer(function() local current_time = get_time(); if #new_data > 0 then for _, d in pairs(new_data) do t_insert(data, d); end new_data = {}; end for i, d in pairs(data) do local t, func = d[1], d[2]; if t <= current_time then data[i] = nil; local r = func(current_time); if type(r) == "number" then _add_task(r, func); end end end end); else local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1; function _add_task(delay, func) event_base:addevent(nil, 0, function () local ret = func(); if ret then return 0, ret; else return EVENT_LEAVE; end end , delay); end end add_task = _add_task; return _M;
util.timer: Use luaevent's built-in method of repeating an event (fixes a weird crash)
util.timer: Use luaevent's built-in method of repeating an event (fixes a weird crash)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
a6d697335788e7e90313bc726e84b5b017773860
lib/rules.hisilicon.lua
lib/rules.hisilicon.lua
package { name = 'ast-files' } package { name = 'make', { 'build', 'host' }, { 'install', 'host' } } package { name = 'android-cmake' } package { name = 'libuv', { 'build', 'target' }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'ffmpeg', { 'build', 'target', { 'ast-files', 'unpack' } }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'chicken', source = { branch = 'cmake' }, { 'build', 'host' }, { 'install', 'host' }, { 'build', 'target', { 'chicken', 'install', 'host' } }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } package { name = 'karaoke-player', { 'build', 'target', { 'android-cmake', 'install', 'unpack' }, { 'astindex', 'unpack' }, { 'chicken', 'install', 'target' }, { 'ffmpeg', 'install', 'target' }, { 'libuv', 'install', 'target' }, }, { 'install', 'target' } } package { name = 'firmware', { 'install', { 'karaoke-player', 'install', 'target' } }, { 'strip' }, { 'deploy' } }
package { name = 'ast-files' } package { name = 'make', { 'build', 'host' }, { 'install', 'host' } } package { name = 'android-cmake' } package { name = 'libuv', { 'build', 'target' }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'ffmpeg', { 'build', 'target', { 'ast-files', 'unpack' } }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'chicken', { 'build', 'host' }, { 'install', 'host' }, { 'build', 'target', { 'chicken', 'install', 'host' } }, { 'install', 'target', { 'firmware', 'unpack' } } } package { name = 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } package { name = 'karaoke-player', { 'build', 'target', { 'android-cmake', 'unpack' }, { 'astindex', 'unpack' }, { 'chicken', 'install', 'target' }, { 'ffmpeg', 'install', 'target' }, { 'libuv', 'install', 'target' }, }, { 'install', 'target' } } package { name = 'firmware', { 'install', { 'karaoke-player', 'install', 'target' } }, { 'strip' }, { 'deploy' } }
Fix android-cmake karaoke-player dependency in hisilicon rules
Fix android-cmake karaoke-player dependency in hisilicon rules
Lua
mit
bazurbat/jagen
59781aa8cf797e384be96f53867f0df58d301009
plugins/lyrics.lua
plugins/lyrics.lua
--[[ Copyright 2017 wrxck <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]]-- local lyrics = {} local mattata = require('mattata') local https = require('ssl.https') local url = require('socket.url') local json = require('dkjson') function lyrics:init(configuration) lyrics.arguments = 'lyrics <query>' lyrics.commands = mattata.commands( self.info.username, configuration.command_prefix ):command('lyrics').table lyrics.help = configuration.command_prefix .. 'lyrics <query> - Find the lyrics to the specified song.' end function lyrics.get_lyrics(input) local jstr, res = https.request('https://api.musixmatch.com/ws/1.1/track.search?apikey=' .. configuration.keys.lyrics .. '&q_track=' .. url.escape(input)) if res ~= 200 then return false end local jdat = json.decode(jstr) if jdat.message.header.available == 0 then jstr, res = https.request('https://api.musixmatch.com/ws/1.1/track.search?apikey=' .. configuration.keys.lyrics .. '&q=' .. url.escape(input)) if res ~= 200 then return false end jdat = json.decode(jstr) if jdat.message.header.available == 0 then return false end end local artist = mattata.bash_escape(musixmatch.message.body.track_list[1].track.artist_name):gsub('"', '\'') local track = mattata.bash_escape(musixmatch.message.body.track_list[1].track.track_name):gsub('"', '\'') local output = io.popen('python plugins/lyrics.py "' .. artist .. '" "' .. track .. '"'):read('*all') if output == nil or output == '' then return false end local title = '<b>' .. mattata.escape_html(jdat.message.body.track_list[1].track.track_name) .. '</b> ' .. mattata.escape_html(jdat.message.body.track_list[1].track.artist_name) .. '\n🕓 ' .. mattata.format_ms(math.floor(tonumber(jdat.message.body.track_list[1].track.track_length) * 1000)):gsub('^%d%d:', ''):gsub('^0', '') .. '\n\n' if output:match('^None\n$') then return false end return title .. mattata.escape_html(output), jdat.message.body.track_list[1].track.track_share_url, musixmatch.message.body.track_list[1].track.track_name, musixmatch.message.body.track_list[1].track.artist_name end function lyrics.get_spotify_url(input) local jstr, res = https.request('https://api.spotify.com/v1/search?q=' .. url.escape(input) .. '&type=track') if res ~= 200 then return false end local jdat = json.decode(jstr) if jdat.tracks.total == 0 then return false end return 'https://open.spotify.com/track/' .. jdat.tracks.items[1].id end function lyrics:on_inline_query(inline_query, configuration, language) local input = inline_query.query:gsub('^' .. configuration.command_prefix .. 'lyrics', ''):gsub(' - ', ' ') local output, musixmatch_url, track, artist = lyrics.get_lyrics(input) if not output then return end local jstr, res = https.request('https://api.spotify.com/v1/search?q=' .. url.escape(input) .. '&type=track') local keyboard = {} if res ~= 200 then keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } } end local jdat = json.decode(jstr) if jdat.tracks.total == 0 then keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } } else keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url }, { ['text'] = 'Spotify', ['url'] = 'https://open.spotify.com/track/' .. jdat.tracks.items[1].id } } } end return mattata.answer_inline_query( inline_query.id, json.encode( { { ['type'] = 'article', ['id'] = '1', ['title'] = track, ['description'] = artist, ['input_message_content'] = { ['message_text'] = output, ['parse_mode'] = 'html' }, ['reply_markup'] = keyboard } } ) ) end function lyrics:on_message(message, configuration, language) local input = mattata.input(message.text) if not input then return mattata.send_reply( message, lyrics.help ) end input = input:gsub(' - ', ' ') mattata.send_chat_action( message.chat.id, 'typing') local output, musixmatch_url = lyrics.get_lyrics(input) if not output then return mattata.send_reply( message, language.errors.results ) end local keyboard = {} local buttons = { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } local spotify_url = lyrics.get_spotify_url(input) if spotify_url then table.insert( buttons, { ['text'] = 'Spotify', ['url'] = spotify_url } ) end keyboard.inline_keyboard = { buttons } return mattata.send_message( message.chat.id, output, 'html', true, false, nil, json.encode(keyboard) ) end return lyrics
--[[ Copyright 2017 wrxck <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]]-- local lyrics = {} local mattata = require('mattata') local https = require('ssl.https') local url = require('socket.url') local json = require('dkjson') local configuration = require('configuration') function lyrics:init(configuration) lyrics.arguments = 'lyrics <query>' lyrics.commands = mattata.commands( self.info.username, configuration.command_prefix ):command('lyrics').table lyrics.help = configuration.command_prefix .. 'lyrics <query> - Find the lyrics to the specified song.' end function lyrics.get_lyrics(input) local jstr, res = https.request('https://api.musixmatch.com/ws/1.1/track.search?apikey=' .. configuration.keys.lyrics .. '&q_track=' .. url.escape(input)) if res ~= 200 then return false end local jdat = json.decode(jstr) if jdat.message.header.available == 0 or not jdat.message.body.track_list[1] then jstr, res = https.request('https://api.musixmatch.com/ws/1.1/track.search?apikey=' .. configuration.keys.lyrics .. '&q=' .. url.escape(input)) if res ~= 200 then return false end jdat = json.decode(jstr) if jdat.message.header.available == 0 or not jdat.message.body.track_list[1] then return false end end local artist = mattata.bash_escape(jdat.message.body.track_list[1].track.artist_name) local track = mattata.bash_escape(jdat.message.body.track_list[1].track.track_name) local output = io.popen('python plugins/lyrics.py "' .. artist:gsub('"', '\'') .. '" "' .. track:gsub('"', '\'') .. '"'):read('*all') if output == nil or output == '' then return false end local title = '<b>' .. mattata.escape_html(jdat.message.body.track_list[1].track.track_name) .. '</b> ' .. mattata.escape_html(jdat.message.body.track_list[1].track.artist_name) .. '\n🕓 ' .. mattata.format_ms(math.floor(tonumber(jdat.message.body.track_list[1].track.track_length) * 1000)):gsub('^%d%d:', ''):gsub('^0', '') .. '\n\n' if output:match('^None\n$') then return false end return title .. mattata.escape_html(output), jdat.message.body.track_list[1].track.track_share_url, jdat.message.body.track_list[1].track.track_name, jdat.message.body.track_list[1].track.artist_name end function lyrics.get_spotify_url(input) local jstr, res = https.request('https://api.spotify.com/v1/search?q=' .. url.escape(input) .. '&type=track') if res ~= 200 then return false end local jdat = json.decode(jstr) if jdat.tracks.total == 0 then return false end return 'https://open.spotify.com/track/' .. jdat.tracks.items[1].id end function lyrics:on_inline_query(inline_query, configuration, language) local input = inline_query.query:gsub('^' .. configuration.command_prefix .. 'lyrics', ''):gsub(' - ', ' ') local output, musixmatch_url, track, artist = lyrics.get_lyrics(input) if not output then return end local jstr, res = https.request('https://api.spotify.com/v1/search?q=' .. url.escape(input) .. '&type=track') local keyboard = {} if res ~= 200 then keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } } else local jdat = json.decode(jstr) if jdat.tracks.total == 0 then keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } } else keyboard.inline_keyboard = { { { ['text'] = 'musixmatch', ['url'] = musixmatch_url }, { ['text'] = 'Spotify', ['url'] = 'https://open.spotify.com/track/' .. jdat.tracks.items[1].id } } } end end return mattata.answer_inline_query( inline_query.id, json.encode( { { ['type'] = 'article', ['id'] = '1', ['title'] = track, ['description'] = artist, ['input_message_content'] = { ['message_text'] = output, ['parse_mode'] = 'html' }, ['reply_markup'] = keyboard } } ) ) end function lyrics:on_message(message, configuration, language) local input = mattata.input(message.text) if not input then return mattata.send_reply( message, lyrics.help ) end input = input:gsub(' - ', ' ') mattata.send_chat_action( message.chat.id, 'typing') local output, musixmatch_url = lyrics.get_lyrics(input) if not output then return mattata.send_reply( message, language.errors.results ) end local keyboard = {} local buttons = { { ['text'] = 'musixmatch', ['url'] = musixmatch_url } } local spotify_url = lyrics.get_spotify_url(input) if spotify_url then table.insert( buttons, { ['text'] = 'Spotify', ['url'] = spotify_url } ) end keyboard.inline_keyboard = { buttons } return mattata.send_message( message.chat.id, output, 'html', true, false, nil, json.encode(keyboard) ) end return lyrics
[v8] Fixed missing dependency in lyrics.lua
[v8] Fixed missing dependency in lyrics.lua
Lua
mit
barreeeiroo/BarrePolice
ba4c80644ec43df3fa2092a5a45678bdedf95422
mods/default/player.lua
mods/default/player.lua
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. --[[ API --- default.player_register_model(name, def) ^ Register a new model to be used by players. ^ <name> is the model filename such as "character.x", "foo.b3d", etc. ^ See Model Definition below for format of <def>. default.registered_player_models[name] ^ See Model Definition below for format. default.player_set_model(player, model_name) ^ <player> is a PlayerRef. ^ <model_name> is a model registered with player_register_model. default.player_set_animation(player, anim_name [, speed]) ^ <player> is a PlayerRef. ^ <anim_name> is the name of the animation. ^ <speed> is in frames per second. If nil, default from the model is used default.player_set_textures(player, textures) ^ <player> is a PlayerRef. ^ <textures> is an array of textures ^ If <textures> is nil, the default textures from the model def are used default.player_get_animation(player) ^ <player> is a PlayerRef. ^ Returns a table containing fields "model", "textures" and "animation". ^ Any of the fields of the returned table may be nil. Model Definition ---------------- model_def = { animation_speed = 30, -- Default animation speed, in FPS. textures = {"character.png", }, -- Default array of textures. visual_size = {x=1, y=1,}, -- Used to scale the model. animations = { -- <anim_name> = { x=<start_frame>, y=<end_frame>, }, foo = { x= 0, y=19, }, bar = { x=20, y=39, }, -- ... }, } ]] -- Player animation blending -- Note: This is currently broken due to a bug in Irrlicht, leave at 0 local animation_blend = 0 default.registered_player_models = { } -- Local for speed. local models = default.registered_player_models function default.player_register_model(name, def) models[name] = def end -- Default player appearance default.player_register_model("character.x", { animation_speed = 30, textures = {"character.png", }, animations = { -- Standard animations. stand = { x= 0, y= 79, }, lay = { x=162, y=166, }, walk = { x=168, y=187, }, mine = { x=189, y=198, }, walk_mine = { x=200, y=219, }, -- Extra animations (not currently used by the game). sit = { x= 81, y=160, }, }, }) -- Player stats and animations local player_model = {} local player_textures = {} local player_anim = {} local player_sneak = {} function default.player_get_animation(player) local name = player:get_player_name() return { model = player_model[name], textures = player_textures[name], animation = player_anim[name], } end -- Called when a player's appearance needs to be updated function default.player_set_model(player, model_name) local name = player:get_player_name() local model = models[model_name] if model then if player_model[name] == model_name then return end player:set_properties({ mesh = model_name, textures = player_textures[name] or model.textures, visual = "mesh", visual_size = model.visual_size or {x=1, y=1}, }) default.player_set_animation(player, "stand") else player:set_properties({ textures = { "player.png", "player_back.png", }, visual = "upright_sprite", }) end player_model[name] = model_name end function default.player_set_textures(player, textures) local name = player:get_player_name() player_textures[name] = textures player:set_properties({textures = textures,}) end function default.player_set_animation(player, anim_name, speed) local name = player:get_player_name() if player_anim[name] == anim_name then return end local model = player_model[name] and models[player_model[name]] if not (model and model.animations[anim_name]) then return end local anim = model.animations[anim_name] player_anim[name] = anim_name player:set_animation(anim, speed or model.animation_speed, animation_blend) end -- Update appearance when the player joins minetest.register_on_joinplayer(function(player) default.player_set_model(player, "character.x") end) -- Localize for better performance. local player_set_animation = default.player_set_animation -- Check each player and apply animations minetest.register_globalstep(function(dtime) for _, player in pairs(minetest.get_connected_players()) do local name = player:get_player_name() local model_name = player_model[name] local model = model_name and models[model_name] if model then local controls = player:get_player_control() local walking = false local animation_speed_mod = model.animation_speed or 30 -- Determine if the player is walking if controls.up or controls.down or controls.left or controls.right then walking = true end -- Determine if the player is sneaking, and reduce animation speed if so if controls.sneak then animation_speed_mod = animation_speed_mod / 2 end -- Apply animations based on what the player is doing if player:get_hp() == 0 then player_set_animation(player, "lay") elseif walking then if player_sneak[name] ~= controls.sneak then player_anim[name] = nil player_sneak[name] = controls.sneak end if controls.LMB then player_set_animation(player, "walk_mine", animation_speed_mod) else player_set_animation(player, "walk", animation_speed_mod) end elseif controls.LMB then player_set_animation(player, "mine") else player_set_animation(player, "stand", animation_speed_mod) end end end end)
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. --[[ API --- default.player_register_model(name, def) ^ Register a new model to be used by players. ^ <name> is the model filename such as "character.x", "foo.b3d", etc. ^ See Model Definition below for format of <def>. default.registered_player_models[name] ^ See Model Definition below for format. default.player_set_model(player, model_name) ^ <player> is a PlayerRef. ^ <model_name> is a model registered with player_register_model. default.player_set_animation(player, anim_name [, speed]) ^ <player> is a PlayerRef. ^ <anim_name> is the name of the animation. ^ <speed> is in frames per second. If nil, default from the model is used default.player_set_textures(player, textures) ^ <player> is a PlayerRef. ^ <textures> is an array of textures ^ If <textures> is nil, the default textures from the model def are used default.player_get_animation(player) ^ <player> is a PlayerRef. ^ Returns a table containing fields "model", "textures" and "animation". ^ Any of the fields of the returned table may be nil. Model Definition ---------------- model_def = { animation_speed = 30, -- Default animation speed, in FPS. textures = {"character.png", }, -- Default array of textures. visual_size = {x=1, y=1,}, -- Used to scale the model. animations = { -- <anim_name> = { x=<start_frame>, y=<end_frame>, }, foo = { x= 0, y=19, }, bar = { x=20, y=39, }, -- ... }, } ]] -- Player animation blending -- Note: This is currently broken due to a bug in Irrlicht, leave at 0 local animation_blend = 0 default.registered_player_models = { } -- Local for speed. local models = default.registered_player_models function default.player_register_model(name, def) models[name] = def end -- Default player appearance default.player_register_model("character.x", { animation_speed = 30, textures = {"character.png", }, animations = { -- Standard animations. stand = { x= 0, y= 79, }, lay = { x=162, y=166, }, walk = { x=168, y=187, }, mine = { x=189, y=198, }, walk_mine = { x=200, y=219, }, -- Extra animations (not currently used by the game). sit = { x= 81, y=160, }, }, }) -- Player stats and animations local player_model = {} local player_textures = {} local player_anim = {} local player_sneak = {} function default.player_get_animation(player) local name = player:get_player_name() return { model = player_model[name], textures = player_textures[name], animation = player_anim[name], } end -- Called when a player's appearance needs to be updated function default.player_set_model(player, model_name) local name = player:get_player_name() local model = models[model_name] if model then if player_model[name] == model_name then return end player:set_properties({ mesh = model_name, textures = player_textures[name] or model.textures, visual = "mesh", visual_size = model.visual_size or {x=1, y=1}, }) default.player_set_animation(player, "stand") else player:set_properties({ textures = { "player.png", "player_back.png", }, visual = "upright_sprite", }) end player_model[name] = model_name end function default.player_set_textures(player, textures) local name = player:get_player_name() player_textures[name] = textures player:set_properties({textures = textures,}) end function default.player_set_animation(player, anim_name, speed) local name = player:get_player_name() if player_anim[name] == anim_name then return end local model = player_model[name] and models[player_model[name]] if not (model and model.animations[anim_name]) then return end local anim = model.animations[anim_name] player_anim[name] = anim_name player:set_animation(anim, speed or model.animation_speed, animation_blend) end -- Update appearance when the player joins minetest.register_on_joinplayer(function(player) default.player_set_model(player, "character.x") end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() player_model[name] = nil player_anim[name] = nil player_textures[name] = nil end) -- Localize for better performance. local player_set_animation = default.player_set_animation -- Check each player and apply animations minetest.register_globalstep(function(dtime) for _, player in pairs(minetest.get_connected_players()) do local name = player:get_player_name() local model_name = player_model[name] local model = model_name and models[model_name] if model then local controls = player:get_player_control() local walking = false local animation_speed_mod = model.animation_speed or 30 -- Determine if the player is walking if controls.up or controls.down or controls.left or controls.right then walking = true end -- Determine if the player is sneaking, and reduce animation speed if so if controls.sneak then animation_speed_mod = animation_speed_mod / 2 end -- Apply animations based on what the player is doing if player:get_hp() == 0 then player_set_animation(player, "lay") elseif walking then if player_sneak[name] ~= controls.sneak then player_anim[name] = nil player_sneak[name] = controls.sneak end if controls.LMB then player_set_animation(player, "walk_mine", animation_speed_mod) else player_set_animation(player, "walk", animation_speed_mod) end elseif controls.LMB then player_set_animation(player, "mine") else player_set_animation(player, "stand", animation_speed_mod) end end end end)
Fix player skin changing code.
Fix player skin changing code.
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
0bcdd82e94e19e6ac9da4732f25f1bfd2f39d139
nyagos.d/catalog/git.lua
nyagos.d/catalog/git.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = {} local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do files[#files+1] = string.sub(line,4) end fd:close() return files end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then local t = gitsubcommands[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" then return t end end end end -- EOF
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = {} local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do files[#files+1] = string.sub(line,4) end fd:close() return files end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end local t = gitsubcommands[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" and #args == 2 then return t end end end -- EOF
Completion for git add: fix: only one arg was completed
Completion for git add: fix: only one arg was completed
Lua
bsd-3-clause
tsuyoshicho/nyagos,zetamatta/nyagos
8429bbb464ec37752922aacc2eee79d448d3ef5c
hammerspoon/init.lua
hammerspoon/init.lua
-- API Doc : http://www.hammerspoon.org/docs/ -- KeyCodes : http://www.hammerspoon.org/docs/hs.keycodes.html#map -- Force launch or focus an app by name (fix issues with Finder) -- @see https://github.com/cmsj/hammerspoon-config/blob/master/init.lua#L156 -- @see http://liuhao.im/english/2017/06/02/macos-automation-and-shortcuts-with-hammerspoon.html function launchOrFocusOrHide(appname) local app = hs.appfinder.appFromName(appname) if not app then if appname == "Calendrier" then hs.application.launchOrFocus("Calendar") else hs.application.launchOrFocus(appname) end return end if appname == "Finder" then app:activate(true) app:unhide() return end local mainwin = app:mainWindow() if mainwin then if mainwin == hs.window.focusedWindow() then app:hide() else app:activate(true) app:unhide() mainwin:focus() end end end -- Set a screen grid size hs.grid.setGrid('12x12') hs.grid.setMargins('0x0') -- Key bindings hs.hotkey.bind({"ctrl"}, "t", function() launchOrFocusOrHide("iTerm") end) hs.hotkey.bind({"ctrl"}, "g", function() launchOrFocusOrHide("Google Chrome") end) hs.hotkey.bind({"ctrl"}, "s", function() launchOrFocusOrHide("Sublime Text") end) hs.hotkey.bind({"ctrl"}, "e", function() launchOrFocusOrHide("Finder") end) hs.hotkey.bind({"ctrl"}, "v", function() launchOrFocusOrHide("Filezilla") end) hs.hotkey.bind({"ctrl"}, "q", function() launchOrFocusOrHide("Calendrier") end) hs.hotkey.bind({"ctrl"}, "a", function() launchOrFocusOrHide("Slack") end) hs.hotkey.bind({"ctrl"}, "b", function() launchOrFocusOrHide("Sequel Pro") end) hs.hotkey.bind({"ctrl"}, "m", function() hs.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend") end) hs.hotkey.bind({"ctrl"}, "p", function() hs.execute("/usr/local/bin/subl /Users/lucvancrayelynghe/TODO.md") end) -- hs.hotkey.bind({"ctrl"}, "m", function() launchOrFocusOrHide("Mail") end) hs.hotkey.bind({"ctrl"}, "h", function() hs.grid.resizeWindowShorter(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "j", function() hs.grid.resizeWindowThinner(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "k", function() hs.grid.resizeWindowWider(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "l", function() hs.grid.resizeWindowTaller(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "h", function() hs.grid.pushWindowUp(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "j", function() hs.grid.pushWindowLeft(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "k", function() hs.grid.pushWindowRight(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "l", function() hs.grid.pushWindowDown(hs.window.focusedWindow()) end) -- Toggle Fullscreen -- hs.hotkey.bind({"ctrl"}, "f", function() -- local win = hs.window.focusedWindow() -- win:toggleFullScreen() -- end) -- Close active window -- hs.hotkey.bind({"ctrl"}, "x", function() -- local win = hs.window.focusedWindow() -- win:application():kill() -- end) -- Chrome reload hs.hotkey.bind({"ctrl"}, "i", function() local script = [[tell application "Chrome" to tell the active tab of its first window reload end tell]] hs.osascript.applescript(script) end) -- Caffeinate local caffeine = hs.menubar.new() function setCaffeineDisplay(state) if state then caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-on.pdf") else caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-off.pdf") end end function caffeineClicked() setCaffeineDisplay(hs.caffeinate.toggle("displayIdle")) end if caffeine then caffeine:setClickCallback(caffeineClicked) setCaffeineDisplay(hs.caffeinate.get("displayIdle")) end -- Autoconfig reload function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config reloaded !"}):send() end end local configWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
-- API Doc : http://www.hammerspoon.org/docs/ -- KeyCodes : http://www.hammerspoon.org/docs/hs.keycodes.html#map -- Force launch or focus an app by name (fix issues with Finder) -- @see https://github.com/cmsj/hammerspoon-config/blob/master/init.lua#L156 -- @see http://liuhao.im/english/2017/06/02/macos-automation-and-shortcuts-with-hammerspoon.html function launchOrFocusOrHide(appname) local app = hs.appfinder.appFromName(appname) if not app then if appname == "Calendrier" then hs.application.launchOrFocus("Calendar") else hs.application.launchOrFocus(appname) end return end if appname == "Finder" then app:activate(true) app:unhide() return end local mainwin = app:mainWindow() if mainwin then if mainwin == hs.window.focusedWindow() then app:hide() else app:activate(true) app:unhide() mainwin:focus() end else if appname == "Calendrier" then app:activate(true) app:unhide() app:selectMenuItem({'Fenêtre', 'Calendrier'}) app:mainWindow():focus() return end end end -- Set a screen grid size hs.grid.setGrid('12x12') hs.grid.setMargins('0x0') -- Key bindings hs.hotkey.bind({"ctrl"}, "t", function() launchOrFocusOrHide("iTerm") end) hs.hotkey.bind({"ctrl"}, "g", function() launchOrFocusOrHide("Google Chrome") end) hs.hotkey.bind({"ctrl"}, "s", function() launchOrFocusOrHide("Sublime Text") end) hs.hotkey.bind({"ctrl"}, "e", function() launchOrFocusOrHide("Finder") end) hs.hotkey.bind({"ctrl"}, "v", function() launchOrFocusOrHide("Filezilla") end) hs.hotkey.bind({"ctrl"}, "q", function() launchOrFocusOrHide("Calendrier") end) hs.hotkey.bind({"ctrl"}, "a", function() launchOrFocusOrHide("Slack") end) hs.hotkey.bind({"ctrl"}, "b", function() launchOrFocusOrHide("Sequel Pro") end) hs.hotkey.bind({"ctrl"}, "m", function() hs.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend") end) hs.hotkey.bind({"ctrl"}, "p", function() hs.execute("/usr/local/bin/subl /Users/lucvancrayelynghe/TODO.md") end) -- hs.hotkey.bind({"ctrl"}, "m", function() launchOrFocusOrHide("Mail") end) hs.hotkey.bind({"ctrl"}, "h", function() hs.grid.resizeWindowShorter(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "j", function() hs.grid.resizeWindowThinner(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "k", function() hs.grid.resizeWindowWider(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl"}, "l", function() hs.grid.resizeWindowTaller(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "h", function() hs.grid.pushWindowUp(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "j", function() hs.grid.pushWindowLeft(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "k", function() hs.grid.pushWindowRight(hs.window.focusedWindow()) end) hs.hotkey.bind({"ctrl", "cmd"}, "l", function() hs.grid.pushWindowDown(hs.window.focusedWindow()) end) -- Toggle Fullscreen -- hs.hotkey.bind({"ctrl"}, "f", function() -- local win = hs.window.focusedWindow() -- win:toggleFullScreen() -- end) -- Close active window -- hs.hotkey.bind({"ctrl"}, "x", function() -- local win = hs.window.focusedWindow() -- win:application():kill() -- end) -- Chrome reload hs.hotkey.bind({"ctrl"}, "u", function() local script = [[tell application "Chrome" to tell the active tab of its first window reload end tell]] hs.osascript.applescript(script) end) -- Caffeinate local caffeine = hs.menubar.new() function setCaffeineDisplay(state) if state then caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-on.pdf") else caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-off.pdf") end end function caffeineClicked() setCaffeineDisplay(hs.caffeinate.toggle("displayIdle")) end if caffeine then caffeine:setClickCallback(caffeineClicked) setCaffeineDisplay(hs.caffeinate.get("displayIdle")) end -- Autoconfig reload function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config reloaded !"}):send() end end local configWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
Fix Hammerspoon config
Fix Hammerspoon config
Lua
mit
Benoth/dotfiles,Benoth/dotfiles
98bebf55cf4f04e4231577f037c7769b6231f647
RNN-train-sample/train.lua
RNN-train-sample/train.lua
-- Eugenio Culurciello -- September 2016 -- RNN training test: ABBA / 1221 sequence detector -- based on: https://raw.githubusercontent.com/karpathy/char-rnn/master/model/RNN.lua require 'nn' require 'nngraph' require 'optim' dofile('RNN.lua') local model_utils = require 'model_utils' torch.setdefaulttensortype('torch.FloatTensor') -- nngraph.setDebug(true) local opt = {} opt.dictionary_size = 2 -- sequence of 2 symbols opt.train_size = 100000 -- train data size opt.seq_length = 4 -- RNN time steps print('Creating Input...') -- create a sequence of 2 numbers: {2, 1, 2, 2, 1, 1, 2, 2, 1 ..} local s = torch.Tensor(opt.train_size):random(2) -- print('Inputs sequence:', s:view(1,-1)) local y = torch.ones(1, opt.train_size) for i = 4, opt.train_size do -- if you find sequence ...1001... then output is class '2', otherwise is '1' if (s[{i-3}]==1 and s[{i-2}]==2 and s[{i-1}]==2 and s[{i}]==1) then y[{1,{i}}] = 2 end end print('Desired sequence:', y) local x = torch.zeros(2, opt.train_size) -- create input with 1-hot encoding: for i = 1, opt.train_size do if y[{{},{i}}][1][1] > 1 then x[{{},{i}}] = torch.Tensor{0,1} else x[{{},{i}}] = torch.Tensor{1,0} end end print('Input vector:', x) -- model: print('Creating Model...') opt.rnn_size = 10 opt.rnn_layers = 1 opt.batch_size = 1 local protos = {} protos.rnn = RNN(opt.dictionary_size, opt.rnn_size, opt.rnn_layers, 0) -- input = 2 (classes), 1 layer, rnn_size=1, no dropout protos.criterion = nn.ClassNLLCriterion() -- print('Test of RNN output:', RNNmodel:forward{ torch.Tensor(2), torch.Tensor(1) }) -- the initial state of the cell/hidden states local init_state = {} for L = 1, opt.rnn_layers do local h_init = torch.zeros(opt.batch_size, opt.rnn_size) table.insert(init_state, h_init:clone()) end local params, grad_params -- get flattened parameters tensor -- params, grad_params = model_utils.combine_all_parameters(protos.rnn) params, grad_params = protos.rnn:getParameters() print('Number of parameters in the model: ' .. params:nElement()) -- print(params, grad_params) -- create clones of model to unroll in time: print('Cloning RNN model:') local clones = {} clones.rnn = {} clones.criterion = {} for i = 1,opt.seq_length do clones.rnn[i] = protos.rnn:clone('weight', 'gradWeights', 'gradBias', 'bias') clones.criterion[i] = protos.criterion:clone() end -- for name, proto in pairs(protos) do -- print('cloning ' .. name) -- clones[name] = model_utils.clone_many_times(proto, opt.seq_length, not proto.parameters) -- end function clone_list(tensor_list, zero_too) -- takes a list of tensors and returns a list of cloned tensors local out = {} for k,v in pairs(tensor_list) do out[k] = v:clone() if zero_too then out[k]:zero() end end return out end -- training function: local init_state_global = clone_list(init_state) local bo = 0 -- batch offset / counter opt.grad_clip = 5 function feval(p) if p ~= params then params:copy(p) end grad_params:zero() -- bo variable creates batches on the fly -- forward pass --------------------------------------------------------------- local rnn_state = {[0]=init_state_global} -- initial state local predictions = {} local loss = 0 for t = 1, opt.seq_length do clones.rnn[t]:training() -- make sure we are in correct training mode -- print( 'sample,target:', x[{{},{t+bo}}], y[{1,{t+bo}}] ) local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])} rnn_state[t] = {} for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output predictions[t] = lst[#lst] loss = loss + clones.criterion[t]:forward(predictions[t], y[{1,{t+bo}}]) end loss = loss / opt.seq_length -- backward pass -------------------------------------------------------------- -- initialize gradient at time t to be zeros (there's no influence from future) local drnn_state = {[opt.seq_length] = clone_list(init_state, true)} -- true also zeros the clones for t = opt.seq_length, 1, -1 do -- print(drnn_state) -- backprop through loss, and softmax/linear -- print(predictions[t], y[{1,{t+bo}}]) local doutput_t = clones.criterion[t]:backward(predictions[t], y[{1,{t+bo}}]) -- print('douptut', doutput_t) table.insert(drnn_state[t], doutput_t) local dlst = clones.rnn[t]:backward({x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}, drnn_state[t]) drnn_state[t-1] = {} for k,v in pairs(dlst) do if k > 1 then -- k == 1 is gradient on x, which we dont need -- note we do k-1 because first item is dembeddings, and then follow the -- derivatives of the state, starting at index 2. I know... drnn_state[t-1][k-1] = v end end end -- transfer final state to initial state (BPTT) init_state_global = rnn_state[#rnn_state] -- grad_params:div(opt.seq_length) -- clip gradient element-wise grad_params:clamp(-opt.grad_clip, opt.grad_clip) -- print(params,grad_params) -- point to next batch: bo = bo + opt.seq_length return loss, grad_params end -- training: opt.learning_rate = 2e-3 opt.decay_rate = 0.95 print('Training...') local losses = {} local optim_state = {learningRate = opt.learning_rate, alpha = opt.decay_rate} local iterations = opt.train_size/opt.seq_length for i = 1, iterations do local _, loss = optim.rmsprop(feval, params, optim_state) losses[#losses + 1] = loss[1] if i % (iterations/10) == 0 then print(string.format("Iteration %8d, loss = %4.4f, loss/seq_len = %4.4f, gradnorm = %4.4e", i, loss[1], loss[1] / opt.seq_length, grad_params:norm())) end end -- testing function: bo = 0 function test() -- bo variable creates batches on the fly -- forward pass --------------------------------------------------------------- local rnn_state = {[0]=init_state} -- initial state local predictions = {} local loss = 0 for t = 1, opt.seq_length do clones.rnn[t]:evaluate() -- make sure we are in correct testing mode local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])} rnn_state[t] = {} for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output predictions[t] = lst[#lst] end -- carry over lstm state rnn_state[0] = rnn_state[#rnn_state] -- print results: local max, idx max,idx = torch.max( predictions[opt.seq_length], 2) print('Prediction:', idx[1][1], 'Label:', y[{1,{opt.seq_length+bo}}][1]) -- point to next batch: bo = bo + opt.seq_length end -- and test! opt.test_samples = 30 for i = 1, opt.test_samples do test() end
-- Eugenio Culurciello -- September 2016 -- RNN training test: ABBA / 1221 sequence detector -- based on: https://raw.githubusercontent.com/karpathy/char-rnn/master/model/RNN.lua require 'nn' require 'nngraph' require 'optim' dofile('RNN.lua') local model_utils = require 'model_utils' torch.setdefaulttensortype('torch.FloatTensor') -- nngraph.setDebug(true) local opt = {} opt.dictionary_size = 2 -- sequence of 2 symbols opt.train_size = 10000 -- train data size opt.seq_length = 4 -- RNN time steps print('Creating Input...') -- create a sequence of 2 numbers: {2, 1, 2, 2, 1, 1, 2, 2, 1 ..} local s = torch.Tensor(opt.train_size):random(2) print('Inputs sequence:', s:view(1,-1)) local y = torch.ones(1, opt.train_size) for i = 4, opt.train_size do -- if you find sequence ...1001... then output is class '2', otherwise is '1' if (s[{i-3}]==1 and s[{i-2}]==2 and s[{i-1}]==2 and s[{i}]==1) then y[{1,{i}}] = 2 end -- if (s[{i-1}]==1 and s[{i}]==2) then y[{1,{i}}] = 2 end -- detect one 1-2 sequence end print('Desired sequence:', y) local x = torch.zeros(2, opt.train_size) -- create input with 1-hot encoding: for i = 1, opt.train_size do if y[{{},{i}}][1][1] > 1 then x[{{},{i}}] = torch.Tensor{0,1} else x[{{},{i}}] = torch.Tensor{1,0} end end print('Input vector:', x) -- model: print('Creating Model...') opt.rnn_size = 10 opt.rnn_layers = 1 opt.batch_size = 1 local protos = {} protos.rnn = RNN(opt.dictionary_size, opt.rnn_size, opt.rnn_layers, 0) -- input = 2 (classes), 1 layer, rnn_size=1, no dropout protos.criterion = nn.ClassNLLCriterion() -- print('Test of RNN output:', RNNmodel:forward{ torch.Tensor(2), torch.Tensor(1) }) -- the initial state of the cell/hidden states local init_state = {} for L = 1, opt.rnn_layers do local h_init = torch.zeros(opt.batch_size, opt.rnn_size) table.insert(init_state, h_init:clone()) end local params, grad_params -- get flattened parameters tensor -- params, grad_params = model_utils.combine_all_parameters(protos.rnn) params, grad_params = protos.rnn:getParameters() print('Number of parameters in the model: ' .. params:nElement()) -- print(params, grad_params) -- create clones of model to unroll in time: print('Cloning RNN model:') local clones = {} clones.rnn = {} clones.criterion = {} for name, proto in pairs(protos) do print('cloning ' .. name) clones[name] = model_utils.clone_many_times(proto, opt.seq_length, not proto.parameters) end function clone_list(tensor_list, zero_too) -- takes a list of tensors and returns a list of cloned tensors local out = {} for k,v in pairs(tensor_list) do out[k] = v:clone() if zero_too then out[k]:zero() end end return out end -- training function: local init_state_global = clone_list(init_state) local bo = 0 -- batch offset / counter opt.grad_clip = 5 function feval(p) if p ~= params then params:copy(p) end grad_params:zero() -- bo variable creates batches on the fly -- forward pass --------------------------------------------------------------- local rnn_state = {[0]=init_state_global} -- initial state local predictions = {} local loss = 0 for t = 1, opt.seq_length do clones.rnn[t]:training() -- make sure we are in correct training mode -- print( 'sample,target:', x[{{},{t+bo}}], y[{1,{t+bo}}] ) local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])} rnn_state[t] = {} for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output predictions[t] = lst[#lst] loss = loss + clones.criterion[t]:forward(predictions[t], y[{1,{t+bo}}]) end loss = loss / opt.seq_length -- backward pass -------------------------------------------------------------- -- initialize gradient at time t to be zeros (there's no influence from future) local drnn_state = {[opt.seq_length] = clone_list(init_state, true)} -- true also zeros the clones for t = opt.seq_length, 1, -1 do -- print(drnn_state) -- backprop through loss, and softmax/linear -- print( 'prediction,target:', predictions[t], y[{1,{t+bo}}] ) local doutput_t = clones.criterion[t]:backward(predictions[t], y[{1,{t+bo}}]) -- print('douptut', doutput_t) table.insert(drnn_state[t], doutput_t) local dlst = clones.rnn[t]:backward({x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])}, drnn_state[t]) drnn_state[t-1] = {} for k,v in pairs(dlst) do if k > 1 then -- k == 1 is gradient on x, which we dont need -- note we do k-1 because first item is dembeddings, and then follow the -- derivatives of the state, starting at index 2. I know... drnn_state[t-1][k-1] = v end end end -- transfer final state to initial state (BPTT) init_state_global = rnn_state[#rnn_state] -- grad_params:div(opt.seq_length) -- clip gradient element-wise grad_params:clamp(-opt.grad_clip, opt.grad_clip) -- print(params,grad_params) -- point to next batch: bo = bo + opt.seq_length return loss, grad_params end -- training: opt.learning_rate = 2e-3 opt.decay_rate = 0.95 print('Training...') local losses = {} local optim_state = {learningRate = opt.learning_rate, alpha = opt.decay_rate} local iterations = opt.train_size/opt.seq_length for i = 1, iterations do local _, loss = optim.rmsprop(feval, params, optim_state) losses[#losses + 1] = loss[1] if i % (iterations/10) == 0 then print(string.format("Iteration %8d, loss = %4.4f, loss/seq_len = %4.4f, gradnorm = %4.4e", i, loss[1], loss[1] / opt.seq_length, grad_params:norm())) end end -- testing function: bo = 0 function test() -- bo variable creates batches on the fly -- forward pass --------------------------------------------------------------- local rnn_state = {[0]=init_state} -- initial state local predictions = {} local loss = 0 for t = 1, opt.seq_length do clones.rnn[t]:evaluate() -- make sure we are in correct testing mode local lst = clones.rnn[t]:forward{x[{{},{t+bo}}]:t(), unpack(rnn_state[t-1])} rnn_state[t] = {} for i=1,#init_state do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output predictions[t] = lst[#lst] end -- carry over lstm state rnn_state[0] = init_state -- here we want to test all steps -- print(predictions[opt.seq_length]) -- print results: local max, idx max,idx = torch.max( predictions[opt.seq_length], 2) print('Prediction:', idx[1][1], 'Label:', y[{1,{opt.seq_length+bo}}][1]) -- point to next batch: bo = bo + 1 -- here we want to test all steps end -- and test! opt.test_samples = 50 for i = 1, opt.test_samples do test() end
fixed training
fixed training the problem was clone_many times functions, which I did not use, and tried to clone myself
Lua
bsd-3-clause
e-lab/torch7-demos,e-lab/torch7-demos
85289600427eabee3a0e0ca3865839a247f84e12
src/plugins/finalcutpro/touchbar/widgets/height.lua
src/plugins/finalcutpro/touchbar/widgets/height.lua
--- === plugins.finalcutpro.touchbar.widgets.height === --- --- Final Cut Pro Browser Height Control Widget for Touch Bar. local require = require --local log = require("hs.logger").new("heightWidget") local canvas = require("hs.canvas") local fcp = require("cp.apple.finalcutpro") local i18n = require("cp.i18n") local touchbar = require("hs._asm.undocumented.touchbar") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.touchbar.widgets.height.widget() -> `hs._asm.undocumented.touchbar.item` --- Function --- The Widget --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.undocumented.touchbar.item` function mod.widget() local canvasWidth, canvasHeight = 250, 30 local widgetCanvas = canvas.new{x = 0, y = 0, h = 30, w = canvasWidth} widgetCanvas[#widgetCanvas + 1] = { id = "background", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 1 }, fillColor = { hex = "#1d1d1d", alpha = 1 }, roundedRectRadii = { xRadius = 5, yRadius = 5 }, } widgetCanvas[#widgetCanvas + 1] = { id = "startLine", type = "segments", coordinates = { {x = 0, y = canvasHeight/2}, {x = canvasWidth / 2, y = canvasHeight/2} }, action = "stroke", strokeColor = { hex = "#5051e7", alpha = 1 }, strokeWidth = 1.5, } widgetCanvas[#widgetCanvas + 1] = { id = "endLine", type = "segments", coordinates = { {x = canvasWidth / 2, y = canvasHeight/2}, {x = canvasWidth, y = canvasHeight/2} }, action = "stroke", strokeColor = { white = 1.0 }, strokeWidth = 1.5, } widgetCanvas[#widgetCanvas + 1] = { id = "circle", type = "circle", radius = 10, action = "strokeAndFill", fillColor = { hex = "#414141", alpha = 1 }, strokeWidth = 1.5, center = { x = canvasWidth / 2, y = canvasHeight / 2 }, } widgetCanvas:canvasMouseEvents(true, true, false, true) :mouseCallback(function(_,m,_,x,_) if not fcp.isFrontmost() or not fcp:libraries():isShowing() then return end widgetCanvas.circle.center = { x = x, y = canvasHeight / 2, } widgetCanvas.startLine.coordinates = { {x = 0, y = canvasHeight/2}, {x = x, y = canvasHeight/2}, } widgetCanvas.endLine.coordinates = { { x = x, y = canvasHeight / 2 }, { x = canvasWidth, y = canvasHeight / 2 }, } if m == "mouseDown" or m == "mouseMove" then fcp:libraries():appearanceAndFiltering():show():clipHeight():setValue(x/(canvasWidth/10)) elseif m == "mouseUp" then fcp:libraries():appearanceAndFiltering():hide() end end) mod.item = touchbar.item.newCanvas(widgetCanvas, "browserHeightSlider") :canvasClickColor{ alpha = 0.0 } return mod.item end --- plugins.finalcutpro.touchbar.widgets.height.init() -> nil --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(deps) local params = { group = "fcpx", text = i18n("browserHeightSlider"), subText = i18n("browserHeightSliderDescription"), item = mod.widget, } deps.manager.widgets:new("browserHeightSlider", params) return mod end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.touchbar.widgets.height", group = "finalcutpro", dependencies = { ["core.touchbar.manager"] = "manager", } } function plugin.init(deps) if touchbar.supported() then return mod.init(deps) end end return plugin
--- === plugins.finalcutpro.touchbar.widgets.height === --- --- Final Cut Pro Browser Height Control Widget for Touch Bar. local require = require --local log = require("hs.logger").new("heightWidget") local canvas = require("hs.canvas") local fcp = require("cp.apple.finalcutpro") local i18n = require("cp.i18n") local touchbar = require("hs._asm.undocumented.touchbar") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.touchbar.widgets.height.widget() -> `hs._asm.undocumented.touchbar.item` --- Function --- The Widget --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.undocumented.touchbar.item` function mod.widget() local canvasWidth, canvasHeight = 250, 30 local widgetCanvas = canvas.new{x = 0, y = 0, h = 30, w = canvasWidth} widgetCanvas[#widgetCanvas + 1] = { id = "background", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 1 }, fillColor = { hex = "#1d1d1d", alpha = 1 }, roundedRectRadii = { xRadius = 5, yRadius = 5 }, } widgetCanvas[#widgetCanvas + 1] = { id = "startLine", type = "segments", coordinates = { {x = 0, y = canvasHeight/2}, {x = canvasWidth / 2, y = canvasHeight/2} }, action = "stroke", strokeColor = { hex = "#5051e7", alpha = 1 }, strokeWidth = 1.5, } widgetCanvas[#widgetCanvas + 1] = { id = "endLine", type = "segments", coordinates = { {x = canvasWidth / 2, y = canvasHeight/2}, {x = canvasWidth, y = canvasHeight/2} }, action = "stroke", strokeColor = { white = 1.0 }, strokeWidth = 1.5, } widgetCanvas[#widgetCanvas + 1] = { id = "circle", type = "circle", radius = 10, action = "strokeAndFill", fillColor = { hex = "#414141", alpha = 1 }, strokeWidth = 1.5, center = { x = canvasWidth / 2, y = canvasHeight / 2 }, } widgetCanvas:canvasMouseEvents(true, true, false, true) :mouseCallback(function(_,m,_,x,_) if not fcp.isFrontmost() or not fcp:libraries():isShowing() then return end widgetCanvas.circle.center = { x = x, y = canvasHeight / 2, } widgetCanvas.startLine.coordinates = { {x = 0, y = canvasHeight/2}, {x = x, y = canvasHeight/2}, } widgetCanvas.endLine.coordinates = { { x = x, y = canvasHeight / 2 }, { x = canvasWidth, y = canvasHeight / 2 }, } if m == "mouseDown" or m == "mouseMove" then -------------------------------------------------------------------------------- -- The height slider goes from 32 to 135: -------------------------------------------------------------------------------- local value = x/(canvasWidth/10) value = (value * (135 - 32) / 10) + 32 fcp:libraries():appearanceAndFiltering():show():clipHeight():value(value) elseif m == "mouseUp" then fcp:libraries():appearanceAndFiltering():hide() end end) mod.item = touchbar.item.newCanvas(widgetCanvas, "browserHeightSlider") :canvasClickColor{ alpha = 0.0 } return mod.item end --- plugins.finalcutpro.touchbar.widgets.height.init() -> nil --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(deps) local params = { group = "fcpx", text = i18n("browserHeightSlider"), subText = i18n("browserHeightSliderDescription"), item = mod.widget, } deps.manager.widgets:new("browserHeightSlider", params) return mod end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.touchbar.widgets.height", group = "finalcutpro", dependencies = { ["core.touchbar.manager"] = "manager", } } function plugin.init(deps) if touchbar.supported() then return mod.init(deps) end end return plugin
#1648
#1648 - Fixed dodgy maths
Lua
mit
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
f25ab30106ad4951cd5c0999a41ad747b6bde6cb
hammerspoon/.hammerspoon/init.lua
hammerspoon/.hammerspoon/init.lua
-- A global variable for the Hyper Mode k = hs.hotkey.modal.new({}, "F17") log = hs.logger.new('WM','debug') -- Tools ------------------------------------------------------------------------------- -- Inspect Focused Window k:bind({"shift"}, 'i', nil, function() local win = hs.window.focusedWindow() log.d("Size", win:size()) log.d("Frame", win:frame()) end) -- Move Windows ------------------------------------------------------------------------------- -- Mission Control k:bind({}, 'up', nil, function() hs.eventtap.keyStroke({"cmd","alt","ctrl"}, 'F12') end) -- Go To Previous Space k:bind({}, 'left', nil, function() hs.eventtap.keyStroke({"ctrl"}, 'left') end) k:bind({}, 'right', nil, function() hs.eventtap.keyStroke({"ctrl"}, 'right') end) -- Resize Windows ------------------------------------------------------------------------------- hs.window.animationDuration = 0 -- 1 - Work Setup - Main Editor Left k:bind({}, '1', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0, y=0, w=0.3, h=1}, nil, nil }, {"Firefox Developer Edition", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil}, {"Code", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil} } hs.layout.apply(windowLayout) end) -- 2 - Work Setup - 50/50 split, terminal in the center k:bind({}, '2', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0.2, y=0.1, w=0.6, h=0.8}, nil, nil }, {"Firefox Developer Edition", nil, nil, {x=0, y=0, w=0.5, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.5, y=0, w=0.5, h=1}, nil, nil}, {"Code", nil, nil, {x=0.5, y=0, w=0.5, h=1}, nil, nil} } hs.layout.apply(windowLayout, string.find) end) -- 3 - Work Setup - 1/3 split, Browser + Editor + Terminal k:bind({}, '3', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0, y=0, w=0.2, h=1}, nil, nil }, {"Firefox Developer Edition", nil, nil, {x=0.2, y=0, w=0.4, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.6, y=0, w=0.4, h=1}, nil, nil}, {"Code", nil, nil, {x=0.6, y=0, w=0.4, h=1}, nil, nil} } hs.layout.apply(windowLayout, string.find) end) -- 4 - Twitch Setup k:bind({}, '4', nil, function() local windowLayout = { {"Firefox Developer Edition", "Twitch", nil, nil, {x=0, y=0, w=914, h=615}, nil}, {"OBS", nil, nil, nil, {x=0, y=637, w=914, h=803}, nil}, {"Atom", nil, nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"Code", nil, nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"Firefox Developer Edition", "francoiscote", nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"iTerm2", nil, nil, nil, {x=2640, y=0, w=800, h=962}, nil}, {"Firefox Developer Edition", "Alert Box Widget", nil, nil, {x=2640, y=985, w=800, h=455}, nil}, } hs.layout.apply(windowLayout, string.find) end) -- 0 - Maximize k:bind({}, '0', nil, function() local win = hs.window.focusedWindow() win:maximize() k.triggered = true end) -- 9 - Right k:bind({}, '9', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 8 - Left k:bind({}, '8', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 7 - "Browser" Size k:bind({}, '7', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.5 else widthratio = 0.8 end f.w = max.w * widthratio f.y = max.y f.h = max.h win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 6 - "Email" Size k:bind({}, '6', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.6 else widthratio = 0.8 end f.w = max.w * widthratio f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 5 - "Finder" Size k:bind({}, '5', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.h = max.h * 0.6 f.w = f.h * 1.5 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- Shortcut to reload config reload = function() hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config Reloaded"}):send() k.triggered = true end k:bind({}, 'r', nil, reload) -- Launch Apps launch = function(appname) hs.application.launchOrFocus(appname) k.triggered = true end -- Single keybinding for app launch singleapps = { {'y', 'Wunderlist'}, {'u', 'Discord'}, {'j', 'Firefox Developer Edition'}, {'n', 'Sourcetree'}, {'i', 'YakYak'}, -- {'k', 'Visual Studio Code'}, {'k', 'Atom'}, {'o', 'Slack'}, {'l', 'iTerm'}, {';', 'Boxy'}, {'h', 'Finder'}, {'p', 'Spotify'} } for i, app in ipairs(singleapps) do k:bind({}, app[1], function() launch(app[2]); end) end -- Enter Hyper Mode when F18 (Hyper/Capslock) is pressed pressedF18 = function() k.triggered = false k:enter() end -- Leave Hyper Mode when F18 (Hyper/Capslock) is pressed, -- send ESCAPE if no other keys are pressed. releasedF18 = function() k:exit() if not k.triggered then hs.eventtap.keyStroke({}, 'ESCAPE') end end -- Bind the Hyper key f18 = hs.hotkey.bind({}, 'F18', pressedF18, releasedF18)
-- A global variable for the Hyper Mode k = hs.hotkey.modal.new({}, "F17") log = hs.logger.new('WM','debug') -- Tools ------------------------------------------------------------------------------- -- Inspect Focused Window k:bind({"shift"}, 'i', nil, function() local win = hs.window.focusedWindow() log.d("Size", win:size()) log.d("Frame", win:frame()) end) -- Move Windows ------------------------------------------------------------------------------- -- Mission Control k:bind({}, 'up', nil, function() hs.eventtap.keyStroke({"cmd","alt","ctrl"}, 'F12') end) -- Go To Previous Space k:bind({}, 'left', nil, function() hs.eventtap.keyStroke({"ctrl"}, 'left') end) k:bind({}, 'right', nil, function() hs.eventtap.keyStroke({"ctrl"}, 'right') end) -- Resize Windows ------------------------------------------------------------------------------- hs.window.animationDuration = 0 -- 1 - Work Setup - Main Editor Left k:bind({}, '1', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0, y=0, w=0.3, h=1}, nil, nil }, {"Google Chrome", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil}, {"Code", nil, nil, {x=0.3, y=0, w=0.7, h=1}, nil, nil} } hs.layout.apply(windowLayout) end) -- 2 - Work Setup - 50/50 split, terminal in the center k:bind({}, '2', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0.2, y=0.1, w=0.6, h=0.8}, nil, nil }, {"Google Chrome", nil, nil, {x=0, y=0, w=0.5, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.5, y=0, w=0.5, h=1}, nil, nil}, {"Code", nil, nil, {x=0.5, y=0, w=0.5, h=1}, nil, nil} } hs.layout.apply(windowLayout, string.find) end) -- 3 - Work Setup - 1/3 split, Browser + Editor + Terminal k:bind({}, '3', nil, function() local windowLayout = { {"iTerm2", nil, nil, {x=0, y=0, w=0.2, h=1}, nil, nil }, {"Google Chrome", nil, nil, {x=0.2, y=0, w=0.4, h=1}, nil, nil}, {"Atom", nil, nil, {x=0.6, y=0, w=0.4, h=1}, nil, nil}, {"Code", nil, nil, {x=0.6, y=0, w=0.4, h=1}, nil, nil} } hs.layout.apply(windowLayout, string.find) end) -- 4 - Twitch Setup k:bind({}, '4', nil, function() local windowLayout = { {"Google Chrome", "Twitch", nil, nil, {x=0, y=0, w=914, h=615}, nil}, {"OBS", nil, nil, nil, {x=0, y=637, w=914, h=803}, nil}, {"Atom", nil, nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"Code", nil, nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"Google Chrome", "francoiscote", nil, nil, {x=915, y=0, w=1724, h=1418}, nil}, {"iTerm2", nil, nil, nil, {x=2640, y=0, w=800, h=962}, nil}, {"Google Chrome", "Alert Box Widget", nil, nil, {x=2640, y=985, w=800, h=455}, nil}, } hs.layout.apply(windowLayout, string.find) end) -- 0 - Maximize k:bind({}, '0', nil, function() local win = hs.window.focusedWindow() win:maximize() k.triggered = true end) -- 9 - Right k:bind({}, '9', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 8 - Left k:bind({}, '8', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 7 - "Browser" Size k:bind({}, '7', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.5 else widthratio = 0.8 end f.w = max.w * widthratio f.y = max.y f.h = max.h win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 6 - "Email" Size k:bind({}, '6', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.6 else widthratio = 0.8 end f.w = max.w * widthratio f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 5 - "Finder" Size k:bind({}, '5', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.h = max.h * 0.6 f.w = f.h * 1.5 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- Shortcut to reload config reload = function() hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config Reloaded"}):send() k.triggered = true end k:bind({}, 'r', nil, reload) -- Launch Apps launch = function(appname) hs.application.launchOrFocus(appname) k.triggered = true end -- Single keybinding for app launch singleapps = { {'y', 'Wunderlist'}, {'u', 'Discord'}, {'j', 'Google Chrome'}, {'n', 'Sourcetree'}, {'i', 'YakYak'}, -- {'k', 'Visual Studio Code'}, {'k', 'Atom'}, {'o', 'Slack'}, {'l', 'iTerm'}, {';', 'Boxy'}, {'h', 'Finder'}, {'p', 'Spotify'} } for i, app in ipairs(singleapps) do k:bind({}, app[1], function() launch(app[2]); end) end -- Enter Hyper Mode when F18 (Hyper/Capslock) is pressed pressedF18 = function() k.triggered = false k:enter() end -- Leave Hyper Mode when F18 (Hyper/Capslock) is pressed, -- send ESCAPE if no other keys are pressed. releasedF18 = function() k:exit() if not k.triggered then hs.eventtap.keyStroke({}, 'ESCAPE') end end -- Bind the Hyper key f18 = hs.hotkey.bind({}, 'F18', pressedF18, releasedF18)
fix hammerspoon, use google chrome
fix hammerspoon, use google chrome
Lua
mit
francoiscote/dotfiles,francoiscote/dotfiles
f0c302cd12a2e4fcdb1609a20eed6509349deeac
webui/src/WebUIManager.lua
webui/src/WebUIManager.lua
-- **************************************************************************** -- * -- * PROJECT: MTA:SA CEF utilities (https://github.com/Jusonex/mtasa_cef_tools) -- * FILE: webui/src/WebUIManager.lua -- * PURPOSE: WebUIManager class definition -- * -- **************************************************************************** WebUIManager = { new = function(self, ...) if self.Instance then return false end local o=setmetatable({},{__index=self}) o:constructor(...) self.Instance = o return o end; getInstance = function() assert(WebUIManager.Instance, "WebUIManager has not been initialised yet") return WebUIManager.Instance end; Settings = { ScrollSpeed = 50; TitleBarHeight = 25; }; } -- -- WebUIManager's constructor -- Returns: The WebUIManager instance -- function WebUIManager:constructor() self.m_Stack = {} addEventHandler("onClientRender", root, function() -- Draw from bottom to top for k, ui in ipairs(self.m_Stack) do ui:draw() end end ) addEventHandler("onClientCursorMove", root, function(relX, relY, absX, absY) for k, ui in pairs(self.m_Stack) do local browser = ui:getUnderlyingBrowser() local pos = ui:getPosition() browser:injectMouseMove(absX - pos.x, absY - pos.y) end end ) local function onMouseWheel(button, state) if button == "mouse_wheel_down" or button == "mouse_wheel_up" then local browser = WebUIManager.getFocusedBrowser() if browser then local direction = button == "mouse_wheel_up" and 1 or -1 browser:injectMouseWheel(direction*WebUIManager.Settings.ScrollSpeed, 0) end end end addEventHandler("onClientKey", root, onMouseWheel) addEventHandler("onClientClick", root, function(button, state, absX, absY) local topIndex = #self.m_Stack -- Process from top to bottom for i = topIndex, 1, -1 do local ui = self.m_Stack[i] local pos, size = ui:getPosition(), ui:getSize() local browser = ui:getUnderlyingBrowser() if state == "up" and ui.movefunc then removeEventHandler("onClientCursorMove", root, ui.movefunc) ui.movefunc = nil end -- Are we within the browser rect? if absX >= pos.x and absY >= pos.y and absX < pos.x + size.x and absY < pos.y + size.y then if ui:getType() == WebWindow.WindowType.Frame and state == "down" then local diff = Vector2(absX-pos.x, absY-pos.y) ui.movefunc = function(relX, relY, absX, absY) ui:setPosition(Vector2(absX, absY) - diff) end if diff.y <= WebUIManager.Settings.TitleBarHeight then addEventHandler("onClientCursorMove", root, ui.movefunc) break end end if state == "down" then browser:injectMouseDown(button) else browser:injectMouseUp(button) end -- Move to front if the current browser isn't the currently focused one if i ~= topIndex then self:moveWindowToFrontByIndex(i) end browser:focus() -- Stop here (the click has been processed!) return end end -- Unfocus and disable input Browser.focus(nil) guiSetInputEnabled(false) end ) addEventHandler("onClientBrowserInputFocusChanged", resourceRoot, function(gainedFocus) if gainedFocus then -- Enable input mode guiSetInputEnabled(true) else -- Disabled input mode guiSetInputEnabled(false) end end ) addEventHandler("onClientResourceStop", resourceRoot, function() self:destroy() end) end -- -- WebUIManager's destructor -- function WebUIManager:destroy() guiSetInputEnabled(false) for k, v in pairs(self.m_Stack) do v:destroy() end end -- -- Registers a window at the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:registerWindow(window) table.insert(self.m_Stack, window) end -- -- Unlinks a window from the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:unregisterWindow(window) -- Disable input if the browser we're about to destroy is focused if window:getUnderlyingBrowser():isFocused() then guiSetInputEnabled(false) end for k, v in pairs(self.m_Stack) do if v == window then table.remove(self.m_Stack, k) return true end end return false end -- -- Moves the specified window to the front (by WebWindow instance) -- Parameters: -- window: The web UI window you want to move to the front (WebWindow) -- function WebUIManager:moveWindowToFront(window) -- TODO end -- -- Moves a window to the front by index (fast internal use) -- Parameters: -- index: The index the window has on the drawing stack -- function WebUIManager:moveWindowToFrontByIndex(index) -- Make a backup of the window at the specified index local ui = self.m_Stack[index] -- Remove it from the list temporally table.remove(self.m_Stack, index) -- Append it to the end table.insert(self.m_Stack, ui) end -- -- Static function that returns the currently focussed browser -- Returns: The focussed browser element -- function WebUIManager.getFocusedBrowser() for k, browser in pairs(getElementsByType("webbrowser")) do if browser:isFocused() then return browser end end return false end
-- **************************************************************************** -- * -- * PROJECT: MTA:SA CEF utilities (https://github.com/Jusonex/mtasa_cef_tools) -- * FILE: webui/src/WebUIManager.lua -- * PURPOSE: WebUIManager class definition -- * -- **************************************************************************** WebUIManager = { new = function(self, ...) if self.Instance then return false end local o=setmetatable({},{__index=self}) o:constructor(...) self.Instance = o return o end; getInstance = function() assert(WebUIManager.Instance, "WebUIManager has not been initialised yet") return WebUIManager.Instance end; Settings = { ScrollSpeed = 50; TitleBarHeight = 25; }; } -- -- WebUIManager's constructor -- Returns: The WebUIManager instance -- function WebUIManager:constructor() self.m_Stack = {} addEventHandler("onClientRender", root, function() -- Draw from bottom to top for k, ui in ipairs(self.m_Stack) do ui:draw() end end ) addEventHandler("onClientCursorMove", root, function(relX, relY, absX, absY) for k, ui in pairs(self.m_Stack) do local browser = ui:getUnderlyingBrowser() local pos = ui:getPosition() browser:injectMouseMove(absX - pos.x, absY - pos.y) end end ) local function onMouseWheel(button, state) if button == "mouse_wheel_down" or button == "mouse_wheel_up" then local browser = WebUIManager.getFocusedBrowser() if browser then local direction = button == "mouse_wheel_up" and 1 or -1 browser:injectMouseWheel(direction*WebUIManager.Settings.ScrollSpeed, 0) end end end addEventHandler("onClientKey", root, onMouseWheel) addEventHandler("onClientClick", root, function(button, state, absX, absY) local topIndex = #self.m_Stack -- Process from top to bottom for i = topIndex, 1, -1 do local ui = self.m_Stack[i] local pos, size = ui:getPosition(), ui:getSize() local browser = ui:getUnderlyingBrowser() if state == "up" and ui.movefunc then removeEventHandler("onClientCursorMove", root, ui.movefunc) ui.movefunc = nil end -- Are we within the browser rect? if absX >= pos.x and absY >= pos.y and absX < pos.x + size.x and absY < pos.y + size.y then if ui:getType() == WebWindow.WindowType.Frame and state == "down" then local diff = Vector2(absX-pos.x, absY-pos.y) ui.movefunc = function(relX, relY, absX, absY) ui:setPosition(Vector2(absX, absY) - diff) end if diff.y <= WebUIManager.Settings.TitleBarHeight then addEventHandler("onClientCursorMove", root, ui.movefunc) -- Move to front if the current browser isn't the currently focused one if i ~= topIndex then self:moveWindowToFrontByIndex(i) end break end end if state == "down" then browser:injectMouseDown(button) else browser:injectMouseUp(button) end -- Move to front if the current browser isn't the currently focused one if i ~= topIndex then self:moveWindowToFrontByIndex(i) end browser:focus() -- Stop here (the click has been processed!) return end end -- Unfocus and disable input Browser.focus(nil) guiSetInputEnabled(false) end ) addEventHandler("onClientBrowserInputFocusChanged", resourceRoot, function(gainedFocus) if gainedFocus then -- Enable input mode guiSetInputEnabled(true) else -- Disabled input mode guiSetInputEnabled(false) end end ) addEventHandler("onClientResourceStop", resourceRoot, function() self:destroy() end) end -- -- WebUIManager's destructor -- function WebUIManager:destroy() guiSetInputEnabled(false) for k, v in pairs(self.m_Stack) do v:destroy() end end -- -- Registers a window at the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:registerWindow(window) table.insert(self.m_Stack, window) end -- -- Unlinks a window from the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:unregisterWindow(window) -- Disable input if the browser we're about to destroy is focused if window:getUnderlyingBrowser():isFocused() then guiSetInputEnabled(false) end for k, v in pairs(self.m_Stack) do if v == window then table.remove(self.m_Stack, k) return true end end return false end -- -- Moves the specified window to the front (by WebWindow instance) -- Parameters: -- window: The web UI window you want to move to the front (WebWindow) -- function WebUIManager:moveWindowToFront(window) -- TODO end -- -- Moves a window to the front by index (fast internal use) -- Parameters: -- index: The index the window has on the drawing stack -- function WebUIManager:moveWindowToFrontByIndex(index) -- Make a backup of the window at the specified index local ui = self.m_Stack[index] -- Remove it from the list temporally table.remove(self.m_Stack, index) -- Append it to the end table.insert(self.m_Stack, ui) end -- -- Static function that returns the currently focussed browser -- Returns: The focussed browser element -- function WebUIManager.getFocusedBrowser() for k, browser in pairs(getElementsByType("webbrowser")) do if browser:isFocused() then return browser end end return false end
Fixed FrameWebWindow not moving to the front when moving
Fixed FrameWebWindow not moving to the front when moving
Lua
unlicense
FL1K3R/mtasa_cef_tools,FL1K3R/mtasa_cef_tools,Jusonex/mtasa_cef_tools,Jusonex/mtasa_cef_tools
1f127ed2d0c7145bdd70eb439dfc4e4ea3442e75
Interface/AddOns/RayUI/modules/misc/bubbles.lua
Interface/AddOns/RayUI/modules/misc/bubbles.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local M = R:GetModule("Misc") local mod = M:NewModule("BubbleSkin", "AceTimer-3.0") --Cache global variables --Lua functions local select, unpack, type = select, unpack, type local strfind, strlower = string.find, string.lower --WoW API / Variables local CreateFrame = CreateFrame --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: UIParent, WorldFrame function mod:UpdateBubbleBorder() if not self.text then return end local r, g, b = self.text:GetTextColor() self:SetBackdropBorderColor(r, g, b, .8) end function mod:SkinBubble(frame) local mult = R.mult * UIParent:GetScale() for i=1, frame:GetNumRegions() do local region = select(i, frame:GetRegions()) if region:GetObjectType() == "Texture" then region:SetTexture(nil) elseif region:GetObjectType() == "FontString" then frame.text = region end end if not R.PixelMode then frame:SetBackdrop({ edgeFile = R["media"].glow, bgFile = R["media"].blank, tile = false, tileSize = 0, edgeSize = 3, insets = {left = 3, right = 3, top = 3, bottom = 3} }) else frame:SetBackdrop({ edgeFile = R["media"].blank, bgFile = R["media"].blank, tile = false, tileSize = 0, edgeSize = mult, }) end frame:SetClampedToScreen(false) frame:SetBackdropBorderColor(unpack(R["media"].bordercolor)) frame:SetBackdropColor(.1, .1, .1, .6) mod.UpdateBubbleBorder(frame) frame:HookScript("OnShow", mod.UpdateBubbleBorder) end function mod:IsChatBubble(frame) for i = 1, frame:GetNumRegions() do local region = select(i, frame:GetRegions()) if region.GetTexture and region:GetTexture() and type(region:GetTexture() == "string") then if strfind(strlower(region:GetTexture()), "chatbubble%-background") then return true end end end return false end local numChildren = 0 function mod:Initialize() local frame = CreateFrame('Frame') frame.lastupdate = -2 frame:SetScript("OnUpdate", function(self, elapsed) self.lastupdate = self.lastupdate + elapsed if (self.lastupdate < .1) then return end self.lastupdate = 0 local count = WorldFrame:GetNumChildren() if(count ~= numChildren) then for i = numChildren + 1, count do local frame = select(i, WorldFrame:GetChildren()) if mod:IsChatBubble(frame) then mod:SkinBubble(frame) end end numChildren = count end end) end M:RegisterMiscModule(mod:GetName())
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local M = R:GetModule("Misc") local mod = M:NewModule("BubbleSkin", "AceTimer-3.0") --Cache global variables --Lua functions local select, unpack, type = select, unpack, type local strfind, strlower = string.find, string.lower --WoW API / Variables local CreateFrame = CreateFrame --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: UIParent, WorldFrame function mod:UpdateBubbleBorder() if not self.text then return end local r, g, b = self.text:GetTextColor() self:SetBackdropBorderColor(r, g, b, .8) end function mod:SkinBubble(frame) local mult = R.mult * UIParent:GetScale() for i=1, frame:GetNumRegions() do local region = select(i, frame:GetRegions()) if region:GetObjectType() == "Texture" then region:SetTexture(nil) elseif region:GetObjectType() == "FontString" then frame.text = region end end if not R.PixelMode then frame:SetBackdrop({ edgeFile = R["media"].glow, bgFile = R["media"].blank, tile = false, tileSize = 0, edgeSize = 3, insets = {left = 3, right = 3, top = 3, bottom = 3} }) else frame:SetBackdrop({ edgeFile = R["media"].blank, bgFile = R["media"].blank, tile = false, tileSize = 0, edgeSize = mult, }) end frame:SetClampedToScreen(false) frame:SetBackdropBorderColor(unpack(R["media"].bordercolor)) frame:SetBackdropColor(.1, .1, .1, .6) mod.UpdateBubbleBorder(frame) frame:HookScript("OnShow", mod.UpdateBubbleBorder) end function mod:IsChatBubble(frame) if not frame:IsForbidden() then for i = 1, frame:GetNumRegions() do local region = select(i, frame:GetRegions()) if region.GetTexture and region:GetTexture() and type(region:GetTexture() == "string") then if strfind(strlower(region:GetTexture()), "chatbubble%-background") then return true end end end end return false end local numChildren = 0 function mod:Initialize() local frame = CreateFrame('Frame') frame.lastupdate = -2 frame:SetScript("OnUpdate", function(self, elapsed) self.lastupdate = self.lastupdate + elapsed if (self.lastupdate < .1) then return end self.lastupdate = 0 local count = WorldFrame:GetNumChildren() if(count ~= numChildren) then for i = numChildren + 1, count do local frame = select(i, WorldFrame:GetChildren()) if mod:IsChatBubble(frame) then mod:SkinBubble(frame) end end numChildren = count end end) end M:RegisterMiscModule(mod:GetName())
fix bubble skin error
fix bubble skin error
Lua
mit
fgprodigal/RayUI
e9d13a545137da45daade20d2a4e4fa89183bf43
state/play.lua
state/play.lua
--[[-- PLAY STATE ---- Play the game. --]]-- local st = GameState.new() local math_floor, math_max, math_min = math.floor, math.max, math.min -- Camera local GameCam = require 'pud.view.GameCam' local vector = require 'lib.hump.vector' -- map builder local MapDirector = require 'pud.map.MapDirector' -- level view local TileMapView = require 'pud.view.TileMapView' -- events local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' function st:enter() self._keyDelay, self._keyInterval = love.keyboard.getKeyRepeat() love.keyboard.setKeyRepeat(200, 25) self:_generateMapFromFile() self:_createView() self:_createCamera() self:_createHUD() self:_drawHUDfb() end function st:_generateMapFromFile() local FileMapBuilder = require 'pud.map.FileMapBuilder' local mapfiles = {'test'} local mapfile = mapfiles[math.random(1,#mapfiles)] local builder = FileMapBuilder(mapfile) self:_generateMap(builder) end function st:_generateMapRandomly() local SimpleGridMapBuilder = require 'pud.map.SimpleGridMapBuilder' local builder = SimpleGridMapBuilder(100,100, 10,10, 20,35) self:_generateMap(builder) end function st:_generateMap(builder) if self._map then self._map:destroy() end self._map = MapDirector:generateStandard(builder) builder:destroy() GameEvent:push(MapUpdateFinishedEvent(self._map)) end function st:_createView(viewClass) if self._view then self._view:destroy() end self._view = TileMapView(self._map) self._view:registerEvents() end function st:_createCamera() local mapW, mapH = self._map:getSize() local tileW, tileH = self._view:getTileSize() local mapTileW, mapTileH = mapW * tileW, mapH * tileH local startX = math_floor(mapW/2+0.5) * tileW - math_floor(tileW/2) local startY = math_floor(mapH/2+0.5) * tileH - math_floor(tileH/2) local zoom = 1 if self._cam then zoom = self._cam:getZoom() self._cam:destroy() end self._cam = GameCam(vector(startX, startY), zoom) local min = vector(math_floor(tileW/2), math_floor(tileH/2)) local max = vector(mapTileW - min.x, mapTileH - min.y) self._cam:setLimits(min, max) self._view:setViewport(self._cam:getViewport()) end function st:_createHUD() if not self._HUDfb then local w, h = nearestPO2(WIDTH), nearestPO2(HEIGHT) self._HUDfb = love.graphics.newFramebuffer(w, h) end end local _accum = 0 local TICK = 0.001 function st:update(dt) _accum = _accum + dt if _accum > TICK then _accum = _accum - TICK self:_drawHUDfb() end end function st:_drawHUD() love.graphics.setColor(1, 1, 1) love.graphics.draw(self._HUDfb) end function st:_drawHUDfb() love.graphics.setRenderTarget(self._HUDfb) -- temporary center square local tileW = self._view:getTileSize() local _,zoomAmt = self._cam:getZoom() local size = zoomAmt * tileW local x = math_floor(WIDTH/2)-math_floor(size/2) local y = math_floor(HEIGHT/2)-math_floor(size/2) love.graphics.setColor(0, 1, 0) love.graphics.rectangle('line', x, y, size, size) if debug then love.graphics.setFont(GameFont.small) local fps = love.timer.getFPS() local color = {1, 1, 1} if fps < 20 then color = {1, 0, 0} elseif fps < 60 then color = {1, .9, 0} end love.graphics.setColor(color) love.graphics.print('fps: '..tostring(fps), 8, 8) end love.graphics.setRenderTarget() end function st:draw() self._cam:predraw() self._view:draw() self._cam:postdraw() self:_drawHUD() end function st:leave() love.keyboard.setKeyRepeat(self._keyDelay, self._keyInterval) self._view:destroy() self._view = nil end function st:_translateCam(x, y) local translate = vector(x, y) self._view:setViewport(self._cam:getViewport(translate)) self._cam:translate(vector(x, y)) end function st:keypressed(key, unicode) local tileW, tileH = self._view:getTileSize() local _,zoomAmt = self._cam:getZoom() switch(key) { escape = function() love.event.push('q') end, m = function() self:_generateMapRandomly() self:_createView() self:_createCamera() end, f = function() self:_generateMapFromFile() self:_createView() self:_createCamera() end, -- camera left = function() self:_translateCam(-tileW/zoomAmt, 0) end, right = function() self:_translateCam(tileW/zoomAmt, 0) end, up = function() self:_translateCam(0, -tileH/zoomAmt) end, down = function() self:_translateCam(0, tileH/zoomAmt) end, pageup = function() self._view:setViewport(self._cam:getViewport(nil, 1)) self._cam:zoomOut() end, pagedown = function() self._view:setViewport(self._cam:getViewport(nil, -1)) self._cam:zoomIn() end, home = function() self._view:setViewport(self._cam:getViewport()) self._cam:home() end, } end return st
--[[-- PLAY STATE ---- Play the game. --]]-- local st = GameState.new() local math_floor, math_max, math_min = math.floor, math.max, math.min -- Camera local GameCam = require 'pud.view.GameCam' local vector = require 'lib.hump.vector' -- map builder local MapDirector = require 'pud.map.MapDirector' -- level view local TileMapView = require 'pud.view.TileMapView' -- events local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' function st:enter() self._keyDelay, self._keyInterval = love.keyboard.getKeyRepeat() love.keyboard.setKeyRepeat(200, 25) self:_generateMapFromFile() self:_createView() self:_createCamera() self:_createHUD() self:_drawHUDfb() end function st:_generateMapFromFile() local FileMapBuilder = require 'pud.map.FileMapBuilder' local mapfiles = {'test'} local mapfile = mapfiles[math.random(1,#mapfiles)] local builder = FileMapBuilder(mapfile) self:_generateMap(builder) end function st:_generateMapRandomly() local SimpleGridMapBuilder = require 'pud.map.SimpleGridMapBuilder' local builder = SimpleGridMapBuilder(100,100, 10,10, 20,35) self:_generateMap(builder) end function st:_generateMap(builder) if self._map then self._map:destroy() end self._map = MapDirector:generateStandard(builder) builder:destroy() GameEvent:push(MapUpdateFinishedEvent(self._map)) end function st:_createView(viewClass) if self._view then self._view:destroy() end self._view = TileMapView(self._map) self._view:registerEvents() end function st:_createCamera() local mapW, mapH = self._map:getSize() local tileW, tileH = self._view:getTileSize() local mapTileW, mapTileH = mapW * tileW, mapH * tileH local startX = math_floor(mapW/2+0.5) * tileW - math_floor(tileW/2) local startY = math_floor(mapH/2+0.5) * tileH - math_floor(tileH/2) local zoom = 1 if self._cam then zoom = self._cam:getZoom() self._cam:destroy() end self._cam = GameCam(vector(startX, startY), zoom) local min = vector(math_floor(tileW/2), math_floor(tileH/2)) local max = vector(mapTileW - min.x, mapTileH - min.y) self._cam:setLimits(min, max) self._view:setViewport(self._cam:getViewport()) end function st:_createHUD() if not self._HUDfb then local w, h = nearestPO2(WIDTH), nearestPO2(HEIGHT) self._HUDfb = love.graphics.newFramebuffer(w, h) end end local _accum = 0 local TICK = 0.001 function st:update(dt) _accum = _accum + dt if _accum > TICK then _accum = _accum - TICK end self:_drawHUDfb() end function st:_drawHUD() love.graphics.setColor(1, 1, 1) love.graphics.draw(self._HUDfb) end function st:_drawHUDfb() love.graphics.setRenderTarget(self._HUDfb) -- temporary center square local tileW = self._view:getTileSize() local _,zoomAmt = self._cam:getZoom() local size = zoomAmt * tileW local x = math_floor(WIDTH/2)-math_floor(size/2) local y = math_floor(HEIGHT/2)-math_floor(size/2) love.graphics.setColor(0, 1, 0) love.graphics.rectangle('line', x, y, size, size) if debug then love.graphics.setFont(GameFont.small) local fps = love.timer.getFPS() local color = {1, 1, 1} if fps < 20 then color = {1, 0, 0} elseif fps < 60 then color = {1, .9, 0} end love.graphics.setColor(color) love.graphics.print('fps: '..tostring(fps), 8, 8) end love.graphics.setRenderTarget() end function st:draw() self._cam:predraw() self._view:draw() self._cam:postdraw() self:_drawHUD() end function st:leave() love.keyboard.setKeyRepeat(self._keyDelay, self._keyInterval) self._view:destroy() self._view = nil end function st:_translateCam(x, y) local translate = vector(x, y) self._view:setViewport(self._cam:getViewport(translate)) self._cam:translate(vector(x, y)) end function st:keypressed(key, unicode) local tileW, tileH = self._view:getTileSize() local _,zoomAmt = self._cam:getZoom() switch(key) { escape = function() love.event.push('q') end, m = function() self:_generateMapRandomly() self:_createView() self:_createCamera() end, f = function() self:_generateMapFromFile() self:_createView() self:_createCamera() end, -- camera left = function() self:_translateCam(-tileW/zoomAmt, 0) end, right = function() self:_translateCam(tileW/zoomAmt, 0) end, up = function() self:_translateCam(0, -tileH/zoomAmt) end, down = function() self:_translateCam(0, tileH/zoomAmt) end, pageup = function() self._view:setViewport(self._cam:getViewport(nil, 1)) self._cam:zoomOut() end, pagedown = function() local vp = self._cam:getViewport(nil, -1) self._cam:zoomIn(self._view.setViewport, self._view, vp) end, home = function() self._view:setViewport(self._cam:getViewport()) self._cam:home() end, } end return st
fix zoomIn viewport being set too early
fix zoomIn viewport being set too early
Lua
mit
scottcs/wyx
b5ce56fd0b0899a427c1053e6599cc2857c10e57
lua/nginx/lua/router.lua
lua/nginx/lua/router.lua
-- -- Copyright 2019 The FATE 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. -- local ngx = ngx function get_upstream_server(request_dest) local server = "127.0.0.1:9360" return server end function get_request_dest() local headers = ngx.req.get_headers() for k, v in pairs(headers) do ngx.log(ngx.INFO, k) ngx.log(ngx.INFO, v) end return headers end function routing() local request_dest = get_request_dest() local forward_server = get_upstream_server(request_dest) ngx.ctx.fate_cluster_server = forward_server -- local ok, err = ngx_balancer.set_current_peer(forward_server) -- if not ok then -- utils.exit_abnormally('failed to set current peer: ' .. err, ngx.HTTP_SERVICE_UNAVAILABLE) -- end end routing()
-- -- Copyright 2019 The FATE 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. -- local ngx = ngx function get_upstream_server(request_headers) -- TODO: Gets the destination address from the routing table based on the header information local server = "127.0.0.1:9360" return server end function get_request_dest() local headers = ngx.req.get_headers() for k, v in pairs(headers) do ngx.log(ngx.INFO, k) ngx.log(ngx.INFO, v) end return headers end function routing() local request_headers = get_request_dest() local forward_server = get_upstream_server(request_headers) ngx.ctx.fate_cluster_server = forward_server -- local ok, err = ngx_balancer.set_current_peer(forward_server) -- if not ok then -- utils.exit_abnormally('failed to set current peer: ' .. err, ngx.HTTP_SERVICE_UNAVAILABLE) -- end end routing()
fix proxy router lua
fix proxy router lua Signed-off-by: zengjice <1dc3faab9c1c669484e2786b29f3d13319949610@gmail.com>
Lua
apache-2.0
FederatedAI/FATE,FederatedAI/FATE,FederatedAI/FATE
b04a85f6c58a8162fc9ee77c4293fa4712de8488
html.lua
html.lua
local Html = cmark.Renderer.new() local gsub, find, format, byte = string.gsub, string.find, string.format, string.byte Html.escape = function(s) if find(s, '[<>&"]') then return gsub(s, '[<>&"]', function(c) if c == '<' then return "&lt;" elseif c == '>' then return "&gt;" elseif c == '&' then return "&amp;" elseif c == '"' then return "&quot;" end end) else return s end end Html.urlencode = function(str) if (str) then str = gsub(str, "\n", "\r\n") str = gsub(str, "([^%w_.@/:%%+()*?&=-])", function(c) if #c == 1 then return format("%%%02X", byte(c)) end end) end return str end local out = Html.out local cr = Html.cr local escape = Html.escape local urlencode = Html.urlencode function Html.tag_open(tag, attrs) if Html.notags > 0 then return end out('<' .. tag) if attrs then for k, v in pairs(attrs) do out(' ' .. k .. '="' .. escape(v) .. '"') end end out('>') end function Html.tag_close(tag) if Html.notags > 0 then return end out('</' .. tag .. '>') end function Html.tag_selfclosing(tag, attrs) if Html.notags > 0 then return end out('<' .. tag) if attrs then for k, v in pairs(attrs) do out(' ' .. k .. '="' .. escape(v) .. '"') end end out(' />') end local tag_open, tag_close, tag_selfclosing = Html.tag_open, Html.tag_close, Html.tag_selfclosing function Html.begin_document() end function Html.end_document() end function Html.begin_paragraph(tight) if not tight then tag_open('p') end end function Html.end_paragraph(tight) if not tight then tag_close('p') cr() end end function Html.begin_block_quote() cr() tag_open('blockquote') cr() end function Html.end_block_quote() cr() tag_close('blockquote') cr() end function Html.begin_header(level) tag_open('h' .. level) end function Html.end_header(level) tag_close('h' .. level) cr() end function Html.code_block(s, info) cr() attrs = {} if #info > 0 then attrs.class = 'language-' .. gsub(info,' .*$','') end tag_open('pre') tag_open('code', attrs) out(escape(s)) tag_close('code') tag_close('pre') cr() end function Html.html(s) cr() out(s) cr() end function Html.hrule() cr() tag_selfclosing('hr') cr() end function Html.begin_list(stype, tight, start) cr() local tag if stype == 'bullet' then tag = 'ul' else tag = 'ol' end local attrs = {} if start > 1 then attrs.start = start end tag_open(tag, attrs) cr() end function Html.end_list(stype) cr() local tag if stype == 'bullet' then tag = 'ul' else tag = 'ol' end tag_close(tag) cr() end function Html.begin_list_item(tight) cr() tag_open('li') if not tight then cr() end end function Html.end_list_item(tight) if not tight then cr() end tag_close('li') cr() end function Html.text(s) out(escape(s)) end function Html.softbreak() out('\n') end function Html.linebreak() tag_selfclosing('br') cr() end function Html.inline_code(s) tag_open('code') out(escape(s)) tag_close('code') end function Html.inline_html(s) out(s) end function Html.begin_emph() tag_open('em') end function Html.end_emph() tag_close('em') end function Html.begin_strong() tag_open('strong') end function Html.end_strong() tag_close('strong') end function Html.begin_link(url, title) local attrs = {href = url} if #title > 0 then attrs.title = title end tag_open('a', attrs) end function Html.end_link(url, title) tag_close('a') end function Html.begin_image(url, title) if Html.notags == 0 then out('<img src="') out(urlencode(url)) out('"') if #title > 0 then out(' title="') out(escape(title)) out('"') end out(' alt="') Html.notags = Html.notags + 1 end end function Html.end_image(url, title) Html.notags = Html.notags - 1 if Html.notags == 0 then out('" />') end end return Html
local Html = cmark.Renderer.new() local gsub, find, format, byte = string.gsub, string.find, string.format, string.byte Html.escape = function(s) if find(s, '[<>&"]') then return gsub(s, '[<>&"]', function(c) if c == '<' then return "&lt;" elseif c == '>' then return "&gt;" elseif c == '&' then return "&amp;" elseif c == '"' then return "&quot;" end end) else return s end end Html.urlencode = function(str) if (str) then str = gsub(str, "\n", "\r\n") str = gsub(str, "[^A-Za-z0-9_.@/:%%+()*?&=-]", function(c) buf = {} for i = 1, #c do buf[#buf + 1] = format("%%%02X", byte(c, i)) end return table.concat(buf) end) end return str end local out = Html.out local cr = Html.cr local escape = Html.escape local urlencode = Html.urlencode function Html.tag_open(tag, attrs) if Html.notags > 0 then return end out('<' .. tag) if attrs then for k, v in pairs(attrs) do out(' ' .. k .. '="' .. escape(v) .. '"') end end out('>') end function Html.tag_close(tag) if Html.notags > 0 then return end out('</' .. tag .. '>') end function Html.tag_selfclosing(tag, attrs) if Html.notags > 0 then return end out('<' .. tag) if attrs then for k, v in pairs(attrs) do out(' ' .. k .. '="' .. escape(v) .. '"') end end out(' />') end local tag_open, tag_close, tag_selfclosing = Html.tag_open, Html.tag_close, Html.tag_selfclosing function Html.begin_document() end function Html.end_document() end function Html.begin_paragraph(tight) if not tight then tag_open('p') end end function Html.end_paragraph(tight) if not tight then tag_close('p') cr() end end function Html.begin_block_quote() cr() tag_open('blockquote') cr() end function Html.end_block_quote() cr() tag_close('blockquote') cr() end function Html.begin_header(level) tag_open('h' .. level) end function Html.end_header(level) tag_close('h' .. level) cr() end function Html.code_block(s, info) cr() attrs = {} if #info > 0 then attrs.class = 'language-' .. gsub(info,' .*$','') end tag_open('pre') tag_open('code', attrs) out(escape(s)) tag_close('code') tag_close('pre') cr() end function Html.html(s) cr() out(s) cr() end function Html.hrule() cr() tag_selfclosing('hr') cr() end function Html.begin_list(stype, tight, start) cr() local tag if stype == 'bullet' then tag = 'ul' else tag = 'ol' end local attrs = {} if start > 1 then attrs.start = start end tag_open(tag, attrs) cr() end function Html.end_list(stype) cr() local tag if stype == 'bullet' then tag = 'ul' else tag = 'ol' end tag_close(tag) cr() end function Html.begin_list_item(tight) cr() tag_open('li') if not tight then cr() end end function Html.end_list_item(tight) if not tight then cr() end tag_close('li') cr() end function Html.text(s) out(escape(s)) end function Html.softbreak() out('\n') end function Html.linebreak() tag_selfclosing('br') cr() end function Html.inline_code(s) tag_open('code') out(escape(s)) tag_close('code') end function Html.inline_html(s) out(s) end function Html.begin_emph() tag_open('em') end function Html.end_emph() tag_close('em') end function Html.begin_strong() tag_open('strong') end function Html.end_strong() tag_close('strong') end function Html.begin_link(url, title) local attrs = {href = url} if #title > 0 then attrs.title = title end tag_open('a', attrs) end function Html.end_link(url, title) tag_close('a') end function Html.begin_image(url, title) if Html.notags == 0 then out('<img src="') out(urlencode(url)) out('"') if #title > 0 then out(' title="') out(escape(title)) out('"') end out(' alt="') Html.notags = Html.notags + 1 end end function Html.end_image(url, title) Html.notags = Html.notags - 1 if Html.notags == 0 then out('" />') end end return Html
Preliminary fixes for urlencoding.
Preliminary fixes for urlencoding. Really we need slnunicode to do this properly.
Lua
bsd-2-clause
jgm/cmark-lua,jgm/cmark-lua
7cd81f13dbc9f14b09fb1bf154dc30765efbf8b6
Quadtastic/exporters/xml.lua
Quadtastic/exporters/xml.lua
local exporter = {} local libquadtastic = require("Quadtastic.libquadtastic") -- This is the name under which the exporter will be listed in the menu exporter.name = "XML" -- This is the default file extension that will be used when the user does not -- specify one. exporter.ext = "xml" local function indent(write, i) write(string.rep(" ", i)) end local function export_table(write, table, ind) if not ind then ind = 0 end for k,v in pairs(table) do indent(write, ind) if libquadtastic.is_quad(v) then write(string.format("<quad name=\"%s\", x=%d, y=%d, w=%d, h=%d />", k, v.x, v.y, v.w, v.h)) elseif type(v) == "table" then write(string.format("<group name=\"%s\">\n", k)) export_table(write, v, ind + 1) indent(write, ind) write("</group>") elseif type(v) == "string" then write(string.format("<%s>%s</%s>", k, v, k)) elseif type(v) == "number" then write(string.format("<%s>%d</%s>", k, v, k)) end write("\n") end end function exporter.export(write, quads) write("<quad_definitions>\n") export_table(write, quads, 1) write("</quad_definitions>\n") end return exporter
local libquadtastic = require("Quadtastic.libquadtastic") local utf8 = require("utf8") local exporter = {} -- This is the name under which the exporter will be listed in the menu exporter.name = "XML" -- This is the default file extension that will be used when the user does not -- specify one. exporter.ext = "xml" local should_escape = { [utf8.codepoint("\"")] = true, [utf8.codepoint("&")] = true, [utf8.codepoint("\'" )] = true, [utf8.codepoint("<")] = true, [utf8.codepoint(">")] = true, } local function utf8_encode(str) return utf8.char(string.byte(str, 1, string.len(str))) end -- Returns a new string in which all special characters of s are escaped, -- according to the json spec on http://json.org/ local function escape(s) local escaped_s = {} for p, c in utf8.codes(utf8_encode(s)) do if should_escape[c] then table.insert(escaped_s, string.format("&#%d;", c)) else table.insert(escaped_s, utf8.char(c)) end end return table.concat(escaped_s) end local function indent(write, i) write(string.rep(" ", i)) end local function xml_key(key) if type(key) == "string" then return string.format("\"%s\"", escape(key)) elseif type(key) == "number" then return string.format("%d", escape(key)) else error("Key of unexpected type " .. type(key)) end end local function export_table(write, table, ind) if not ind then ind = 0 end for k,v in pairs(table) do indent(write, ind) if libquadtastic.is_quad(v) then write(string.format("<quad key=%s, x=%d, y=%d, w=%d, h=%d />", xml_key(k), v.x, v.y, v.w, v.h)) elseif type(v) == "table" then write(string.format("<group key=%s>\n", xml_key(k))) export_table(write, v, ind + 1) indent(write, ind) write("</group>") elseif type(v) == "string" then write(string.format("<string key=%s>%s</string>", xml_key(k), escape(v))) elseif type(v) == "number" then write(string.format("<number key=%s>%d</number>", xml_key(k), v)) end write("\n") end end function exporter.export(write, quads) write("<?xml encoding='UTF-8'?>\n") write("<quad_definitions>\n") export_table(write, quads, 1) write("</quad_definitions>\n") end return exporter
Fix encoding and escaping in xml exporter
Fix encoding and escaping in xml exporter
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
112e8f17ad5010ecdc43b48cd816c224eaae3b35
pud/ui/Text.lua
pud/ui/Text.lua
local Class = require 'lib.hump.class' local Frame = getClass 'pud.ui.Frame' local pushRenderTarget, popRenderTarget = pushRenderTarget, popRenderTarget local setColor = love.graphics.setColor local setFont = love.graphics.setFont local gprint = love.graphics.print local math_floor = math.floor local string_sub = string.sub local string_gmatch = string.gmatch local format = string.format -- Text -- A static text frame local Text = Class{name='Text', inherits=Frame, function(self, ...) Frame.construct(self, ...) self._maxLines = 1 self._text = {} self._justify = 'l' self._margin = 0 end } -- destructor function Text:destroy() self:clear() self._text = nil self._justify = nil self._margin = nil self._watched = nil Frame.destroy(self) end -- set the text that will be displayed -- text can be a string or a table of strings, representing lines -- (newline is not supported) function Text:setText(text) if type(text) == 'string' then text = {text} end verify('table', text) self:clear() text = self:_wrap(text) local numLines = #text if numLines > self._maxLines then warning('setText(lines): number of lines (%d) exceeds maximum (%d)', numLines, self._maxLines) for i=1,self._maxLines do self._text[i] = text[i] end else self._text = text end self:_drawFB() end -- assuming width is constant, wrap lines if they're larger than the width -- of this frame. function Text:_wrap(text) local font = self._curStyle:getFont() if font then local space = font:getWidth(' ') local margin = self._margin or 0 local frameWidth = self:getWidth() - (2 * margin) local num = #text local wrapped local wrapcount = 0 for i=1,num do wrapcount = wrapcount + 1 wrapped = wrapped or {} -- if width is too long, wrap if font:getWidth(text[i]) > frameWidth then local width = 0 local here = 0 -- check one word at a time for word in string_gmatch(text[i], '%s*(%S+)') do local wordW = font:getWidth(word) local prevWidth = width width = width + wordW -- if the running width of all checked words is too long, wrap if width > frameWidth then -- if it's a single word, or we're on the last line, truncate if width == wordW or wrapcount == self._maxLines then local old = word while #word > 0 and width > frameWidth do word = string_sub(word, 1, -2) wordW = font:getWidth(word) width = prevWidth + wordW end --warning('Word %q is too long, truncating to %q', old, word) end if prevWidth == 0 then -- single word width = -space wrapped[wrapcount] = word elseif wrapcount == self._maxLines then -- last line width = frameWidth - space wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word) else -- neither single word or last line width = wordW wrapcount = wrapcount + 1 wrapped[wrapcount] = word end else -- didn't wrap, just add the word if wrapped[wrapcount] then wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word) else wrapped[wrapcount] = word end end -- if width > frameWidth width = width + space end -- for word in string_gmatch else wrapped[wrapcount] = text[i] end -- if font:getWidth end return wrapped and wrapped or text end end -- returns the currently set text as a table of strings, one per line function Text:getText() return self._text end -- watch a table (this replaces any text already set) -- the table must be an array function Text:watch(t) verify('table', t) self._watched = t end function Text:unwatch() self._watched = nil end -- clear the current text function Text:clear() for k in pairs(self._text) do self._text[k] = nil end end -- set the maximum number of lines function Text:setMaxLines(max) verify('number', max) self._maxLines = max end -- set the margin between the frame edge and the text function Text:setMargin(margin) verify('number', margin) self._margin = margin self:_drawFB() end -- set the justification function Text:setJustifyLeft() self._justify = 'l' end function Text:setJustifyRight() self._justify = 'r' end function Text:setJustifyCenter() self._justify = 'c' end -- onTick - check watched table function Text:_onTick(dt, x, y) if self._watched then self:setText(self._watched) end return Frame._onTick(self, dt, x, y) end -- override Frame:_drawFB() function Text:_drawFB() self._bfb = self._bfb or self:_getFramebuffer() pushRenderTarget(self._bfb) self:_drawBackground() if self._text and #self._text > 0 then if self._curStyle then local font = self._curStyle:getFont() if font then local height = font:getHeight() local margin = self._margin or 0 local text = self._text local textLines = #text local maxLines = math_floor((self:getHeight() - (2*margin)) / height) local numLines = textLines > maxLines and maxLines or textLines local fontcolor = self._curStyle:getFGColor() setFont(font) setColor(fontcolor) for i=1,numLines do local line = text[i] local h = (i-1) * height local w = font:getWidth(line) local y = margin + h local x if 'l' == self._justify then x = margin elseif 'c' == self._justify then local cx = self:getWidth() / 2 x = math_floor(cx - (w/2)) elseif 'r' == self._justify then x = self:getWidth() - (margin + w) else x, y = 0, 0 warning('Unjustified (justify is set to %q)', tostring(self._justify)) end gprint(line, x, y) end end end end popRenderTarget() self._ffb, self._bfb = self._bfb, self._ffb end -- the class return Text
local Class = require 'lib.hump.class' local Frame = getClass 'pud.ui.Frame' local pushRenderTarget, popRenderTarget = pushRenderTarget, popRenderTarget local setColor = love.graphics.setColor local setFont = love.graphics.setFont local gprint = love.graphics.print local math_floor = math.floor local string_sub = string.sub local string_gmatch = string.gmatch local format = string.format -- Text -- A static text frame local Text = Class{name='Text', inherits=Frame, function(self, ...) Frame.construct(self, ...) self._maxLines = 1 self._text = {} self._justify = 'l' self._margin = 0 end } -- destructor function Text:destroy() self:clear() self._text = nil self._justify = nil self._margin = nil self._watched = nil Frame.destroy(self) end -- set the text that will be displayed -- text can be a string or a table of strings, representing lines -- (newline is not supported) function Text:setText(text) if type(text) == 'string' then text = {text} end verify('table', text) self:clear() text = self:_wrap(text) local numLines = #text if numLines > self._maxLines then warning('setText(lines): number of lines (%d) exceeds maximum (%d)', numLines, self._maxLines) for i=1,self._maxLines do self._text[i] = text[i] end else self._text = text end self:_drawFB() end -- assuming width is constant, wrap lines if they're larger than the width -- of this frame. function Text:_wrap(text) local font = self._curStyle:getFont() if font then local space = font:getWidth(' ') local margin = self._margin or 0 local frameWidth = self:getWidth() - (2 * margin) local num = #text local wrapped local wrapcount = 0 for i=1,num do wrapcount = wrapcount + 1 wrapped = wrapped or {} -- if width is too long, wrap if font:getWidth(text[i]) > frameWidth then local width = 0 local here = 0 -- check one word at a time for word in string_gmatch(text[i], '%s*(%S+)') do local wordW = font:getWidth(word) local prevWidth = width width = width + wordW -- if the running width of all checked words is too long, wrap if width > frameWidth then -- if it's a single word, or we're on the last line, truncate if width == wordW or wrapcount == self._maxLines then local old = word while #word > 0 and width > frameWidth do word = string_sub(word, 1, -2) wordW = font:getWidth(word) width = prevWidth + wordW end --warning('Word %q is too long, truncating to %q', old, word) end if prevWidth == 0 then -- single word width = -space wrapped[wrapcount] = word elseif wrapcount == self._maxLines then -- last line width = frameWidth - space wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word) else -- neither single word or last line width = wordW wrapcount = wrapcount + 1 wrapped[wrapcount] = word end else -- didn't wrap, just add the word if wrapped[wrapcount] then wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word) else wrapped[wrapcount] = word end end -- if width > frameWidth width = width + space end -- for word in string_gmatch else wrapped[wrapcount] = text[i] end -- if font:getWidth end return wrapped and wrapped or text end end -- returns the currently set text as a table of strings, one per line function Text:getText() return self._text end -- watch a table (this replaces any text already set) -- the table must be an array function Text:watch(t) verify('table', t) self._watched = t end function Text:unwatch() self._watched = nil end -- clear the current text function Text:clear() for k in pairs(self._text) do self._text[k] = nil end end -- set the maximum number of lines function Text:setMaxLines(max) verify('number', max) self._maxLines = max end -- set the margin between the frame edge and the text function Text:setMargin(margin) verify('number', margin) self._margin = margin self:_drawFB() end -- set the justification function Text:setJustifyLeft() self._justify = 'l'; self:_drawFB() end function Text:setJustifyRight() self._justify = 'r'; self:_drawFB() end function Text:setJustifyCenter() self._justify = 'c'; self:_drawFB() end -- onTick - check watched table function Text:_onTick(dt, x, y) if self._watched then self:setText(self._watched) end return Frame._onTick(self, dt, x, y) end -- override Frame:_drawFB() function Text:_drawFB() self._bfb = self._bfb or self:_getFramebuffer() pushRenderTarget(self._bfb) self:_drawBackground() if self._text and #self._text > 0 then if self._curStyle then local font = self._curStyle:getFont() if font then local height = font:getHeight() local margin = self._margin or 0 local text = self._text local textLines = #text local maxLines = math_floor((self:getHeight() - (2*margin)) / height) local numLines = textLines > maxLines and maxLines or textLines local fontcolor = self._curStyle:getFGColor() setFont(font) setColor(fontcolor) for i=1,numLines do local line = text[i] local h = (i-1) * height local w = font:getWidth(line) local y = margin + h local x if 'l' == self._justify then x = margin elseif 'c' == self._justify then local cx = self:getWidth() / 2 x = math_floor(cx - (w/2)) elseif 'r' == self._justify then x = self:getWidth() - (margin + w) else x, y = 0, 0 warning('Unjustified (justify is set to %q)', tostring(self._justify)) end gprint(line, x, y) end end end end popRenderTarget() self._ffb, self._bfb = self._bfb, self._ffb end -- the class return Text
fix justify to draw after being set
fix justify to draw after being set
Lua
mit
scottcs/wyx
501ccb77defb3881807fef7542fc002b3be3c6a2
src/pegasus/request.lua
src/pegasus/request.lua
local Request = {} function Request:new(client) local newObj = {} self.__index = self newObj.client = client newObj.firstLine = nil newObj._method = nil newObj._path = nil newObj._params = {} newObj._headers_parsed = false newObj._headers = {} newObj._form = {} newObj._is_valid = false newObj._body = '' newObj._content_done = 0 return setmetatable(newObj, self) end Request.PATTERN_METHOD = '^(.+)%s' Request.PATTERN_PATH = '(.*)%s' Request.PATTERN_PROTOCOL = '(HTTP%/%d%.%d)' Request.PATTERN_REQUEST = (Request.PATTERN_METHOD .. Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL) function Request:parseFirstLine() if (self.firstLine ~= nil) then return end local status, partial self.firstLine, status, partial = self.client:receive() if (self.firstLine == nil and status == 'timeout' and partial == '' or status == 'closed') then return end -- Parse firstline http: METHOD PATH PROTOCOL, -- GET Makefile HTTP/1.1 local method, path, protocol = string.match(self.firstLine, Request.PATTERN_REQUEST) local filename, querystring = string.match(path, '^([^#?]+)[#|?]?(.*)') self._path = filename self._query_string = querystring self._method = method end Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?' function Request:parseURLEncoded(value, _table) --value exists and _table is empty if value and next(_table) == nil then for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do _table[k] = v end end return _table end function Request:params() self:parseFirstLine() return self:parseURLEncoded(self._query_string, self._params) end function Request:post() if self:method() ~= 'POST' then return nil end local data = self:receiveBody() return self:parseURLEncoded(data, {}) end function Request:path() self:parseFirstLine() return self._path end function Request:method() self:parseFirstLine() return self._method end Request.PATTERN_HEADER = '([%w-]+): ([%w %p]+=?)' function Request:headers() if self._headers_parsed then return self._headers end self:parseFirstLine() local data = self.client:receive() while (data ~= nil) and (data:len() > 0) do local key, value = string.match(data, Request.PATTERN_HEADER) if key and value then self._headers[key] = value end data = self.client:receive() end self._headers_parsed = true self._content_length = tonumber(self._headers["Content-Length"] or 0) return self._headers end function Request:receiveBody(size) size = size or self._content_length -- do we have content? if self._content_done >= self._content_length then return false end -- fetch in chunks local fetch = math.min(self._content_length-self._content_done, size) local data, err, partial = self.client:receive(fetch) if err =='timeout' then err = nil data = partial end self._content_done = self._content_done + #data return data end function Request:ip() local result = self.client:getpeername() if result then local ipv4 = string.match(result, '%w+%.%w+%.%w+%.%w+') if ipv4 then return ipv4 else return string.match(result, '[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+') end end return nil end return Request
local Request = {} function Request:new(client) local newObj = {} self.__index = self newObj.client = client newObj.ip = client:getpeername() newObj.firstLine = nil newObj._method = nil newObj._path = nil newObj._params = {} newObj._headers_parsed = false newObj._headers = {} newObj._form = {} newObj._is_valid = false newObj._body = '' newObj._content_done = 0 return setmetatable(newObj, self) end Request.PATTERN_METHOD = '^(.+)%s' Request.PATTERN_PATH = '(.*)%s' Request.PATTERN_PROTOCOL = '(HTTP%/%d%.%d)' Request.PATTERN_REQUEST = (Request.PATTERN_METHOD .. Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL) function Request:parseFirstLine() if (self.firstLine ~= nil) then return end local status, partial self.firstLine, status, partial = self.client:receive() if (self.firstLine == nil and status == 'timeout' and partial == '' or status == 'closed') then return end -- Parse firstline http: METHOD PATH PROTOCOL, -- GET Makefile HTTP/1.1 local method, path, protocol = string.match(self.firstLine, Request.PATTERN_REQUEST) local filename, querystring = string.match(path, '^([^#?]+)[#|?]?(.*)') self._path = filename self._query_string = querystring self._method = method end Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?' function Request:parseURLEncoded(value, _table) --value exists and _table is empty if value and next(_table) == nil then for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do _table[k] = v end end return _table end function Request:params() self:parseFirstLine() return self:parseURLEncoded(self._query_string, self._params) end function Request:post() if self:method() ~= 'POST' then return nil end local data = self:receiveBody() return self:parseURLEncoded(data, {}) end function Request:path() self:parseFirstLine() return self._path end function Request:method() self:parseFirstLine() return self._method end Request.PATTERN_HEADER = '([%w-]+): ([%w %p]+=?)' function Request:headers() if self._headers_parsed then return self._headers end self:parseFirstLine() local data = self.client:receive() while (data ~= nil) and (data:len() > 0) do local key, value = string.match(data, Request.PATTERN_HEADER) if key and value then self._headers[key] = value end data = self.client:receive() end self._headers_parsed = true self._content_length = tonumber(self._headers["Content-Length"] or 0) return self._headers end function Request:receiveBody(size) size = size or self._content_length -- do we have content? if self._content_done >= self._content_length then return false end -- fetch in chunks local fetch = math.min(self._content_length-self._content_done, size) local data, err, partial = self.client:receive(fetch) if err =='timeout' then err = nil data = partial end self._content_done = self._content_done + #data return data end function Request:ip() local result = self.client:getpeername() if result then local ipv4 = string.match(result, '%w+%.%w+%.%w+%.%w+') if ipv4 then return ipv4 else return string.match(result, '[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+%:?[%a%d]+') end end return nil end return Request
add `req.ip`
add `req.ip` Fix #63
Lua
mit
EvandroLG/pegasus.lua
ad42ef432091f2ca9ebbb57ba04227b637eeca15
OpenSteamClient.lua
OpenSteamClient.lua
solution "OpenSteamClient" language "C++" location "Projects" targetdir "Binaries" includedirs { "Include" } configurations { "Debug", "Release", "DebugShared", "ReleaseShared" } configuration "Debug or DebugShared" flags { "Symbols" } configuration "Release or ReleaseShared" flags { "Optimize" } project "OpenSteamClient" files { "Source/**.h", "Source/**.cc", "Source/**.hpp", "Source/**.cpp", "Include/OpenSteamClient/**.hpp" } vpaths { ["Source Files"] = "Source/**.cpp", ["Source Files/Messages"] = "Source/Messages/**.cpp", ["Source Files/Protobufs"] = "Source/Protobufs/**.cc", ["Header Files"] = "Source/**.hpp", ["Header Files/Messages"] = "Source/Messages/**.hpp", ["Header Files/Protobufs"] = "Source/Protobufs/**.h", ["Include Files"] = "Include/OpenSteamClient/**" } configuration "windows" defines { "_SCL_SECURE_NO_WARNINGS", "OPENSTEAMCLIENT_INTERNAL" } libdirs { "ThirdParty/Libraries" } includedirs { "ThirdParty/Include" } configuration "linux" buildoptions { "-std=c++11" } configuration "Debug" targetsuffix "_sd" configuration "Release" targetsuffix "_s" configuration "DebugShared" targetsuffix "_d" configuration "Debug or Release" kind "StaticLib" configuration "DebugShared or ReleaseShared" kind "SharedLib" defines { "OPENSTEAMCLIENT_SHARED" } configuration { "windows", "DebugShared" } links { "ws2_32", "cryptopp_d", "libprotobuf-lite_d" } configuration { "windows", "ReleaseShared" } links { "ws2_32", "cryptopp", "libprotobuf-lite" } configuration "linux" excludes { "Source/TcpConnectionWin32.cpp" } configuration "windows" excludes { "Source/TcpConnectionPosix.cpp" }
solution "OpenSteamClient" language "C++" location "Projects" targetdir "Binaries" includedirs { "Include" } configurations { "Debug", "Release", "DebugShared", "ReleaseShared" } configuration "Debug or DebugShared" flags { "Symbols" } configuration "Release or ReleaseShared" flags { "Optimize" } project "OpenSteamClient" files { "Source/**.h", "Source/**.cc", "Source/**.hpp", "Source/**.cpp", "Include/OpenSteamClient/**.hpp" } vpaths { ["Source Files"] = "Source/**.cpp", ["Source Files/Messages"] = "Source/Messages/**.cpp", ["Source Files/Protobufs"] = "Source/Protobufs/**.cc", ["Header Files"] = "Source/**.hpp", ["Header Files/Messages"] = "Source/Messages/**.hpp", ["Header Files/Protobufs"] = "Source/Protobufs/**.h", ["Include Files"] = "Include/OpenSteamClient/**" } configuration "windows" defines { "_SCL_SECURE_NO_WARNINGS", "OPENSTEAMCLIENT_INTERNAL" } libdirs { "ThirdParty/Libraries" } includedirs { "ThirdParty/Include" } configuration "linux" buildoptions { "-std=c++11" } configuration "Debug" targetsuffix "_sd" configuration "Release" targetsuffix "_s" configuration "DebugShared" targetsuffix "_d" configuration "Debug or Release" kind "StaticLib" configuration "DebugShared or ReleaseShared" kind "SharedLib" defines { "OPENSTEAMCLIENT_SHARED" } configuration { "linux", "DebugShared or ReleaseShared"} links { "crypto++", "protobuf-lite" } configuration { "windows", "DebugShared" } links { "ws2_32", "cryptopp_d", "libprotobuf-lite_d" } configuration { "windows", "ReleaseShared" } links { "ws2_32", "cryptopp", "libprotobuf-lite" } configuration "linux" excludes { "Source/TcpConnectionWin32.cpp" } configuration "windows" excludes { "Source/TcpConnectionPosix.cpp" }
Fixed linking on Unix.
Fixed linking on Unix.
Lua
mit
dajoh/OpenSteamClient,dajoh/OpenSteamClient,dajoh/OpenSteamClient
c1568bca408b9592e0b45045f6d3070206c8ab71
Boilerplate_Resource/src/Boilerplate_Resource.lua
Boilerplate_Resource/src/Boilerplate_Resource.lua
-------------------------------------------------------- -- This file is part of the JX3 Plugin Project. -- @desc : Դ -- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd. -------------------------------------------------------- ------------------------------------------------------------------------------------------------------- -- these global functions are accessed all the time by the event handler -- so caching them is worth the effort ------------------------------------------------------------------------------------------------------- local setmetatable = setmetatable local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select local byte, char, len, find, format = string.byte, string.char, string.len, string.find, string.format local gmatch, gsub, dump, reverse = string.gmatch, string.gsub, string.dump, string.reverse local match, rep, sub, upper, lower = string.match, string.rep, string.sub, string.upper, string.lower local type, tonumber, tostring = type, tonumber, tostring local HUGE, PI, random, randomseed = math.huge, math.pi, math.random, math.randomseed local min, max, floor, ceil, abs = math.min, math.max, math.floor, math.ceil, math.abs local mod, modf, pow, sqrt = math['mod'] or math['fmod'], math.modf, math.pow, math.sqrt local sin, cos, tan, atan, atan2 = math.sin, math.cos, math.tan, math.atan, math.atan2 local insert, remove, concat = table.insert, table.remove, table.concat local pack, unpack = table['pack'] or function(...) return {...} end, table['unpack'] or unpack local sort, getn = table.sort, table['getn'] or function(t) return #t end -- jx3 apis caching local wsub, wlen, wfind, wgsub = wstring.sub, wstring.len, StringFindW, StringReplaceW local GetTime, GetLogicFrameCount, GetCurrentTime = GetTime, GetLogicFrameCount, GetCurrentTime local GetClientTeam, UI_GetClientPlayerID = GetClientTeam, UI_GetClientPlayerID local GetClientPlayer, GetPlayer, GetNpc, IsPlayer = GetClientPlayer, GetPlayer, GetNpc, IsPlayer -- lib apis caching local LIB = Boilerplate local UI, GLOBAL, CONSTANT = LIB.UI, LIB.GLOBAL, LIB.CONSTANT local PACKET_INFO, DEBUG_LEVEL, PATH_TYPE = LIB.PACKET_INFO, LIB.DEBUG_LEVEL, LIB.PATH_TYPE local wsub, count_c, lodash = LIB.wsub, LIB.count_c, LIB.lodash local pairs_c, ipairs_c, ipairs_r = LIB.pairs_c, LIB.ipairs_c, LIB.ipairs_r local spairs, spairs_r, sipairs, sipairs_r = LIB.spairs, LIB.spairs_r, LIB.sipairs, LIB.sipairs_r local IsNil, IsEmpty, IsEquals, IsString = LIB.IsNil, LIB.IsEmpty, LIB.IsEquals, LIB.IsString local IsBoolean, IsNumber, IsHugeNumber = LIB.IsBoolean, LIB.IsNumber, LIB.IsHugeNumber local IsTable, IsArray, IsDictionary = LIB.IsTable, LIB.IsArray, LIB.IsDictionary local IsFunction, IsUserdata, IsElement = LIB.IsFunction, LIB.IsUserdata, LIB.IsElement local EncodeLUAData, DecodeLUAData = LIB.EncodeLUAData, LIB.DecodeLUAData local GetTraceback, RandomChild, GetGameAPI = LIB.GetTraceback, LIB.RandomChild, LIB.GetGameAPI local Get, Set, Clone, GetPatch, ApplyPatch = LIB.Get, LIB.Set, LIB.Clone, LIB.GetPatch, LIB.ApplyPatch local Call, XpCall, SafeCall, NSFormatString = LIB.Call, LIB.XpCall, LIB.SafeCall, LIB.NSFormatString ------------------------------------------------------------------------------------------------------- local PLUGIN_NAME = NSFormatString('{$NS}_Resource') local PLUGIN_ROOT = PACKET_INFO.ROOT .. PLUGIN_NAME local MODULE_NAME = NSFormatString('{$NS}_Resource') local _L = LIB.LoadLangPack(PLUGIN_ROOT .. '/lang/') -------------------------------------------------------------------------- if not LIB.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^0.0.0') then return end -------------------------------------------------------------------------- local C, D = {}, {} C.aSound = { -- { -- type = _L['Wuer'], -- { id = 2, file = 'WE/voice-52001.ogg' }, -- { id = 3, file = 'WE/voice-52002.ogg' }, -- }, } do local root = PLUGIN_ROOT .. '/audio/' local function GetSoundList(tSound) local t = {} if tSound.type then t.szType = tSound.type elseif tSound.id then t.dwID = tSound.id t.szName = _L[tSound.file] t.szPath = root .. tSound.file end for _, v in ipairs(tSound) do local t1 = GetSoundList(v) if t1 then insert(t, t1) end end return t end function D.GetSoundList() return GetSoundList(C.aSound) end end do local BUTTON_STYLE_CONFIG = LIB.SetmetaReadonly{ FLAT = { nWidth = 100, nHeight = 25, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 8, nMouseOverGroup = 9, nMouseDownGroup = 10, nDisableGroup = 11, }, FLAT_LACE_BORDER = { nWidth = 148, nHeight = 33, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 0, nMouseOverGroup = 1, nMouseDownGroup = 2, nDisableGroup = 3, }, SKEUOMORPHISM = { nWidth = 148, nHeight = 33, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 4, nMouseOverGroup = 5, nMouseDownGroup = 6, nDisableGroup = 7, }, SKEUOMORPHISM_LACE_BORDER = { nWidth = 224, nHeight = 64, nMarginTop = 2, nMarginRight = 9, nMarginBottom = 10, nMarginLeft = 6, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 12, nMouseOverGroup = 13, nMouseDownGroup = 14, nDisableGroup = 15, }, } function D.GetWndButtonStyleConfig(eStyle) return BUTTON_STYLE_CONFIG[eStyle] end function D.GetWndButtonStyleName(szImage, nNormalGroup) for e, p in ipairs(BUTTON_STYLE_CONFIG) do if p.szImage == szImage and p.nNormalGroup == nNormalGroup then return e end end end end -- Global exports do local settings = { exports = { { fields = { GetSoundList = D.GetSoundList, GetWndButtonStyle = D.GetWndButtonStyle, }, }, }, } _G[MODULE_NAME] = LIB.GeneGlobalNS(settings) end
-------------------------------------------------------- -- This file is part of the JX3 Plugin Project. -- @desc : Դ -- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd. -------------------------------------------------------- ------------------------------------------------------------------------------------------------------- -- these global functions are accessed all the time by the event handler -- so caching them is worth the effort ------------------------------------------------------------------------------------------------------- local setmetatable = setmetatable local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select local byte, char, len, find, format = string.byte, string.char, string.len, string.find, string.format local gmatch, gsub, dump, reverse = string.gmatch, string.gsub, string.dump, string.reverse local match, rep, sub, upper, lower = string.match, string.rep, string.sub, string.upper, string.lower local type, tonumber, tostring = type, tonumber, tostring local HUGE, PI, random, randomseed = math.huge, math.pi, math.random, math.randomseed local min, max, floor, ceil, abs = math.min, math.max, math.floor, math.ceil, math.abs local mod, modf, pow, sqrt = math['mod'] or math['fmod'], math.modf, math.pow, math.sqrt local sin, cos, tan, atan, atan2 = math.sin, math.cos, math.tan, math.atan, math.atan2 local insert, remove, concat = table.insert, table.remove, table.concat local pack, unpack = table['pack'] or function(...) return {...} end, table['unpack'] or unpack local sort, getn = table.sort, table['getn'] or function(t) return #t end -- jx3 apis caching local wsub, wlen, wfind, wgsub = wstring.sub, wstring.len, StringFindW, StringReplaceW local GetTime, GetLogicFrameCount, GetCurrentTime = GetTime, GetLogicFrameCount, GetCurrentTime local GetClientTeam, UI_GetClientPlayerID = GetClientTeam, UI_GetClientPlayerID local GetClientPlayer, GetPlayer, GetNpc, IsPlayer = GetClientPlayer, GetPlayer, GetNpc, IsPlayer -- lib apis caching local LIB = Boilerplate local UI, GLOBAL, CONSTANT = LIB.UI, LIB.GLOBAL, LIB.CONSTANT local PACKET_INFO, DEBUG_LEVEL, PATH_TYPE = LIB.PACKET_INFO, LIB.DEBUG_LEVEL, LIB.PATH_TYPE local wsub, count_c, lodash = LIB.wsub, LIB.count_c, LIB.lodash local pairs_c, ipairs_c, ipairs_r = LIB.pairs_c, LIB.ipairs_c, LIB.ipairs_r local spairs, spairs_r, sipairs, sipairs_r = LIB.spairs, LIB.spairs_r, LIB.sipairs, LIB.sipairs_r local IsNil, IsEmpty, IsEquals, IsString = LIB.IsNil, LIB.IsEmpty, LIB.IsEquals, LIB.IsString local IsBoolean, IsNumber, IsHugeNumber = LIB.IsBoolean, LIB.IsNumber, LIB.IsHugeNumber local IsTable, IsArray, IsDictionary = LIB.IsTable, LIB.IsArray, LIB.IsDictionary local IsFunction, IsUserdata, IsElement = LIB.IsFunction, LIB.IsUserdata, LIB.IsElement local EncodeLUAData, DecodeLUAData = LIB.EncodeLUAData, LIB.DecodeLUAData local GetTraceback, RandomChild, GetGameAPI = LIB.GetTraceback, LIB.RandomChild, LIB.GetGameAPI local Get, Set, Clone, GetPatch, ApplyPatch = LIB.Get, LIB.Set, LIB.Clone, LIB.GetPatch, LIB.ApplyPatch local Call, XpCall, SafeCall, NSFormatString = LIB.Call, LIB.XpCall, LIB.SafeCall, LIB.NSFormatString ------------------------------------------------------------------------------------------------------- local PLUGIN_NAME = NSFormatString('{$NS}_Resource') local PLUGIN_ROOT = PACKET_INFO.ROOT .. PLUGIN_NAME local MODULE_NAME = NSFormatString('{$NS}_Resource') local _L = LIB.LoadLangPack(PLUGIN_ROOT .. '/lang/') -------------------------------------------------------------------------- if not LIB.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^0.0.0') then return end -------------------------------------------------------------------------- local C, D = {}, {} C.aSound = { -- { -- type = _L['Wuer'], -- { id = 2, file = 'WE/voice-52001.ogg' }, -- { id = 3, file = 'WE/voice-52002.ogg' }, -- }, } do local root = PLUGIN_ROOT .. '/audio/' local function GetSoundList(tSound) local t = {} if tSound.type then t.szType = tSound.type elseif tSound.id then t.dwID = tSound.id t.szName = _L[tSound.file] t.szPath = root .. tSound.file end for _, v in ipairs(tSound) do local t1 = GetSoundList(v) if t1 then insert(t, t1) end end return t end function D.GetSoundList() return GetSoundList(C.aSound) end end do local BUTTON_STYLE_CONFIG = { FLAT = LIB.SetmetaReadonly({ nWidth = 100, nHeight = 25, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 8, nMouseOverGroup = 9, nMouseDownGroup = 10, nDisableGroup = 11, }), FLAT_LACE_BORDER = LIB.SetmetaReadonly({ nWidth = 148, nHeight = 33, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 0, nMouseOverGroup = 1, nMouseDownGroup = 2, nDisableGroup = 3, }), SKEUOMORPHISM = LIB.SetmetaReadonly({ nWidth = 148, nHeight = 33, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 4, nMouseOverGroup = 5, nMouseDownGroup = 6, nDisableGroup = 7, }), SKEUOMORPHISM_LACE_BORDER = LIB.SetmetaReadonly({ nWidth = 224, nHeight = 64, nMarginTop = 2, nMarginRight = 9, nMarginBottom = 10, nMarginLeft = 6, szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex', nNormalGroup = 12, nMouseOverGroup = 13, nMouseDownGroup = 14, nDisableGroup = 15, }), } function D.GetWndButtonStyleName(szImage, nNormalGroup) for e, p in ipairs(BUTTON_STYLE_CONFIG) do if p.szImage == szImage and p.nNormalGroup == nNormalGroup then return e end end end function D.GetWndButtonStyleConfig(eStyle) return BUTTON_STYLE_CONFIG[eStyle] end end -- Global exports do local settings = { exports = { { fields = { GetSoundList = D.GetSoundList, GetWndButtonStyle = D.GetWndButtonStyle, }, }, }, } _G[MODULE_NAME] = LIB.GeneGlobalNS(settings) end
fix: 修复按钮资源获取名字失败的问题
fix: 修复按钮资源获取名字失败的问题
Lua
bsd-3-clause
tinymins/MY
47e17357c8caf4b6d902f88b2bc26deaf01e44ab
tests/trees/04_closure-insert.lua
tests/trees/04_closure-insert.lua
--[[! - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form - or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. - - In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright - interest in the software to the public domain. We make this dedication for the benefit of the public at large and to - the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in - perpetuity of all present and future rights to this software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to <http://unlicense.org/> --]] --[[ - Benchmark file for design problem "Trees", "Closure Table" solution. - Insert intermediate node "four-legged" between "carnivore" and its children. - - @author Markus Deutschl <deutschl.markus@gmail.com> - @copyright 2014 Markus Deutschl - @license http://unlicense.org/ Unlicense --]] -- --------------------------------------------------------------------------------------------------------------------- Includes pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "../common.inc") -- --------------------------------------------------------------------------------------------------------------------- Preparation functions --- Prepare data for the benchmark. -- Is called during the prepare command of sysbench in common.lua. function prepare_data() local query query = [[ CREATE TABLE `animals` ( `id` INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL ) ]] db_query(query) query = [[ CREATE TABLE `tree_paths` ( `ancestor` INTEGER UNSIGNED NOT NULL, `descendant` INTEGER UNSIGNED NOT NULL, `path_length` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (`ancestor`, `descendant`), CONSTRAINT `fk_tree_ancestor` FOREIGN KEY (`ancestor`) REFERENCES `animals` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_tree_descendant` FOREIGN KEY (`descendant`) REFERENCES `animals` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'carnivore'") db_query('INSERT INTO `tree_paths` SET `ancestor` = LAST_INSERT_ID(), `descendant` = LAST_INSERT_ID(), `path_length` = 0') db_query("INSERT INTO `animals` SET `name` = 'feline'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 1 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'cat'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 2 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'big cat'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 2 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'tiger'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 4 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'lion'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 4 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'canine'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 1 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'dog'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 7 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'wolf'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 7 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) db_query("INSERT INTO `animals` SET `name` = 'fox'") query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, LAST_INSERT_ID(), `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 7 UNION ALL SELECT LAST_INSERT_ID(), LAST_INSERT_ID(), 0 ]] db_query(query) end -- --------------------------------------------------------------------------------------------------------------------- Benchmark functions --- Execute the benchmark queries. -- Is called during the run command of sysbench. function benchmark() db_query('BEGIN') rs = db_query("INSERT INTO `animals` (`id`, `name`) VALUES (11, 'four-legged')") rs = db_query("UPDATE `tree_paths` SET `path_length` = `path_length` + 1 WHERE `ancestor` = 1 AND `descendant` != 1") rs = db_query([[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, 11, `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 1 UNION ALL SELECT 11, `descendant`, `path_length` - 1 FROM `tree_paths` WHERE `ancestor` = 1 AND `descendant` != 1 UNION ALL SELECT 11, 11, 0 ]]) db_query('ROLLBACK') end
--[[! - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form - or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. - - In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright - interest in the software to the public domain. We make this dedication for the benefit of the public at large and to - the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in - perpetuity of all present and future rights to this software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to <http://unlicense.org/> --]] --[[ - Benchmark file for design problem "Trees", "Closure Table" solution. - Insert intermediate node "four-legged" between "carnivore" and its children. - - @author Markus Deutschl <deutschl.markus@gmail.com> - @copyright 2014 Markus Deutschl - @license http://unlicense.org/ Unlicense --]] -- --------------------------------------------------------------------------------------------------------------------- Includes pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "../common.inc") dofile(pathtest .. "prepare.inc") -- --------------------------------------------------------------------------------------------------------------------- Preparation functions --- Implement the appropriate insert function. -- Is called during tree traversal in prepare_tree(). function Node:insertPre() local query db_query("INSERT INTO `animals` SET `id` = " .. self.id .. ", `name` = '" .. self.name .. "'") if self.parent == nil then db_query('INSERT INTO `tree_paths` SET `ancestor` = ' .. self.id .. ', `descendant` = ' .. self.id .. ', `path_length` = 0') else query = [[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, ]] .. self.id .. [[, `path_length` + 1 FROM `tree_paths` WHERE `descendant` = ]] .. self.parent.id .. [[ UNION ALL SELECT ]] .. self.id .. [[, ]] .. self.id .. [[, 0 ]] db_query(query) end end --- Prepare data for the benchmark. -- Is called during the prepare command of sysbench in common.lua. function prepare_data() local query query = [[ CREATE TABLE `animals` ( `id` INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL ) ]] db_query(query) query = [[ CREATE TABLE `tree_paths` ( `ancestor` INTEGER UNSIGNED NOT NULL, `descendant` INTEGER UNSIGNED NOT NULL, `path_length` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (`ancestor`, `descendant`), CONSTRAINT `fk_tree_ancestor` FOREIGN KEY (`ancestor`) REFERENCES `animals` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_tree_descendant` FOREIGN KEY (`descendant`) REFERENCES `animals` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ]] db_query(query) prepare_tree() fail() end -- --------------------------------------------------------------------------------------------------------------------- Benchmark functions --- Execute the benchmark queries. -- Is called during the run command of sysbench. function benchmark() db_query('BEGIN') rs = db_query("INSERT INTO `animals` (`id`, `name`) VALUES (11, 'four-legged')") rs = db_query("UPDATE `tree_paths` SET `path_length` = `path_length` + 1 WHERE `ancestor` = 1 AND `descendant` != 1") rs = db_query([[ INSERT INTO `tree_paths` (`ancestor`, `descendant`, `path_length`) SELECT `ancestor`, 11, `path_length` + 1 FROM `tree_paths` WHERE `descendant` = 1 UNION ALL SELECT 11, `descendant`, `path_length` - 1 FROM `tree_paths` WHERE `ancestor` = 1 AND `descendant` != 1 UNION ALL SELECT 11, 11, 0 ]]) db_query('ROLLBACK') end
Fixed Tree Closure Table data preparation.
Fixed Tree Closure Table data preparation.
Lua
unlicense
Ravenlord/ddp-testing
c3bedfa3cca1b0527d251c7076c8a88247534045
penguingui/TextField.lua
penguingui/TextField.lua
-- Editable text field TextField = class(Component) TextField.vPadding = 3 TextField.hPadding = 4 TextField.borderColor = "#545454" TextField.backgroundColor = "black" TextField.textColor = "white" TextField.textHoverColor = "#777777" TextField.defaultTextColor = "#333333" TextField.defaultTextHoverColor = "#777777" TextField.cursorColor = "white" TextField.cursorRate = 1 -- Constructs a new TextField. -- -- @param x The x coordinate of the new component, relative to its parent. -- @param y The y coordinate of the new component, relative to its parent. -- @param width The width of the new component. -- @param height The height of the new component. -- @param defaultText The text to display when nothing has been entered. function TextField:_init(x, y, width, height, defaultText) Component._init(self) self.x = x self.y = y self.width = width self.height = height self.fontSize = height - self.vPadding * 2 self.cursorPosition = 0 self.cursorX = 0 self.cursorTimer = self.cursorRate self.text = "" self.defaultText = defaultText self.textOffset = 0 self.textClip = nil self.mouseOver = false end function TextField:draw(dt) local startX = self.x local startY = self.y local w = self.width local h = self.height -- Draw border and background local borderRect = { startX, startY, startX + w, startY + h } local backgroundRect = { startX + 1, startY + 1, startX + w - 1, startY + h - 1 } console.canvasDrawRect(borderRect, self.borderColor) console.canvasDrawRect(backgroundRect, self.backgroundColor) local text = self.text -- Decide if the default text should be displayed local default = (text == "") and (self.defaultText ~= nil) local textColor -- Choose the color to draw the text with if self.mouseOver then textColor = default and self.defaultTextHoverColor or self.textHoverColor else textColor = default and self.defaultTextColor or self.textColor end local cursorPosition = self.cursorPosition text = default and self.defaultText or text:sub(self.textOffset, self.textOffset + (self.textClip or #text)) -- Draw the text console.canvasDrawText(text, { position = { startX + self.hPadding, startY + self.vPadding }, verticalAnchor = "bottom" }, self.fontSize, textColor) -- Text cursor if self.hasFocus then local timer = self.cursorTimer local rate = self.cursorRate timer = timer - dt if timer < 0 then timer = rate end if timer > rate / 2 then -- Draw cursor local cursorX = startX + self.cursorX + self.hPadding local cursorY = startY + self.vPadding console.canvasDrawLine({cursorX, cursorY}, {cursorX, cursorY + h - self.vPadding * 2}, self.cursorColor, 1) end self.cursorTimer = timer end Component.draw(self) end -- Set the character position of the text cursor. -- -- @param pos The new position for the cursor, where 0 is the beginning of the -- field. function TextField:setCursorPosition(pos) self.cursorPosition = pos if pos < self.textOffset then self.textOffset = pos end self:calculateTextClip() local textClip = self.textClip while (textClip) and (pos > self.textOffset + textClip) do self.textOffset = self.textOffset + 1 self:calculateTextClip() textClip = self.textClip end local text = self.text local cursorX = 0 for i=self.textOffset + 1,pos,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) cursorX = cursorX + charWidth end self.cursorX = cursorX self.cursorTimer = self.cursorRate end -- Calculates the text clip, i.e. how many characters to display. function TextField:calculateTextClip() local maxX = self.width - self.hPadding * 2 local text = self.text local totalWidth = 0 local startI = self.textOffset + 1 for i=startI,#text,1 do totalWidth = totalWidth + PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if totalWidth > maxX then self.textClip = i - startI return end end self.textClip = nil end function TextField:clickEvent(position, button, pressed) local xPos = position[1] - self.offset[1] - self.hPadding local text = self.text local totalWidth = 0 for i=self.textOffset + 1,#text,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if xPos < (totalWidth + charWidth * 0.8) then self:setCursorPosition(i - 1) return end totalWidth = totalWidth + charWidth end self:setCursorPosition(#text) end function TextField:keyEvent(keyCode, pressed) if not pressed then return end local keyState = GUI.keyState local shift = keyState[303] or keyState[304] local caps = keyState[301] local key = PtUtil.getKey(keyCode, shift, caps) local text = self.text local cursorPos = self.cursorPosition if #key == 1 then -- Type a character self.text = text:sub(1, cursorPos) .. key .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos + 1) else -- Special character if key == "backspace" then if cursorPos > 0 then self.text = text:sub(1, cursorPos - 1) .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos - 1) end elseif key == "enter" then if self.onEnter then self:onEnter() end elseif key == "delete" then if cursorPos < #text then self.text = text:sub(1, cursorPos) .. text:sub(cursorPos + 2) end elseif key == "right" then self:setCursorPosition(math.min(cursorPos + 1, #text)) elseif key == "left" then self:setCursorPosition(math.max(0, cursorPos - 1)) elseif key == "home" then self:setCursorPosition(0) elseif key == "end" then self:setCursorPosition(#text) end end end
-- Editable text field TextField = class(Component) TextField.vPadding = 3 TextField.hPadding = 4 TextField.borderColor = "#545454" TextField.backgroundColor = "black" TextField.textColor = "white" TextField.textHoverColor = "#999999" TextField.defaultTextColor = "#333333" TextField.defaultTextHoverColor = "#777777" TextField.cursorColor = "white" TextField.cursorRate = 1 -- Constructs a new TextField. -- -- @param x The x coordinate of the new component, relative to its parent. -- @param y The y coordinate of the new component, relative to its parent. -- @param width The width of the new component. -- @param height The height of the new component. -- @param defaultText The text to display when nothing has been entered. function TextField:_init(x, y, width, height, defaultText) Component._init(self) self.x = x self.y = y self.width = width self.height = height self.fontSize = height - self.vPadding * 2 self.cursorPosition = 0 self.cursorX = 0 self.cursorTimer = self.cursorRate self.text = "" self.defaultText = defaultText self.textOffset = 0 self.textClip = nil self.mouseOver = false end function TextField:draw(dt) local startX = self.x local startY = self.y local w = self.width local h = self.height -- Draw border and background local borderRect = { startX, startY, startX + w, startY + h } local backgroundRect = { startX + 1, startY + 1, startX + w - 1, startY + h - 1 } console.canvasDrawRect(borderRect, self.borderColor) console.canvasDrawRect(backgroundRect, self.backgroundColor) local text = self.text -- Decide if the default text should be displayed local default = (text == "") and (self.defaultText ~= nil) local textColor -- Choose the color to draw the text with if self.mouseOver then textColor = default and self.defaultTextHoverColor or self.textHoverColor else textColor = default and self.defaultTextColor or self.textColor end local cursorPosition = self.cursorPosition text = default and self.defaultText or text:sub(self.textOffset + 1, self.textOffset + (self.textClip or #text)) -- Draw the text console.canvasDrawText(text, { position = { startX + self.hPadding, startY + self.vPadding }, verticalAnchor = "bottom" }, self.fontSize, textColor) -- Text cursor if self.hasFocus then local timer = self.cursorTimer local rate = self.cursorRate timer = timer - dt if timer < 0 then timer = rate end if timer > rate / 2 then -- Draw cursor local cursorX = startX + self.cursorX + self.hPadding local cursorY = startY + self.vPadding console.canvasDrawLine({cursorX, cursorY}, {cursorX, cursorY + h - self.vPadding * 2}, self.cursorColor, 1) end self.cursorTimer = timer end Component.draw(self) end -- Set the character position of the text cursor. -- -- @param pos The new position for the cursor, where 0 is the beginning of the -- field. function TextField:setCursorPosition(pos) self.cursorPosition = pos if pos < self.textOffset then self.textOffset = pos end self:calculateTextClip() local textClip = self.textClip while (textClip) and (pos > self.textOffset + textClip) do self.textOffset = self.textOffset + 1 self:calculateTextClip() textClip = self.textClip end while self.textOffset > 0 and not textClip do self.textOffset = self.textOffset - 1 self:calculateTextClip() textClip = self.textClip if textClip then self.textOffset = self.textOffset + 1 self:calculateTextClip() end end -- world.logInfo("cursor: %s, textOffset: %s, textClip: %s", pos, self.textOffset, self.textClip) local text = self.text local cursorX = 0 for i=self.textOffset + 1,pos,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) cursorX = cursorX + charWidth end self.cursorX = cursorX self.cursorTimer = self.cursorRate end -- Calculates the text clip, i.e. how many characters to display. function TextField:calculateTextClip() local maxX = self.width - self.hPadding * 2 local text = self.text local totalWidth = 0 local startI = self.textOffset + 1 for i=startI,#text,1 do totalWidth = totalWidth + PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if totalWidth > maxX then self.textClip = i - startI return end end self.textClip = nil end function TextField:clickEvent(position, button, pressed) local xPos = position[1] - self.x - self.offset[1] - self.hPadding local text = self.text local totalWidth = 0 for i=self.textOffset + 1,#text,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if xPos < (totalWidth + charWidth * 0.6) then self:setCursorPosition(i - 1) return end totalWidth = totalWidth + charWidth end self:setCursorPosition(#text) end function TextField:keyEvent(keyCode, pressed) -- Ignore key releases and any keys pressed while ctrl or alt is held local keyState = GUI.keyState if not pressed or keyState[305] or keyState[306] or keyState[307] or keyState[308] then return end local shift = keyState[303] or keyState[304] local caps = keyState[301] local key = PtUtil.getKey(keyCode, shift, caps) local text = self.text local cursorPos = self.cursorPosition if #key == 1 then -- Type a character self.text = text:sub(1, cursorPos) .. key .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos + 1) else -- Special character if key == "backspace" then if cursorPos > 0 then self.text = text:sub(1, cursorPos - 1) .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos - 1) end elseif key == "enter" then if self.onEnter then self:onEnter() end elseif key == "delete" then if cursorPos < #text then self.text = text:sub(1, cursorPos) .. text:sub(cursorPos + 2) end elseif key == "right" then self:setCursorPosition(math.min(cursorPos + 1, #text)) elseif key == "left" then self:setCursorPosition(math.max(0, cursorPos - 1)) elseif key == "home" then self:setCursorPosition(0) elseif key == "end" then self:setCursorPosition(#text) end end end
Fixed mouse clicking and text clipping to actually work.
Fixed mouse clicking and text clipping to actually work. - There is a bug where drawing a string will trim the string of whitespace first.
Lua
apache-2.0
PenguinToast/PenguinGUI
c905a6a3300d0c8a00cdc6eac6bf345d7cfbf1ce
src/lua/luatexts/lua.lua
src/lua/luatexts/lua.lua
-------------------------------------------------------------------------------- -- luatexts/lua.lua: plain Lua implementation of luatexts -------------------------------------------------------------------------------- -- Copyright (c) 2011, luatexts authors -- See license in the file named COPYRIGHT -------------------------------------------------------------------------------- local error, pairs, select, type = error, pairs, select, type local table_concat = table.concat -------------------------------------------------------------------------------- local save do local handlers = { } local handle_value = function(cat, v, visited, buf) local handler = handlers[type(v)] if handler == nil then return nil, "can't save `" .. type(v) .. "'" end return handler(cat, v, { }, buf) end handlers["nil"] = function(cat, v, visited, buf) return cat "-" "\n" end handlers["boolean"] = function(cat, v, visited, buf) return cat (v and "1" or "0") "\n" end handlers["number"] = function(cat, v, visited, buf) return cat "N" "\n" (("%.54g"):format(v)) "\n" end handlers["string"] = function(cat, v, visited, buf) return cat "S" "\n" (#v) "\n" (v) "\n" end handlers["table"] = function(cat, t, visited, buf) if visited[t] then -- TODO: This should be `return nil, err`, not `error()`! error("circular table reference detected") end visited[t] = true cat "T" "\n" local array_size = #t cat (array_size) "\n" local hash_size_pos = #buf + 1 cat ("?") "\n" for i = 1, array_size do handle_value(cat, t[i], visited, buf) end local hash_size = 0 for k, v in pairs(t) do if type(k) ~= "number" or k > array_size or k < 1 or -- integer key in hash part of the table k % 1 ~= 0 -- non-integer key then hash_size = hash_size + 1 handle_value(cat, k, visited, buf) handle_value(cat, v, visited, buf) end end buf[hash_size_pos] = hash_size visited[t] = nil return cat end save = function(...) local nargs = select("#", ...) local buf = { } local function cat(s) buf[#buf + 1] = s; return cat end cat (nargs) "\n" for i = 1, nargs do handle_value(cat, select(i, ...), { }, buf) end return table_concat(buf) end end -------------------------------------------------------------------------------- return { _VERSION = "luatexts-lua 0.1"; _COPYRIGHT = "Copyright (C) 2011, luatexts authors"; _DESCRIPTION = "Trivial Lua human-readable binary-safe serialization library"; -- save = save; -- Sorry, no load() (yet). Patches are welcome. }
-------------------------------------------------------------------------------- -- luatexts/lua.lua: plain Lua implementation of luatexts -------------------------------------------------------------------------------- -- Copyright (c) 2011, luatexts authors -- See license in the file named COPYRIGHT -------------------------------------------------------------------------------- local assert, error, pairs, select, type = assert, error, pairs, select, type local table_concat = table.concat -------------------------------------------------------------------------------- local save do local handlers = { } local handle_value = function(cat, v, visited, buf) local handler = handlers[type(v)] if handler == nil then return nil, "can't save `" .. type(v) .. "'" end return handler(cat, v, { }, buf) end handlers["nil"] = function(cat, v, visited, buf) return cat "-" "\n" end handlers["boolean"] = function(cat, v, visited, buf) return cat (v and "1" or "0") "\n" end handlers["number"] = function(cat, v, visited, buf) return cat "N" "\n" (("%.54g"):format(v)) "\n" end handlers["string"] = function(cat, v, visited, buf) return cat "S" "\n" (#v) "\n" (v) "\n" end handlers["table"] = function(cat, t, visited, buf) if visited[t] then -- TODO: This should be `return nil, err`, not `error()`! error("circular table reference detected") end visited[t] = true cat "T" "\n" local array_size = #t cat (array_size) "\n" local hash_size_pos = #buf + 1 cat ("?") "\n" for i = 1, array_size do handle_value(cat, t[i], visited, buf) end local hash_size = 0 for k, v in pairs(t) do if type(k) ~= "number" or k > array_size or k < 1 or -- integer key in hash part of the table k % 1 ~= 0 -- non-integer key then hash_size = hash_size + 1 -- TODO: return nil, err on failure instead of asserting assert(handle_value(cat, k, visited, buf)) assert(handle_value(cat, v, visited, buf)) end end buf[hash_size_pos] = hash_size visited[t] = nil return cat end save = function(...) local nargs = select("#", ...) local buf = { } local function cat(s) buf[#buf + 1] = s; return cat end cat (nargs) "\n" for i = 1, nargs do handle_value(cat, select(i, ...), { }, buf) end return table_concat(buf) end end -------------------------------------------------------------------------------- return { _VERSION = "luatexts-lua 0.1"; _COPYRIGHT = "Copyright (C) 2011, luatexts authors"; _DESCRIPTION = "Trivial Lua human-readable binary-safe serialization library"; -- save = save; -- Sorry, no load() (yet). Patches are welcome. }
luatexts.lua: fixed error handling
luatexts.lua: fixed error handling
Lua
mit
agladysh/luatexts,agladysh/luatexts,agladysh/luatexts,agladysh/luatexts,agladysh/luatexts
b9a5a8596bcd91595e726addb176d1bcbbf5424f
lua/entities/gmod_wire_expression2/core/functions.lua
lua/entities/gmod_wire_expression2/core/functions.lua
--[[============================================================ E2 Function System By Rusketh General Operators ============================================================]]-- __e2setcost(20) registerOperator("function", "", "", function(self, args) local Stmt, args = args[2], args[3] local Sig, Return, Args = args[3], args[4], args[6] self.funcs[Sig] = function(self,args) local Variables = {} for K,Data in pairs (Args) do local Name, Type, OP = Data[1], Data[2], args[K + 1] local RV = OP[1](self, OP) Variables[#Variables + 1] = {Name,RV} end local OldScopes = self:SaveScopes() self:InitScope() -- Create a new Scope Enviroment self:PushScope() for I = 1, #Variables do local Var = Variables[I] self.Scope[Var[1]] = Var[2] self.Scope["$" .. Var[1]] = Var[2] self.Scope.vclk[Var[1]] = true end self.func_rv = nil local ok, msg = pcall(Stmt[1],self,Stmt) self:PopScope() self:LoadScopes(OldScopes) if not ok and msg:find( "C stack overflow" ) then error( "tick quota exceeded", -1 ) end -- a "C stack overflow" error will probably just confuse E2 users more than a "tick quota" error. if not ok and msg == "return" then return self.func_rv end if not ok then error(msg,0) end end end) __e2setcost(2) registerOperator("return", "", "", function(self, args) if args[2] then local op = args[2] local rv = op[1](self, op) self.func_rv = rv end error("return",0) end)
--[[============================================================ E2 Function System By Rusketh General Operators ============================================================]]-- __e2setcost(20) registerOperator("function", "", "", function(self, args) local Stmt, args = args[2], args[3] local Sig, ReturnType, Args = args[3], args[4], args[6] self.funcs[Sig] = function(self,args) local Variables = {} for K,Data in pairs (Args) do local Name, Type, OP = Data[1], Data[2], args[K + 1] local RV = OP[1](self, OP) Variables[#Variables + 1] = {Name,RV} end local OldScopes = self:SaveScopes() self:InitScope() -- Create a new Scope Enviroment self:PushScope() for I = 1, #Variables do local Var = Variables[I] self.Scope[Var[1]] = Var[2] self.Scope["$" .. Var[1]] = Var[2] self.Scope.vclk[Var[1]] = true end self.func_rv = nil local ok, msg = pcall(Stmt[1],self,Stmt) self:PopScope() self:LoadScopes(OldScopes) if not ok and msg:find( "C stack overflow" ) then error( "tick quota exceeded", -1 ) end -- a "C stack overflow" error will probably just confuse E2 users more than a "tick quota" error. if not ok and msg == "return" then return self.func_rv end if not ok then error(msg,0) end if Return ~= "" then error("Function " .. E2Lib.generate_signature(Sig, nil, Args) .. " executed and didn't return a value - expecting a value of type " .. E2Lib.typeName(ReturnType), 0) end end end) __e2setcost(2) registerOperator("return", "", "", function(self, args) if args[2] then local op = args[2] local rv = op[1](self, op) self.func_rv = rv end error("return",0) end)
Throw error when an E2 UDF doesn't return a value
Throw error when an E2 UDF doesn't return a value Fixes #519.
Lua
apache-2.0
sammyt291/wire,Grocel/wire,thegrb93/wire,garrysmodlua/wire,wiremod/wire,dvdvideo1234/wire,bigdogmat/wire,NezzKryptic/Wire
ddb2f7e81d268f36f1b213b506b27ef59bf3e3ca
tests/largetransfer.lua
tests/largetransfer.lua
-- tests large transmissions, sending and receiving -- uses `receive` and `receivePartial` -- Does send the same string twice simultaneously -- -- Test should; -- * show timer output, once per second, and actual time should be 1 second increments -- * both transmissions should take appr. equal time, then they we're nicely cooperative local copas = require 'copas' local socket = require 'socket' local body = ("A"):rep(1024*1024*50) -- 50 mb string local start = socket.gettime() local done = 0 local sparams, cparams local function runtest() local s1 = socket.bind('*', 49500) copas.addserver(s1, copas.handler(function(skt) --skt:settimeout(0) -- don't set, uses `receive` method local res, err, part = skt:receive('*a') res = res or part if res ~= body then print("Received doesn't match send") end print("Reading... 49500... Done!", socket.gettime()-start, err, #res) if copas.removeserver then copas.removeserver(s1) end end, sparams)) local s2 = socket.bind('*', 49501) copas.addserver(s2, copas.handler(function(skt) skt:settimeout(0) -- set, uses the `receivePartial` method local res, err, part = skt:receive('*a') res = res or part if res ~= body then print("Received doesn't match send") end print("Reading... 49501... Done!", socket.gettime()-start, err, #res) if copas.removeserver then copas.removeserver(s2) end end, sparams)) copas.addthread(function() copas.sleep(0) local skt = socket.tcp() skt = copas.wrap(skt, cparams) skt:connect("localhost", 49500) skt:send(body) print("Writing... 49500... Done!", socket.gettime()-start, err, #body) skt = nil collectgarbage() collectgarbage() done = done + 1 end) copas.addthread(function() copas.sleep(0) local skt = socket.tcp() skt = copas.wrap(skt, cparams) skt:connect("localhost", 49501) skt:send(body) print("Writing... 49501... Done!", socket.gettime()-start, err, #body) skt = nil collectgarbage() collectgarbage() done = done + 1 end) copas.addthread(function() copas.sleep(0) local i = 1 while done ~= 2 do copas.sleep(1) print(i, "seconds:", socket.gettime()-start) i = i + 1 end end) print("starting loop") copas.loop() print("Loop done") end runtest() -- run test using regular connection (s/cparams == nil) -- set ssl parameters and do it again sparams = { mode = "server", protocol = "tlsv1", key = "tests/certs/serverAkey.pem", certificate = "tests/certs/serverA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, } cparams = { mode = "client", protocol = "tlsv1", key = "tests/certs/clientAkey.pem", certificate = "tests/certs/clientA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, } done = 0 start = socket.gettime() runtest()
-- tests large transmissions, sending and receiving -- uses `receive` and `receivePartial` -- Does send the same string twice simultaneously -- -- Test should; -- * show timer output, once per second, and actual time should be 1 second increments -- * both transmissions should take appr. equal time, then they we're nicely cooperative local copas = require 'copas' local socket = require 'socket' local body = ("A"):rep(1024*1024*50) -- 50 mb string local start = socket.gettime() local done = 0 local sparams, cparams local function runtest() local s1 = socket.bind('*', 49500) copas.addserver(s1, copas.handler(function(skt) --skt:settimeout(0) -- don't set, uses `receive` method local res, err, part = skt:receive('*a') res = res or part if res ~= body then print("Received doesn't match send") end print("Reading... 49500... Done!", socket.gettime()-start, err, #res) if copas.removeserver then copas.removeserver(s1) end end, sparams)) local s2 = socket.bind('*', 49501) copas.addserver(s2, copas.handler(function(skt) skt:settimeout(0) -- set, uses the `receivePartial` method local res, err, part = skt:receive('*a') res = res or part if res ~= body then print("Received doesn't match send") end print("Reading... 49501... Done!", socket.gettime()-start, err, #res) if copas.removeserver then copas.removeserver(s2) end end, sparams)) copas.addthread(function() copas.sleep(0) local skt = socket.tcp() skt = copas.wrap(skt, cparams) skt:connect("localhost", 49500) skt:send(body) print("Writing... 49500... Done!", socket.gettime()-start, err, #body) skt = nil collectgarbage() collectgarbage() done = done + 1 end) copas.addthread(function() copas.sleep(0) local skt = socket.tcp() skt = copas.wrap(skt, cparams) skt:connect("localhost", 49501) skt:send(body) print("Writing... 49501... Done!", socket.gettime()-start, err, #body) skt = nil collectgarbage() collectgarbage() done = done + 1 end) copas.addthread(function() copas.sleep(0) local i = 1 while done ~= 2 do copas.sleep(1) print(i, "seconds:", socket.gettime()-start) i = i + 1 end end) print("starting loop") copas.loop() print("Loop done") end runtest() -- run test using regular connection (s/cparams == nil) -- set ssl parameters and do it again sparams = { mode = "server", protocol = "tlsv1", key = "./certs/serverAkey.pem", certificate = "./certs/serverA.pem", cafile = "./certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, } cparams = { mode = "client", protocol = "tlsv1", key = "./certs/clientAkey.pem", certificate = "./certs/clientA.pem", cafile = "./certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, } done = 0 start = socket.gettime() runtest()
Fix location of certs in tests so that `make test` doesn't fail.
Fix location of certs in tests so that `make test` doesn't fail.
Lua
mit
keplerproject/copas
39132638dd64e58d627124b36f7734563e1d1241
site/api/lib/elastic.lua
site/api/lib/elastic.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. ]]-- -- This is elastic.lua - ElasticSearch library local http = require 'socket.http' local JSON = require 'cjson' local config = require 'lib/config' local default_doc = "mbox" -- http code return check -- N.B. if the index is closed, ES returns 403, but that may perhaps be true for other conditions -- ES returns 404 if the index is missing. function checkReturn(code) if not code or code == "closed" then -- code is called by top-level functions only, so level 3 is the external caller error("Could not contact database backend!", 3) else -- we have a valid code -- index returns 201 when an entry is created if code ~= 200 and code ~= 201 then error("Backend Database returned code " .. code .. "!", 3) end end end -- Standard ES query, returns $size results of any doc of type $doc, sorting by $sitem function getHits(query, size, doc, sitem) doc = doc or "mbox" sitem = sitem or "epoch" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?q="..query.."&sort=" .. sitem .. ":desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, v._source) end end return out end -- Get a single document function getDoc (ty, id) local url = config.es_url .. ty .. "/" .. id local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) if json and json._source then json._source.request_id = json._id end return (json and json._source) and json._source or {} end -- Get results (a'la getHits), but only return email headers, not the body -- provides faster transport when we don't need everything function getHeaders(query, size, doc) doc = doc or "mbox" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=date:desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, v._source) end end return out end -- Same as above, but reverse return order function getHeadersReverse(query, size, doc) doc = doc or "mbox" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=epoch:desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, 1, v._source) end end return out end -- Do a raw ES query with a JSON query function raw(query, doctype) local js = JSON.encode(query) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/_search" local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) return json or {}, url end -- Raw query with scroll/scan function scan(query, doctype) local js = JSON.encode(query) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/_search?search_type=scan&scroll=1m" local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) if json and json._scroll_id then return json._scroll_id end return nil end function scroll(sid) -- We have to do some gsubbing here, as ES expects us to be at the root of the ES URL -- But in case we're being proxied, let's just cut off the last part of the URL local url = config.es_url:gsub("[^/]+/?$", "") .. "/_search/scroll?scroll=1m&scroll_id=" .. sid local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) if json and json._scroll_id then return json, json._scroll_id end return nil end -- Update a document function update(doctype, id, query, consistency) local js = JSON.encode({doc = query }) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/" .. id .. "/_update" if consistency then url = url .. "?write_consistency=" .. consistency end local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) return json or {}, url end -- Put a new document somewhere function index(r, id, ty, body, consistency) if not id then id = r:sha1(ty .. (math.random(1,99999999)*os.time()) .. ':' .. r:clock()) end local url = config.es_url .. ty .. "/" .. id if consistency then url = url .. "?write_consistency=" .. consistency end local result, hc = http.request(url, body) checkReturn(hc) local json = JSON.decode(result) return json or {} end function setDefault(typ) default_doc = typ end -- module defs return { find = getHits, findFast = getHeaders, findFastReverse = getHeadersReverse, get = getDoc, raw = raw, index = index, default = setDefault, update = update, scan = scan, scroll = scroll }
--[[ 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. ]]-- -- This is elastic.lua - ElasticSearch library local http = require 'socket.http' local JSON = require 'cjson' local config = require 'lib/config' local default_doc = "mbox" -- http code return check -- N.B. if the index is closed, ES returns 403, but that may perhaps be true for other conditions -- ES returns 404 if the index is missing. function checkReturn(code) if type(code) == "number" then -- we have a valid HTTP status code -- ignore expected return codes here -- index returns 201 when an entry is created if code ~= 200 and code ~= 201 then -- code is called by top-level functions only, so level 3 is the external caller error("Backend Database returned code " .. code .. "!", 3) end else error("Could not contact database backend: " .. code .. "!", 3) end end -- Standard ES query, returns $size results of any doc of type $doc, sorting by $sitem function getHits(query, size, doc, sitem) doc = doc or "mbox" sitem = sitem or "epoch" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?q="..query.."&sort=" .. sitem .. ":desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, v._source) end end return out end -- Get a single document function getDoc (ty, id) local url = config.es_url .. ty .. "/" .. id local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) if json and json._source then json._source.request_id = json._id end return (json and json._source) and json._source or {} end -- Get results (a'la getHits), but only return email headers, not the body -- provides faster transport when we don't need everything function getHeaders(query, size, doc) doc = doc or "mbox" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=date:desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, v._source) end end return out end -- Same as above, but reverse return order function getHeadersReverse(query, size, doc) doc = doc or "mbox" size = size or 10 query = query:gsub(" ", "+") local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=epoch:desc&size=" .. size local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) local out = {} if json and json.hits and json.hits.hits then for k, v in pairs(json.hits.hits) do v._source.request_id = v._id table.insert(out, 1, v._source) end end return out end -- Do a raw ES query with a JSON query function raw(query, doctype) local js = JSON.encode(query) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/_search" local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) return json or {}, url end -- Raw query with scroll/scan function scan(query, doctype) local js = JSON.encode(query) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/_search?search_type=scan&scroll=1m" local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) if json and json._scroll_id then return json._scroll_id end return nil end function scroll(sid) -- We have to do some gsubbing here, as ES expects us to be at the root of the ES URL -- But in case we're being proxied, let's just cut off the last part of the URL local url = config.es_url:gsub("[^/]+/?$", "") .. "/_search/scroll?scroll=1m&scroll_id=" .. sid local result, hc = http.request(url) checkReturn(hc) local json = JSON.decode(result) if json and json._scroll_id then return json, json._scroll_id end return nil end -- Update a document function update(doctype, id, query, consistency) local js = JSON.encode({doc = query }) doctype = doctype or default_doc local url = config.es_url .. doctype .. "/" .. id .. "/_update" if consistency then url = url .. "?write_consistency=" .. consistency end local result, hc = http.request(url, js) checkReturn(hc) local json = JSON.decode(result) return json or {}, url end -- Put a new document somewhere function index(r, id, ty, body, consistency) if not id then id = r:sha1(ty .. (math.random(1,99999999)*os.time()) .. ':' .. r:clock()) end local url = config.es_url .. ty .. "/" .. id if consistency then url = url .. "?write_consistency=" .. consistency end local result, hc = http.request(url, body) checkReturn(hc) local json = JSON.decode(result) return json or {} end function setDefault(typ) default_doc = typ end -- module defs return { find = getHits, findFast = getHeaders, findFastReverse = getHeadersReverse, get = getDoc, raw = raw, index = index, default = setDefault, update = update, scan = scan, scroll = scroll }
elastic.lua checkReturn() does not properly check return code
elastic.lua checkReturn() does not properly check return code This fixes #236
Lua
apache-2.0
Humbedooh/ponymail,quenda/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,quenda/ponymail,jimjag/ponymail,jimjag/ponymail,quenda/ponymail,jimjag/ponymail,jimjag/ponymail
ac79a571c591a590bb79497d7a7dc6935ba133f1
Interface/AddOns/RayUI/modules/actionbar/vehicleexit.lua
Interface/AddOns/RayUI/modules/actionbar/vehicleexit.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local AB = R:GetModule("ActionBar") local S = R:GetModule("Skins") --Cache global variables --Lua functions local _G = _G --WoW API / Variables local CreateFrame = CreateFrame local MainMenuBarVehicleLeaveButton_OnEnter = MainMenuBarVehicleLeaveButton_OnEnter local GameTooltip_Hide = GameTooltip_Hide local UnitOnTaxi = UnitOnTaxi local TaxiRequestEarlyLanding = TaxiRequestEarlyLanding local VehicleExit = VehicleExit local CanExitVehicle = CanExitVehicle local ActionBarController_GetCurrentActionBarState = ActionBarController_GetCurrentActionBarState --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: LE_ACTIONBAR_STATE_MAIN function AB:CreateVehicleExit() local holder = CreateFrame("Frame", nil, R.UIParent, "SecureHandlerStateTemplate") holder:SetHeight(AB.db.buttonsize) holder:SetWidth(AB.db.buttonsize) local bar = CreateFrame("Frame", "RayUIVehicleBar", holder) bar:SetFrameStrata("HIGH") bar:Show() bar:SetAllPoints() local veb = CreateFrame("BUTTON", nil, bar) veb:Show() veb:SetAllPoints() veb:CreateShadow("Background") veb:RegisterForClicks("AnyUp") veb.icon = veb:CreateFontString(nil, "OVERLAY") veb.icon:FontTemplate(R["media"].octicons, 20*R.mult, "OUTLINE") veb.icon:Point("CENTER", 2, -1) veb.icon:SetText("") veb:SetScript("OnClick", function(self) if ( UnitOnTaxi("player") ) then TaxiRequestEarlyLanding() self:GetNormalTexture():SetVertexColor(1, 0, 0) self:EnableMouse(false) else VehicleExit() end end) veb:SetScript("OnEnter", MainMenuBarVehicleLeaveButton_OnEnter) veb:HookScript("OnEnter", function() veb.icon:SetTextColor(S["media"].r, S["media"].g, S["media"].b) end) veb:SetScript("OnLeave", GameTooltip_Hide) veb:HookScript("OnLeave", function() veb.icon:SetTextColor(1, 1, 1) end) veb:RegisterEvent("PLAYER_ENTERING_WORLD") veb:RegisterEvent("UPDATE_BONUS_ACTIONBAR") veb:RegisterEvent("UPDATE_MULTI_CAST_ACTIONBAR") veb:RegisterEvent("UNIT_ENTERED_VEHICLE") veb:RegisterEvent("UNIT_EXITED_VEHICLE") veb:RegisterEvent("VEHICLE_UPDATE") veb:SetScript("OnEvent", function(self) if ( CanExitVehicle() and ActionBarController_GetCurrentActionBarState() == LE_ACTIONBAR_STATE_MAIN ) then self:Show() self:EnableMouse(true) else self:Hide() end end) if not self.db.bar2.enable and not self.db.bar3.enable and not ( R.db.movers and R.db.movers.ActionBar1Mover ) then holder:SetPoint("LEFT", "RayUIActionBar1", "RIGHT", AB.db.buttonspacing, 0) else--[[ if not ( R.db.movers and R.db.movers.ActionBar1Mover ) then ]] holder:SetPoint("BOTTOMLEFT", "RayUIActionBar3", "BOTTOMRIGHT", AB.db.buttonspacing, 0) end R:CreateMover(holder, "VehicleExitButtonMover", L["离开载具按钮"], true, nil, "ALL,ACTIONBARS") end
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local AB = R:GetModule("ActionBar") local S = R:GetModule("Skins") --Cache global variables --Lua functions local _G = _G --WoW API / Variables local CreateFrame = CreateFrame local MainMenuBarVehicleLeaveButton_OnEnter = MainMenuBarVehicleLeaveButton_OnEnter local GameTooltip_Hide = GameTooltip_Hide local UnitOnTaxi = UnitOnTaxi local TaxiRequestEarlyLanding = TaxiRequestEarlyLanding local VehicleExit = VehicleExit local CanExitVehicle = CanExitVehicle local ActionBarController_GetCurrentActionBarState = ActionBarController_GetCurrentActionBarState --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: LE_ACTIONBAR_STATE_MAIN function AB:CreateVehicleExit() local holder = CreateFrame("Frame", nil, R.UIParent, "SecureHandlerStateTemplate") holder:SetHeight(AB.db.buttonsize) holder:SetWidth(AB.db.buttonsize) local bar = CreateFrame("Frame", "RayUIVehicleBar", holder) bar:SetFrameStrata("HIGH") bar:Show() bar:SetAllPoints() local veb = CreateFrame("BUTTON", nil, bar) veb:Show() veb:SetAllPoints() veb:CreateShadow("Background") veb:RegisterForClicks("AnyUp") veb.icon = veb:CreateFontString(nil, "OVERLAY") veb.icon:FontTemplate(R["media"].octicons, 20*R.mult, "OUTLINE") veb.icon:Point("CENTER", 2, -1) veb.icon:SetText("") veb:SetScript("OnClick", function(self) if ( UnitOnTaxi("player") ) then TaxiRequestEarlyLanding() self:EnableMouse(false) else VehicleExit() end end) veb:SetScript("OnEnter", MainMenuBarVehicleLeaveButton_OnEnter) veb:HookScript("OnEnter", function() veb.icon:SetTextColor(S["media"].r, S["media"].g, S["media"].b) end) veb:SetScript("OnLeave", GameTooltip_Hide) veb:HookScript("OnLeave", function() veb.icon:SetTextColor(1, 1, 1) end) veb:RegisterEvent("PLAYER_ENTERING_WORLD") veb:RegisterEvent("UPDATE_BONUS_ACTIONBAR") veb:RegisterEvent("UPDATE_MULTI_CAST_ACTIONBAR") veb:RegisterEvent("UNIT_ENTERED_VEHICLE") veb:RegisterEvent("UNIT_EXITED_VEHICLE") veb:RegisterEvent("VEHICLE_UPDATE") veb:SetScript("OnEvent", function(self) if ( CanExitVehicle() and ActionBarController_GetCurrentActionBarState() == LE_ACTIONBAR_STATE_MAIN ) then self:Show() self:EnableMouse(true) else self:Hide() end end) if not self.db.bar2.enable and not self.db.bar3.enable and not ( R.db.movers and R.db.movers.ActionBar1Mover ) then holder:SetPoint("LEFT", "RayUIActionBar1", "RIGHT", AB.db.buttonspacing, 0) else--[[ if not ( R.db.movers and R.db.movers.ActionBar1Mover ) then ]] holder:SetPoint("BOTTOMLEFT", "RayUIActionBar3", "BOTTOMRIGHT", AB.db.buttonspacing, 0) end R:CreateMover(holder, "VehicleExitButtonMover", L["离开载具按钮"], true, nil, "ALL,ACTIONBARS") end
fix bug
fix bug
Lua
mit
fgprodigal/RayUI
e4b83a9e154e30e4388a1bf63786d1cd689cfd21
lift/init/config.lua
lift/init/config.lua
------------------------------------------------------------------------------ -- Default Lift Configuration ------------------------------------------------------------------------------ local config = ... local path = require 'lift.path' -- Default app_id and app_version if not config.app_version then config.app_version = config.LIFT_VERSION end -- Default init_file_name if not config.config_file_name then config.config_file_name = 'config.lua' end ------------------------------------------------------------------------------ -- Portable Directory Paths: {system,user}_{config,data}_dir and cache_dir -- We follow the XDG specification on UNIX and something sensible on Windows. ------------------------------------------------------------------------------ local function env(var_name, default_value) local v = var_name and os.getenv(var_name) return (v and path.to_slash(v)) or default_value end local function set_dir(name, unix_var, unix_default, win_var, win_default) if not config[name] then if config.IS_WINDOWS then config[name] = env(win_var, win_default) ..'/'.. config.app_id else config[name] = env(unix_var, unix_default) ..'/'.. config.app_id end end end set_dir('system_config_dir', nil, '/etc/xdg', 'ProgramFiles', 'c:/Program Files') set_dir('system_data_dir', nil, '/usr/local/share', 'ProgramData', 'c:/ProgramData') set_dir('user_config_dir', 'XDG_CONFIG_HOME', config.HOME..'/.config', 'APPDATA', 'c:') set_dir('user_data_dir', 'XDG_DATA_HOME', config.HOME..'/.local/share', 'LOCALAPPDATA', 'c:') set_dir('cache_dir', 'XDG_CACHE_HOME', config.HOME..'/.cache', 'TEMP', 'c:/Temp') ------------------------------------------------------------------------------ -- Default load_path ------------------------------------------------------------------------------ -- Add default entries to load_path local function add_path(p) if path.is_dir(p) then config:insert_unique('load_path', p) return true end end -- project-specific files (from CWD up to FS root) local dir = path.cwd() while true do add_path(dir..'/.'..config.app_id) if #dir <= 1 or path.is_root(dir) then break end dir = path.dir(dir) end add_path(config.user_config_dir) add_path(config.system_config_dir) assert(add_path(config.LIFT_SRC_DIR..'/init'), "missing Lift's built-in files")
------------------------------------------------------------------------------ -- Default Lift Configuration ------------------------------------------------------------------------------ local config = ... local path = require 'lift.path' -- Default app_id and app_version if not config.app_version then config.app_version = config.LIFT_VERSION end -- Default init_file_name if not config.config_file_name then config.config_file_name = 'config.lua' end ------------------------------------------------------------------------------ -- Portable Directory Paths: {system,user}_{config,data}_dir and cache_dir -- We follow the XDG specification on UNIX and something sensible on Windows. ------------------------------------------------------------------------------ local function env(var_name, default_value) local v = var_name and os.getenv(var_name) return (v and path.to_slash(v)) or default_value end local function set_dir(name, unix_var, unix_default, win_var, win_default) if not config[name] then if config.IS_WINDOWS then config[name] = env(win_var, win_default) ..'/'.. config.app_id else config[name] = env(unix_var, unix_default) ..'/'.. config.app_id end end end local function user_home(p) local home = config.HOME return home and (home..p) or p end set_dir('system_config_dir', nil, '/etc/xdg', 'ProgramFiles', 'c:/Program Files') set_dir('system_data_dir', nil, '/usr/local/share', 'ProgramData', 'c:/ProgramData') set_dir('user_config_dir', 'XDG_CONFIG_HOME', user_home('/.config'), 'APPDATA', 'c:') set_dir('user_data_dir', 'XDG_DATA_HOME', user_home('/.local/share'), 'LOCALAPPDATA', 'c:') set_dir('cache_dir', 'XDG_CACHE_HOME', user_home('/.cache'), 'TEMP', 'c:/Temp') ------------------------------------------------------------------------------ -- Default load_path ------------------------------------------------------------------------------ -- Add default entries to load_path local function add_path(p) if path.is_dir(p) then config:insert_unique('load_path', p) return true end end -- project-specific files (from CWD up to FS root) local dir = path.cwd() while true do add_path(dir..'/.'..config.app_id) if #dir <= 1 or path.is_root(dir) then break end dir = path.dir(dir) end add_path(config.user_config_dir) add_path(config.system_config_dir) assert(add_path(config.LIFT_SRC_DIR..'/init'), "missing Lift's built-in files")
Fix tests on Windows
Fix tests on Windows
Lua
mit
tbastos/lift
a89e2f5584415c1550e630e27b164c9ca369486c
modules/kibana_asf/files/frombrowser.lua
modules/kibana_asf/files/frombrowser.lua
#!/usr/bin/env lua package.path = package.path .. ";/usr/local/etc/logproxy/?.lua" local JSON = require "JSON" -- function for injecting strings into each 'query' element in the JSON function inject(tbl, what) for k, v in pairs(tbl) do if type(v) == "table" then inject(v, what) elseif k == "query" then tbl[k] = tbl[k] .. what end end end -- The main filter -- Get which user has authed this request local user = os.getenv('REMOTE_USER') -- Query LDAP for host records local hosts = {} -- If auth is broken/circumvented, return nothing if not user then print("{}") os.exit() end -- Validate user id, just in case user = user:gsub("[^-a-zA-Z0-9_.]+", "") -- Construct a list of valid hosts to retain data for local hosts = {} local allHosts = false local p = io.popen("ldapsearch -x -LLL uid="..user .. " host log-access-host log-access-vhost", "r") if p then local data = p:read("*a") p:close() for host in data:gmatch("host: ([^\r\n]+)") do host = host:gsub("%.apache%.org", "") table.insert(hosts, ([[@node:"%s.apache.org"]]):format(host)) if host == "*" then allHosts = true end end for host in data:gmatch("log-access-host: ([^\r\n]+)") do host = host:gsub("%.apache%.org", "") table.insert(hosts, ([[host:"%s.apache.org"]]):format(host)) if host == "*" then allHosts = true end end end -- Read JSON data from stdin local data = io.stdin:read("*a") local valid, json = pcall(function() return JSON:decode(data) end) -- If the input contains a query, then mangle it... if valid and json then -- If user doesn't have access to "*", then inject a host requirement into the query if not allHosts then local what = " AND (" .. table.concat(hosts, " OR ") .. ")" inject(json, what) end local output = JSON:encode(json) print(output) -- Send converted data down the chain -- If there's no query, just return what was sent else print(data) end
#!/usr/bin/env lua package.path = package.path .. ";/usr/local/etc/logproxy/?.lua" local JSON = require "JSON" -- function for injecting strings into each 'query' element in the JSON function inject(tbl, what) for k, v in pairs(tbl) do if type(v) == "table" then inject(v, what) elseif k == "query" then tbl[k] = tbl[k] .. what end end end -- The main filter -- Get which user has authed this request local user = os.getenv('REMOTE_USER') -- Query LDAP for host records local hosts = {} -- If auth is broken/circumvented, return nothing if not user then print("{}") os.exit() end -- Validate user id, just in case user = user:gsub("[^-a-zA-Z0-9_.]+", "") -- Construct a list of valid hosts to retain data for local hosts = {} local allHosts = false local p = io.popen("ldapsearch -x -LLL uid="..user .. " host log-access-host log-access-vhost", "r") if p then local data = p:read("*a") p:close() for host in data:gmatch("host: ([^\r\n]+)") do host = host:gsub("%.apache%.org", "") table.insert(hosts, ([[@node:"%s.apache.org"]]):format(host)) if host == "*" then allHosts = true end end for host in data:gmatch("log%-access%-host: ([^\r\n]+)") do host = host:gsub("%.apache%.org", "") table.insert(hosts, ([[@node:"%s.apache.org"]]):format(host)) if host == "*" then allHosts = true end end for host in data:gmatch("log%-access%-vhost: ([^\r\n]+)") do host = host:gsub("%.apache%.org", "") table.insert(hosts, ([[(vhost:"%s.apache.org" AND logtype:"httpd_access")]]):format(host)) if host == "*" then table.insert(hosts, ([[logtype:"httpd_access"]]):format(host)) end end end -- Read JSON data from stdin local data = io.stdin:read("*a") local valid, json = pcall(function() return JSON:decode(data) end) -- If the input contains a query, then mangle it... if valid and json then -- If user doesn't have access to "*", then inject a host requirement into the query if not allHosts then local what = " AND (" .. table.concat(hosts, " OR ") .. ")" inject(json, what) end local output = JSON:encode(json) print(output) -- Send converted data down the chain -- If there's no query, just return what was sent else print(data) end
fixup ACL
fixup ACL
Lua
apache-2.0
chtyim/infrastructure-puppet,sebbASF/infrastructure-puppet,apache/infrastructure-puppet,apache/infrastructure-puppet,stumped2/infrastructure-puppet,apache/infrastructure-puppet,chtyim/infrastructure-puppet,chtyim/infrastructure-puppet,sebbASF/infrastructure-puppet,sebbASF/infrastructure-puppet,bdube/infrastructure-puppet,sebbASF/infrastructure-puppet,stumped2/infrastructure-puppet,chtyim/infrastructure-puppet,sebbASF/infrastructure-puppet,chtyim/infrastructure-puppet,apache/infrastructure-puppet,chtyim/infrastructure-puppet,bdube/infrastructure-puppet,stumped2/infrastructure-puppet,apache/infrastructure-puppet,stumped2/infrastructure-puppet,apache/infrastructure-puppet,stumped2/infrastructure-puppet,sebbASF/infrastructure-puppet,apache/infrastructure-puppet,sebbASF/infrastructure-puppet,sebbASF/infrastructure-puppet,bdube/infrastructure-puppet,stumped2/infrastructure-puppet,bdube/infrastructure-puppet,bdube/infrastructure-puppet,bdube/infrastructure-puppet
7913f0da9e0238971780c72d22322c21ada5b70d
luasrc/multivariateGaussian.lua
luasrc/multivariateGaussian.lua
function randomkit.multivariateGaussianLogPDF(x, mu, sigma) x = torch.Tensor(x) mu = torch.Tensor(mu) -- If any input is vectorised, we return a vector. Otherwise remember that we should return scalar. local scalarResult = (x:dim() == 1) and (mu:dim() == 1) -- Now make our inputs all vectors, for simplicity if x:dim() == 1 then x:resize(1, x:nElement()) end if mu:dim() == 1 then mu:resize(1, mu:nElement()) end -- Expand any 1-row inputs so that we have matching sizes local nResults if x:size(1) == 1 and mu:size(1) ~= 1 then nResults = mu:size(1) x = x:expand(nResults, x:size(2)) elseif x:size(1) ~= 1 and mu:size(1) == 1 then nResults = x:size(1) mu = mu:expand(nResults, mu:size(2)) else if x:size(1) ~= mu:size(1) then error("x and mu should have the same number of rows") end nResults = x:size(1) end x = x:clone():add(-1, mu) local logdet local transformed -- For a diagonal covariance matrix, we allow passing a vector of the diagonal entries if sigma:dim() == 1 then local D = sigma:size(1) local decomposed = sigma:sqrt() logdet = decomposed:clone():log():sum() transformed = torch.cdiv(x, decomposed:resize(1, D):expand(nResults, D)) else local decomposed = torch.potrf(sigma):triu() -- TODO remove triu as torch will be fixed transformed = torch.mm(x, torch.inverse(decomposed)) logdet = decomposed:diag():log():sum() end transformed:apply(function(a) return randomkit.gaussianLogPDF(a, 0, 1) end) local result = transformed:sum(2) - logdet -- by independence if scalarResult then return result[1][1] else return result end end function randomkit.multivariateGaussianPDF(...) local r = randomkit.multivariateGaussianLogPDF(...) if type(r) == 'number' then return math.exp(r) else return r:exp() end end function randomkit.multivariateGaussianRand(...) local nArgs = select("#", ...) local resultTensor local n -- number of samples local d -- number of dimensions for the Gaussian local mu -- mean local sigma -- covariance matrix if nArgs == 2 then -- mu, sigma only: return one sample n = 1 mu = torch.Tensor(select(1, ...)) sigma = torch.Tensor(select(2, ...)) d = sigma:size(2) resultTensor = torch.Tensor(d) elseif nArgs == 3 then -- RESULT, mu, sigma - where result is either a number or an output tensor local resultInfo = select(1, ...) mu = torch.Tensor(select(2, ...)) sigma = torch.Tensor(select(3, ...)) -- If we have non-constant parameters, get the number of results to return from there local nParams if mu:dim() ~= 1 then nParams = mu:size(1) if sigma:dim() == 3 and sigma:size(1) ~= nParams then error("Incoherent parameter sizes for multivariateGaussianRand") end end if not nParams and sigma:dim() == 3 then nParams = sigma:size(1) end if type(resultInfo) == 'number' then n = resultInfo d = sigma:size(1) resultTensor = torch.Tensor(n, d) if nParams and nParams ~= n then error("Parameter sizes do not match number of samples requested") end elseif randomkit._isTensor(resultInfo) then resultTensor = resultInfo d = sigma:size(1) if nParams then n = nParams else n = resultTensor:nElement() / d end resultTensor:resize(n, d) else error("Unable to understand first argument for multivariateGaussianRand - should be an integer number of samples to be returned, or a result tensor") end else error("Invalid arguments for multivariateGaussianRand().\ Should be (mu, sigma), or (N, mu, sigma), or (ResultTensor, mu, sigma).") end print("mu", mu) print("sigma", sigma) -- Now make our inputs all tensors, for simplicity if mu:dim() == 1 then mu:resize(1, mu:nElement()) end if sigma:dim() == 2 then print("mu size", mu:size()) print("sigma size", sigma:size()) if mu:size(2) ~= sigma:size(1) or mu:size(2) ~= sigma:size(2) then error("multivariateGaussianRand: inconsistent sizes for mu and sigma") end sigma:resize(1, d, d) end if mu:size(1) == 1 then mu = mu:expand(n, d) end if sigma:size(1) == 1 then local resultSize = resultTensor:size() local x = torch.Tensor(n,d) randomkit.gauss(x) local y -- TODO: when Lapack's pstrf will be wrapped in Torch, use that instead of Cholesky with SVD failsafe local fullRank, decomposed = pcall(function() return torch.potrf(sigma[1]):triu() end) if fullRank then -- Definite positive matrix: use Cholesky y = torch.mm(x, decomposed) else -- Rank-deficient matrix: fall back on SVD local u, s, v = torch.svd(sigma[1]) local tmp = torch.cmul(x, s:sqrt():resize(1, d):expand(n, d)) y = torch.mm(tmp, v) end torch.add(resultTensor, y, mu):resize(resultSize) return resultTensor else error("Multiple covariance matrices: not implemented") --[[ TODO multiple sigmas for k = 1, n do local decomposed = torch.potrf(sigma[k]):triu() -- TODO remove triu as torch will be fixed local r = torch.mm(torch.randn(n, d), decomposed) + mu end --]] end end
function randomkit.multivariateGaussianLogPDF(x, mu, sigma) x = torch.Tensor(x) mu = torch.Tensor(mu) -- If any input is vectorised, we return a vector. Otherwise remember that we should return scalar. local scalarResult = (x:dim() == 1) and (mu:dim() == 1) -- Now make our inputs all vectors, for simplicity if x:dim() == 1 then x:resize(1, x:nElement()) end if mu:dim() == 1 then mu:resize(1, mu:nElement()) end -- Expand any 1-row inputs so that we have matching sizes local nResults if x:size(1) == 1 and mu:size(1) ~= 1 then nResults = mu:size(1) x = x:expand(nResults, x:size(2)) elseif x:size(1) ~= 1 and mu:size(1) == 1 then nResults = x:size(1) mu = mu:expand(nResults, mu:size(2)) else if x:size(1) ~= mu:size(1) then error("x and mu should have the same number of rows") end nResults = x:size(1) end x = x:clone():add(-1, mu) local logdet local transformed -- For a diagonal covariance matrix, we allow passing a vector of the diagonal entries if sigma:dim() == 1 then local D = sigma:size(1) local decomposed = sigma:sqrt() logdet = decomposed:clone():log():sum() transformed = torch.cdiv(x, decomposed:resize(1, D):expand(nResults, D)) else local decomposed = torch.potrf(sigma):triu() -- TODO remove triu as torch will be fixed transformed = torch.mm(x, torch.inverse(decomposed)) logdet = decomposed:diag():log():sum() end transformed:apply(function(a) return randomkit.gaussianLogPDF(a, 0, 1) end) local result = transformed:sum(2) - logdet -- by independence if scalarResult then return result[1][1] else return result end end function randomkit.multivariateGaussianPDF(...) local r = randomkit.multivariateGaussianLogPDF(...) if type(r) == 'number' then return math.exp(r) else return r:exp() end end function randomkit.multivariateGaussianRand(...) local nArgs = select("#", ...) local resultTensor local n -- number of samples local d -- number of dimensions for the Gaussian local mu -- mean local sigma -- covariance matrix if nArgs == 2 then -- mu, sigma only: return one sample n = 1 mu = torch.Tensor(select(1, ...)) sigma = torch.Tensor(select(2, ...)) d = sigma:size(2) resultTensor = torch.Tensor(d) elseif nArgs == 3 then -- RESULT, mu, sigma - where result is either a number or an output tensor local resultInfo = select(1, ...) mu = torch.Tensor(select(2, ...)) sigma = torch.Tensor(select(3, ...)) -- If we have non-constant parameters, get the number of results to return from there local nParams if mu:dim() ~= 1 then nParams = mu:size(1) if sigma:dim() == 3 and sigma:size(1) ~= nParams then error("Incoherent parameter sizes for multivariateGaussianRand") end end if not nParams and sigma:dim() == 3 then nParams = sigma:size(1) end d = sigma:size(2) if type(resultInfo) == 'number' then n = resultInfo resultTensor = torch.Tensor(n, d) if nParams and nParams ~= n then error("Parameter sizes do not match number of samples requested") end elseif randomkit._isTensor(resultInfo) then resultTensor = resultInfo if nParams then n = nParams else n = resultTensor:nElement() / d end resultTensor:resize(n, d) else error("Unable to understand first argument for multivariateGaussianRand - should be an integer number of samples to be returned, or a result tensor") end else error("Invalid arguments for multivariateGaussianRand().\ Should be (mu, sigma), or (N, mu, sigma), or (ResultTensor, mu, sigma).") end print("mu", mu) print("sigma", sigma) -- Now make our inputs all tensors, for simplicity if mu:dim() == 1 then mu:resize(1, mu:nElement()) end if sigma:dim() == 2 then print("mu size", mu:size()) print("sigma size", sigma:size()) if mu:size(2) ~= sigma:size(1) or mu:size(2) ~= sigma:size(2) then error("multivariateGaussianRand: inconsistent sizes for mu and sigma") end sigma:resize(1, d, d) end if mu:size(2) ~= d or sigma:size(2) ~= d or sigma:size(3) ~= d then error("multivariateGaussianRand: inconsistent sizes for mu and sigma") end if mu:size(1) == 1 then print("trying to expand mu to " .. n .. "x" .. d) print("mu is ", mu) mu = mu:expand(n, d) end if sigma:size(1) == 1 then local resultSize = resultTensor:size() local x = torch.Tensor(n,d) randomkit.gauss(x) local y -- TODO: when Lapack's pstrf will be wrapped in Torch, use that instead of Cholesky with SVD failsafe local fullRank, decomposed = pcall(function() return torch.potrf(sigma[1]):triu() end) if fullRank then -- Definite positive matrix: use Cholesky y = torch.mm(x, decomposed) else -- Rank-deficient matrix: fall back on SVD local u, s, v = torch.svd(sigma[1]) local tmp = torch.cmul(x, s:sqrt():resize(1, d):expand(n, d)) y = torch.mm(tmp, v) end torch.add(resultTensor, y, mu):resize(resultSize) return resultTensor else error("Multiple covariance matrices: not implemented") --[[ TODO multiple sigmas for k = 1, n do local decomposed = torch.potrf(sigma[k]):triu() -- TODO remove triu as torch will be fixed local r = torch.mm(torch.randn(n, d), decomposed) + mu end --]] end end
Fix for inferring dimensionality
Fix for inferring dimensionality
Lua
bsd-3-clause
fastturtle/torch-randomkit,fastturtle/torch-randomkit,deepmind/torch-randomkit,deepmind/torch-randomkit
42034f35e7dba6d680ad82ab326b9dc95f3e41ba
xmake/modules/detect/tools/nvcc/has_flags.lua
xmake/modules/detect/tools/nvcc/has_flags.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") import("core.language.language") -- is linker? function _islinker(flags, opt) -- the flags is "-Wl,<arg>" or "-Xlinker <arg>"? local flags_str = table.concat(flags, " ") if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then return true end -- the tool kind is ld or sh? local toolkind = opt.toolkind or "" return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh") end -- try running function _try_running(...) local argv = {...} local errors = nil return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors end -- attempt to check it from the argument list function _check_from_arglist(flags, opt, islinker) -- check for the builtin flags local builtin_flags = {["-code"] = true, ["--gpu-code"] = true, ["-gencode"] = true, ["--generate-code"] = true, ["-arch"] = true, ["--gpu-architecture"] = true, ["-cudart=none"] = true, ["--cudart=none"] = true} if builtin_flags[flags[1]] then return true end -- check for the builtin flag=value local cudart_flags = {none = true, shared = true, static = true} local builtin_flags_pair = {["-cudart"] = cudart_flags, ["--cudart"] = cudart_flags} if #flags > 1 and builtin_flags_pair[flags[1]] and builtin_flags_pair[flags[1]][flags[2]] then return true end -- check from the `--help` menu, only for linker if islinker or #flags > 1 then return end -- make cache key local key = "detect.tools.nvcc.has_flags" -- make flags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all flags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = os.iorunv(opt.program, {"--help"}) if arglist then for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do allflags[arg] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]] end -- try running to check flags function _check_try_running(flags, opt, islinker) -- make an stub source file local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu") if not os.isfile(sourcefile) then io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end local args = table.join(flags, "-o", os.nuldev(), sourcefile) if not islinker then table.insert(args, 2, "-c") end local allow_unsupported_compiler = main("-allow-unsupported-compiler", opt) if allow_unsupported_compiler then table.insert(args, 1, "-allow-unsupported-compiler") end -- check flags return _try_running(opt.program, args) end -- has_flags(flags)? -- -- @param opt the argument options, e.g. {toolname = "", program = "", programver = "", toolkind = "cu"} -- -- @return true or false -- function main(flags, opt) -- is linker? local islinker = _islinker(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt, islinker) then return true end -- try running to check it return _check_try_running(flags, opt, islinker) end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") import("core.language.language") -- is linker? function _islinker(flags, opt) -- the flags is "-Wl,<arg>" or "-Xlinker <arg>"? local flags_str = table.concat(flags, " ") if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then return true end -- the tool kind is ld or sh? local toolkind = opt.toolkind or "" return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh") end -- try running function _try_running(...) local argv = {...} local errors = nil return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors end -- attempt to check it from the argument list function _check_from_arglist(flags, opt, islinker) -- check for the builtin flags local builtin_flags = {["-code"] = true, ["--gpu-code"] = true, ["-gencode"] = true, ["--generate-code"] = true, ["-arch"] = true, ["--gpu-architecture"] = true, ["-cudart=none"] = true, ["--cudart=none"] = true} if builtin_flags[flags[1]] then return true end -- check for the builtin flag=value local cudart_flags = {none = true, shared = true, static = true} local builtin_flags_pair = {["-cudart"] = cudart_flags, ["--cudart"] = cudart_flags} if #flags > 1 and builtin_flags_pair[flags[1]] and builtin_flags_pair[flags[1]][flags[2]] then return true end -- check from the `--help` menu, only for linker if islinker or #flags > 1 then return end -- make cache key local key = "detect.tools.nvcc.has_flags" -- make flags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all flags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = os.iorunv(opt.program, {"--help"}) if arglist then for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do allflags[arg] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]] end -- try running to check flags function _check_try_running(flags, opt, islinker) -- make an stub source file local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu") if not os.isfile(sourcefile) then io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end local args = table.join("-o", os.nuldev(), sourcefile) if not islinker then table.insert(args, 1, "-c") end if flags[1] ~= "-allow-unsupported-compiler" then local allow_unsupported_compiler = main({"-allow-unsupported-compiler"}, opt) if allow_unsupported_compiler then table.insert(args, 1, "-allow-unsupported-compiler") end end -- check flags return _try_running(opt.program, table.join(flags, args)) end -- has_flags(flags)? -- -- @param opt the argument options, e.g. {toolname = "", program = "", programver = "", toolkind = "cu"} -- -- @return true or false -- function main(flags, opt) -- is linker? local islinker = _islinker(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt, islinker) then return true end -- try running to check it return _check_try_running(flags, opt, islinker) end
fix has_flags
fix has_flags
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
568d668519324ab3a060f01f9f6c4b876d90ee5e
nvim/lua/plugins.lua
nvim/lua/plugins.lua
return require('packer').startup(function() use('wbthomason/packer.nvim') use('folke/tokyonight.nvim') -- -- nvim dependencies -- use('nvim-lua/plenary.nvim') use('kyazdani42/nvim-web-devicons') use('tami5/sqlite.lua') -- -- nvim plugins -- use({ 'nvim-treesitter/nvim-treesitter', run = 'TSUpdate', commit = '57f4dbd47b2af3898a6153cd915b106eb72fc980', }) use('nvim-treesitter/nvim-treesitter-textobjects') use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/plenary.nvim' } }, }) use({ 'nvim-telescope/telescope-frecency.nvim', requires = { { 'tami5/sqlite.lua' } }, }) use({ 'nvim-telescope/telescope-fzf-native.nvim', requires = { { 'nvim-telescope/telescope.nvim' } }, run = 'make', }) use({ 'nvim-telescope/telescope-smart-history.nvim', run = 'mkdir -p ~/.local/share/nvim/databases', requires = { { 'nvim-telescope/telescope.nvim', 'tami5/sqlite.lua' } }, }) use('neovim/nvim-lspconfig') use('williamboman/nvim-lsp-installer') use('hrsh7th/nvim-cmp') use('hrsh7th/cmp-nvim-lsp') use('hrsh7th/cmp-buffer') use('hrsh7th/cmp-cmdline') use('hrsh7th/cmp-path') use('L3MON4D3/LuaSnip') use('saadparwaiz1/cmp_luasnip') use({ 'nvim-neo-tree/neo-tree.nvim', branch = 'v2.x', requires = { 'nvim-lua/plenary.nvim', 'kyazdani42/nvim-web-devicons', 'MunifTanjim/nui.nvim', }, }) use({ 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons' }, }) use('lukas-reineke/indent-blankline.nvim') use('xiyaowong/nvim-cursorword') use('lewis6991/gitsigns.nvim') -- -- evaluating nvim plugins -- use({ 'seblj/nvim-tabline', requires = { 'kyazdani42/nvim-web-devicons' }, }) use('petertriho/nvim-scrollbar') use('windwp/nvim-autopairs') use('windwp/nvim-ts-autotag') use('folke/lua-dev.nvim') use('mfussenegger/nvim-treehopper') use('phaazon/hop.nvim') use('ethanholz/nvim-lastplace') use('rcarriga/nvim-notify') -- -- older, but still useful vim plugins -- use('AndrewRadev/splitjoin.vim') use('tpope/vim-unimpaired') use({ 'kylechui/nvim-surround', tag = '*', -- Use for stability; omit for the latest features }) use('tpope/vim-repeat') use('tommcdo/vim-exchange') use('wellle/targets.vim') use('editorconfig/editorconfig-vim') use({ 'terrortylor/nvim-comment', config = function() require('ryankoval.nvim-comment') end, }) use({ 'kshenoy/vim-signature', config = function() require('ryankoval.vim-signature') end, }) use('ruanyl/vim-gh-line') use({ 'tpope/vim-fugitive', config = function() require('ryankoval.vim-fugitive') end, }) use({ 'tpope/vim-rhubarb', requires = { { 'vim-fugitive' } }, }) -- -- probably keep -- use('mg979/vim-visual-multi') use({ 'mattn/emmet-vim', ft = { 'html', 'css', 'less', 'scss', 'vue', 'markdown' }, config = function() require('ryankoval.emmet-vim') end, }) end)
return require('packer').startup(function() use('wbthomason/packer.nvim') use('folke/tokyonight.nvim') -- -- nvim dependencies -- use('nvim-lua/plenary.nvim') use('kyazdani42/nvim-web-devicons') use('tami5/sqlite.lua') -- -- nvim plugins -- use({ 'nvim-treesitter/nvim-treesitter', run = 'TSUpdate', commit = '57f4dbd47b2af3898a6153cd915b106eb72fc980', }) use('nvim-treesitter/nvim-treesitter-textobjects') use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/plenary.nvim' } }, }) use({ 'nvim-telescope/telescope-frecency.nvim', requires = { { 'tami5/sqlite.lua' } }, }) use({ 'nvim-telescope/telescope-fzf-native.nvim', requires = { { 'nvim-telescope/telescope.nvim' } }, run = 'make', }) use({ 'nvim-telescope/telescope-smart-history.nvim', run = 'mkdir -p ~/.local/share/nvim/databases', requires = { { 'nvim-telescope/telescope.nvim', 'tami5/sqlite.lua' } }, }) use('neovim/nvim-lspconfig') use('williamboman/nvim-lsp-installer') use('hrsh7th/nvim-cmp') use('hrsh7th/cmp-nvim-lsp') use('hrsh7th/cmp-buffer') use('hrsh7th/cmp-cmdline') use('hrsh7th/cmp-path') use('L3MON4D3/LuaSnip') use('saadparwaiz1/cmp_luasnip') use({ 'nvim-neo-tree/neo-tree.nvim', branch = 'v2.x', requires = { 'nvim-lua/plenary.nvim', 'kyazdani42/nvim-web-devicons', 'MunifTanjim/nui.nvim', }, }) use({ 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons' }, }) use('lukas-reineke/indent-blankline.nvim') use('xiyaowong/nvim-cursorword') use('lewis6991/gitsigns.nvim') -- -- evaluating nvim plugins -- use({ 'seblj/nvim-tabline', requires = { 'kyazdani42/nvim-web-devicons' }, }) use('petertriho/nvim-scrollbar') use('windwp/nvim-autopairs') use('windwp/nvim-ts-autotag') use('folke/lua-dev.nvim') use('mfussenegger/nvim-treehopper') use('phaazon/hop.nvim') use('ethanholz/nvim-lastplace') use('rcarriga/nvim-notify') -- -- older, but still useful vim plugins -- use('AndrewRadev/splitjoin.vim') use('tpope/vim-unimpaired') use({ 'kylechui/nvim-surround', tag = '*', -- Use for stability; omit for the latest features }) use('tpope/vim-repeat') use('tommcdo/vim-exchange') use('wellle/targets.vim') use('editorconfig/editorconfig-vim') use({ 'terrortylor/nvim-comment', config = function() require('ryankoval.nvim-comment') end, }) use({ 'kshenoy/vim-signature', config = function() require('ryankoval.vim-signature') end, }) use('ruanyl/vim-gh-line') use({ 'tpope/vim-fugitive', config = function() require('ryankoval.vim-fugitive') end, }) use({ 'tpope/vim-rhubarb', requires = { { 'vim-fugitive' } }, }) -- -- probably keep -- use('mg979/vim-visual-multi') use({ 'mattn/emmet-vim', ft = { 'html', 'css', 'less', 'javascriptreact', 'typescriptreact', 'scss', 'vue', 'markdown' }, config = function() require('ryankoval.emmet-vim') end, }) end)
fixed emmet
fixed emmet
Lua
mit
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
165e0583ff475005b18084b03c9cfec424e2fba1
lua/entities/gmod_wire_expression2/core/cl_console.lua
lua/entities/gmod_wire_expression2/core/cl_console.lua
local convars = { wire_expression2_concmd = 0, wire_expression2_concmd_whitelist = "", } local function CreateCVars() for name,default in pairs(convars) do current_cvar = CreateClientConVar(name, default, true, true) local value = current_cvar:GetString() or default RunConsoleCommand(name, value) end end if CanRunConsoleCommand() then CreateCVars() else hook.Add("OnEntityCreated", "wire_expression2_console", function(ent) if not IsValid(ent) then return end if ent ~= LocalPlayer() then return end CreateCVars() timer.Create("Remove_wire_expression2_console_Hook",0,1,function() hook.Remove("OnEntityCreated", "wire_expression2_console") end) -- Removing it immediately may hurt the hook loop end) end
local convars = { wire_expression2_concmd = 0, wire_expression2_concmd_whitelist = "", } local function CreateCVars() for name,default in pairs(convars) do local current_cvar = CreateClientConVar(name, default, true, true) local value = current_cvar:GetString() or default RunConsoleCommand(name, value) end end if CanRunConsoleCommand() then CreateCVars() else hook.Add("Initialize", "wire_expression2_console", function() CreateCVars() end) end
Switch cl_console's convars to start on Initialize instead of OnEntityCreated May improve compatibility with addons that for some reason fiddle with OnEntityCreate for LocalPlayer() Fixes #1470
Switch cl_console's convars to start on Initialize instead of OnEntityCreated May improve compatibility with addons that for some reason fiddle with OnEntityCreate for LocalPlayer() Fixes #1470
Lua
apache-2.0
sammyt291/wire,Grocel/wire,dvdvideo1234/wire,bigdogmat/wire,wiremod/wire,garrysmodlua/wire,thegrb93/wire,NezzKryptic/Wire
78313dbb4b85d42e08cfff9a8494c6c764a64c56
packages/verbatim.lua
packages/verbatim.lua
SILE.registerCommand("verbatim:font", function(options, content) SILE.settings.set("font.family", "Consolas") SILE.settings.set("font.size", SILE.settings.get("font.size") - 3) end, "The font chosen for the verbatim environment") SILE.registerCommand("verbatim", function(options, content) SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) }) SILE.typesetter:leaveHmode() SILE.settings.temporarily(function() SILE.settings.set("typesetter.parseppattern", "\n") SILE.settings.set("typesetter.obeyspaces", true) SILE.settings.set("document.rskip", SILE.nodefactory.newGlue("0 plus 10000pt")) SILE.settings.set("document.parindent", SILE.nodefactory.newGlue("0")) SILE.settings.set("document.baselineskip", SILE.nodefactory.newVglue("0")) SILE.settings.set("document.lineskip", SILE.nodefactory.newVglue("2pt")) SILE.call("verbatim:font") SILE.settings.set("document.spaceskip", SILE.length.parse("1spc")) SILE.settings.set("document.language", "und") -- SILE.settings.set("shaper.spacepattern", '%s') -- XXX Shaper no longer uses this so it was removed SILE.process(content) end) SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) }) end, "Typesets its contents in a monospaced font.") SILE.registerCommand("obeylines", function(options, content) SILE.settings.temporarily(function() SILE.settings.set("typesetter.parseppattern", "\n") SILE.process(content) end) end) return [[\begin{document} The \code{verbatim} package is useful when quoting pieces of computer code and other text for which formatting is significant. It changes SILE’s settings so that text is set ragged right, with no hyphenation, no indentation and regular spacing. It tells SILE to honor multiple spaces, and sets a monospaced font. \note{Despite the name, \code{verbatim} does not alter the way that SILE sees special characters. You still need to escape backslashes and braces: to produce a backslash, you need to write \code{\\\\}.} Here is some text set in the verbatim environment: \begin{verbatim} function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end \end{verbatim} If you want to specify what font the verbatim environment should use, you can redefine the \code{verbatim:font} command. The current document says: \begin{verbatim} <define command="verbatim:font"> <font family="DejaVu Sans Mono" size="9pt"/> </define> \end{verbatim} \end{document}]]
SILE.registerCommand("verbatim:font", function(options, content) SILE.settings.set("font.family", "Consolas") SILE.settings.set("font.size", SILE.settings.get("font.size") - 3) end, "The font chosen for the verbatim environment") SILE.registerCommand("verbatim", function(options, content) SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) }) SILE.typesetter:leaveHmode() SILE.settings.temporarily(function() SILE.settings.set("typesetter.parseppattern", "\n") SILE.settings.set("typesetter.obeyspaces", true) SILE.settings.set("document.rskip", SILE.nodefactory.newGlue("0 plus 10000pt")) SILE.settings.set("document.parindent", SILE.nodefactory.newGlue("0")) SILE.settings.set("document.baselineskip", SILE.nodefactory.newVglue("0")) SILE.settings.set("document.lineskip", SILE.nodefactory.newVglue("2pt")) SILE.call("verbatim:font") SILE.settings.set("document.spaceskip", SILE.length.parse("1spc")) SILE.settings.set("document.language", "und") -- SILE.settings.set("shaper.spacepattern", '%s') -- XXX Shaper no longer uses this so it was removed SILE.process(content) end) SILE.typesetter:leaveHmode() end, "Typesets its contents in a monospaced font.") SILE.registerCommand("obeylines", function(options, content) SILE.settings.temporarily(function() SILE.settings.set("typesetter.parseppattern", "\n") SILE.process(content) end) end) return [[\begin{document} The \code{verbatim} package is useful when quoting pieces of computer code and other text for which formatting is significant. It changes SILE’s settings so that text is set ragged right, with no hyphenation, no indentation and regular spacing. It tells SILE to honor multiple spaces, and sets a monospaced font. \note{Despite the name, \code{verbatim} does not alter the way that SILE sees special characters. You still need to escape backslashes and braces: to produce a backslash, you need to write \code{\\\\}.} Here is some text set in the verbatim environment: \begin{verbatim} function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end \end{verbatim} If you want to specify what font the verbatim environment should use, you can redefine the \code{verbatim:font} command. The current document says: \begin{verbatim} <define command="verbatim:font"> <font family="DejaVu Sans Mono" size="9pt"/> </define> \end{verbatim} \end{document}]]
Ensure end-of-line after verbatim environment. Fixes #317
Ensure end-of-line after verbatim environment. Fixes #317
Lua
mit
alerque/sile,simoncozens/sile,neofob/sile,alerque/sile,neofob/sile,neofob/sile,simoncozens/sile,neofob/sile,simoncozens/sile,alerque/sile,simoncozens/sile,alerque/sile
1593a21033a70ddbd3a5dfb8ee0cdc18d4d0e4b5
inkblazers.lua
inkblazers.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 illu_name = os.getenv('illu_name') local illu_number = os.getenv('illu_number') 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"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if string.match(url, "images%.inkblazers%.com") then return verdict elseif item_type == "illustration" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "[^0-9]"..illu_name.."[^0-9]") or string.match(url, "[^0-9]"..illu_number.."[^0-9]") then return verdict elseif html == 0 then return verdict else return false end elseif item_type == "manga" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "/"..illu_number.."/[0-9]+/[0-9]+") then return verdict elseif html == 0 then return verdict 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 table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "illustration" then if string.match(url, "https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/illustrations/[^/]+/detail%-page/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end local dataurl1 = string.match(html, 'data%-url="([^"]+)"') local dataurl = "http://www.inkblazers.com"..dataurl1 check(dataurl) local datalink = string.match(html, 'data%-link="([^"]+)"') if not string.match(datalink, "load%-as%-page%-by%-profile%-key%.json") then check(datalink) end local datapicture = string.match(html, 'data%-picture="([^"]+)"') check(datapicture) end elseif item_type == "manga" then if string.match(url, "images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://[^/]+/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/api/1%.0/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com/") then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do local nurl = "http://www.inkblazers.com"..newurl io.stdout:write("added "..nurl) io.stdout:flush() if string.match(nurl, "/"..illu_number.."/[0-9]+/[0-9]+/") then io.stdout:write("checking "..nurl) io.stdout:flush() check(nurl) end end end if string.match(url, "inkblazers%.com/manga%-and%-comics/"..illu_name.."/detail%-page/"..illu_number) or string.match(url, "inkblazers%.com/read%-manga/[^/]+/"..illu_number.."/[0-9]+/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") or string.match(newurl, "/"..illu_number.."/[0-9]+/[0-9]+") then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do local nurl = "http://www.inkblazers.com"..newurl io.stdout:write("added "..nurl) io.stdout:flush() if string.match(nurl, "/"..illu_number.."/[0-9]+/[0-9]+/") then io.stdout:write("checking "..nurl) io.stdout:flush() check(nurl) 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"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 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) 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") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local illu_name = os.getenv('illu_name') local illu_number = os.getenv('illu_number') 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"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if string.match(url, "images%.inkblazers%.com") then return verdict elseif item_type == "illustration" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "[^0-9]"..illu_name.."[^0-9]") or string.match(url, "[^0-9]"..illu_number.."[^0-9]") then return verdict elseif html == 0 then return verdict else return false end elseif item_type == "manga" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "/"..illu_number.."/[0-9]+/[0-9]+") then return verdict elseif html == 0 then return verdict 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 table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "illustration" then if string.match(url, "https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/illustrations/[^/]+/detail%-page/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end local dataurl1 = string.match(html, 'data%-url="([^"]+)"') local dataurl = "http://www.inkblazers.com"..dataurl1 check(dataurl) local datalink = string.match(html, 'data%-link="([^"]+)"') if not string.match(datalink, "load%-as%-page%-by%-profile%-key%.json") then check(datalink) end local datapicture = string.match(html, 'data%-picture="([^"]+)"') check(datapicture) end elseif item_type == "manga" then if string.match(url, "images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://[^/]+/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/api/1%.0/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com/") then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do local nurl = "http://www.inkblazers.com"..newurl if string.match(nurl, "/"..illu_number.."/[0-9]+/[0-9]+") then check(nurl) end end end if string.match(url, "inkblazers%.com/manga%-and%-comics/"..illu_name.."/detail%-page/"..illu_number) or string.match(url, "inkblazers%.com/read%-manga/[^/]+/"..illu_number.."/[0-9]+/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") or string.match(newurl, "/"..illu_number.."/[0-9]+/[0-9]+") then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do local nurl = "http://www.inkblazers.com"..newurl if string.match(nurl, "/"..illu_number.."/[0-9]+/[0-9]+") then check(nurl) 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"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 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) 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
inkblazers.lua: fix the error
inkblazers.lua: fix the error
Lua
unlicense
ArchiveTeam/inkblazers-grab,ArchiveTeam/inkblazers-grab
9679c6bf3c2038e0fe56c75667e97e30333ae309
lua/starfall2/libs_sh/builtins.lua
lua/starfall2/libs_sh/builtins.lua
------------------------------------------------------------------------------- -- Builtins.lua -- Functions built-in to the default environment ------------------------------------------------------------------------------- local function createRefMtbl(target) local tbl = {} tbl.__index = function(self,k) if k:sub(1,2) ~= "__" then return target[k] end end tbl.__newindex = function() end SF.Typedef("Module", tbl) return tbl end local dgetmeta = debug.getmetatable --- Built in values. These don't need to be loaded; they are in the default environment. -- @name builtin -- @shared -- @class library -- @libtbl SF.DefaultEnvironment -- ------------------------- Lua Ports ------------------------- -- -- This part is messy because of LuaDoc stuff. --- Same as the Gmod vector type -- @name SF.DefaultEnvironment.Vector -- @class function -- @param x -- @param y -- @param z SF.DefaultEnvironment.Vector = Vector --- Same as the Gmod angle type -- @name SF.DefaultEnvironment.Angle -- @class function -- @param p Pitch -- @param y Yaw -- @param r Roll SF.DefaultEnvironment.Angle = Angle --- Same as the Gmod VMatrix type -- @name SF.DefaultEnvironment.VMatrix -- @class function SF.DefaultEnvironment.Matrix = Matrix --- Same as Lua's tostring -- @name SF.DefaultEnvironment.tostring -- @class function -- @param obj SF.DefaultEnvironment.tostring = tostring --- Same as Lua's tonumber -- @name SF.DefaultEnvironment.tonumber -- @class function -- @param obj SF.DefaultEnvironment.tonumber = tonumber --- Same as Lua's ipairs -- @name SF.DefaultEnvironment.ipairs -- @class function -- @param tbl SF.DefaultEnvironment.ipairs = ipairs --- Same as Lua's pairs -- @name SF.DefaultEnvironment.pairs -- @class function -- @param tbl SF.DefaultEnvironment.pairs = pairs --- Same as Lua's type -- @name SF.DefaultEnvironment.type -- @class function -- @param obj SF.DefaultEnvironment.type = type --- Same as Lua's next -- @name SF.DefaultEnvironment.next -- @class function -- @param tbl SF.DefaultEnvironment.next = next --- Same as Lua's assert. TODO: lua's assert doesn't work. -- @name SF.DefaultEnvironment.assert -- @class function -- @param condition -- @param msg SF.DefaultEnvironment.assert = function(ok, msg) if not ok then error(msg or "assertion failed!",2) end end --- Same as Lua's unpack -- @name SF.DefaultEnvironment.unpack -- @class function -- @param tbl SF.DefaultEnvironment.unpack = unpack --- Same as Lua's setmetatable. Doesn't work on most internal metatables SF.DefaultEnvironment.setmetatable = function(tbl, meta) SF.CheckType(tbl,"table") SF.CheckType(meta,"table") if dgetmeta(tbl).__metatable then error("cannot change a protected metatable",2) end return setmetatable(tbl,meta) end --- Same as Lua's getmetatable. Doesn't work on most internal metatables SF.DefaultEnvironment.getmetatable = function(tbl) SF.CheckType(tbl,"table") return getmetatable(tbl) end --- Throws an error. Can't change the level yet. SF.DefaultEnvironment.error = function(msg) error(msg,2) end SF.DefaultEnvironment.CLIENT = CLIENT SF.DefaultEnvironment.SERVER = SERVER --- Gets the amount of ops used so far function SF.DefaultEnvironment.opsUsed() return SF.instance.ops end --- Gets the ops hard quota function SF.DefaultEnvironment.opsMax() return SF.instance.context.ops end -- The below modules have the Gmod functions removed (the ones that begin with a capital letter), -- as requested by Divran -- Filters Gmod Lua files based on Garry's naming convention. local function filterGmodLua(lib) local original, gm = {}, {} for name, func in pairs(lib) do if name:match("^[A-Z]") then gm[name] = func else original[name] = func end end return original, gm end -- String library local str_orig, _ = filterGmodLua(string) --- Lua's (not glua's) string library -- @name SF.DefaultEnvironment.string -- @class table SF.DefaultEnvironment.string = setmetatable({},createRefMtbl(str_orig)) -- Math library local math_orig, _ = filterGmodLua(math) math_orig.clamp = math.Clamp math_orig.round = math.Round math_orig.randfloat = math.Rand math_orig.calcBSplineN = nil --- Lua's (not glua's) math library, plus clamp, round, and randfloat -- @name SF.DefaultEnvironment.math -- @class table SF.DefaultEnvironment.math = setmetatable({},createRefMtbl(math_orig)) local table_orig, _ = filterGmodLua(table) --- Lua's (not glua's) table library -- @name SF.DefaultEnvironment.table -- @class table SF.DefaultEnvironment.table = setmetatable({},createRefMtbl(table_orig)) -- ------------------------- Functions ------------------------- -- --- Loads a library. function SF.DefaultEnvironment.loadLibrary(name) SF.CheckType(name,"string") local instance = SF.instance if instance.context.libs[name] then return setmetatable({},instance.context.libs[name]) else return SF.Libraries.Get(name) end end --- Sets a hook function function SF.DefaultEnvironment.setHook(name, func) SF.CheckType(name,"string") if func then SF.CheckType(func,"function") end local inst = SF.instance inst.hooks[name:lower()] = func or nil end if SERVER then --- Prints a message to the player's chat. Limited to 255 characters on the server. function SF.DefaultEnvironment.print(s) SF.instance.player:PrintMessage(HUD_PRINTTALK, tostring(s):sub(1,255)) end else function SF.DefaultEnvironment.print(s) LocalPlayer():PrintMessage(HUD_PRINTTALK, tostring(s)) end end -- ------------------------- Restrictions ------------------------- -- -- Restricts access to builtin type's metatables local function createSafeIndexFunc(mt) local old_index = mt.__index local new_index if type(old_index) == "function" then function new_index(self, k) return k:sub(1,2) ~= "__" and old_index(self,k) or nil end else function new_index(self,k) return k:sub(1,2) ~= "__" and old_index[k] or nil end end local function protect() old_index = mt.__index mt.__index = new_index end local function unprotect() mt.__index = old_index end return protect, unprotect end local vector_restrict, vector_unrestrict = createSafeIndexFunc(_R.Vector) local angle_restrict, angle_unrestrict = createSafeIndexFunc(_R.Angle) local matrix_restrict, matrix_unrestrict = createSafeIndexFunc(_R.VMatrix) local function restrict(instance, hook) vector_restrict() angle_restrict() matrix_restrict() end local function unrestrict(instance, hook) vector_unrestrict() angle_unrestrict() matrix_unrestrict() end SF.Libraries.AddHook("prepare", restrict) SF.Libraries.AddHook("cleanup", unrestrict)
------------------------------------------------------------------------------- -- Builtins.lua -- Functions built-in to the default environment ------------------------------------------------------------------------------- local dgetmeta = debug.getmetatable --- Built in values. These don't need to be loaded; they are in the default environment. -- @name builtin -- @shared -- @class library -- @libtbl SF.DefaultEnvironment -- ------------------------- Lua Ports ------------------------- -- -- This part is messy because of LuaDoc stuff. --- Same as the Gmod vector type -- @name SF.DefaultEnvironment.Vector -- @class function -- @param x -- @param y -- @param z SF.DefaultEnvironment.Vector = Vector --- Same as the Gmod angle type -- @name SF.DefaultEnvironment.Angle -- @class function -- @param p Pitch -- @param y Yaw -- @param r Roll SF.DefaultEnvironment.Angle = Angle --- Same as the Gmod VMatrix type -- @name SF.DefaultEnvironment.VMatrix -- @class function SF.DefaultEnvironment.Matrix = Matrix --- Same as Lua's tostring -- @name SF.DefaultEnvironment.tostring -- @class function -- @param obj SF.DefaultEnvironment.tostring = tostring --- Same as Lua's tonumber -- @name SF.DefaultEnvironment.tonumber -- @class function -- @param obj SF.DefaultEnvironment.tonumber = tonumber --- Same as Lua's ipairs -- @name SF.DefaultEnvironment.ipairs -- @class function -- @param tbl SF.DefaultEnvironment.ipairs = ipairs --- Same as Lua's pairs -- @name SF.DefaultEnvironment.pairs -- @class function -- @param tbl SF.DefaultEnvironment.pairs = pairs --- Same as Lua's type -- @name SF.DefaultEnvironment.type -- @class function -- @param obj SF.DefaultEnvironment.type = type --- Same as Lua's next -- @name SF.DefaultEnvironment.next -- @class function -- @param tbl SF.DefaultEnvironment.next = next --- Same as Lua's assert. TODO: lua's assert doesn't work. -- @name SF.DefaultEnvironment.assert -- @class function -- @param condition -- @param msg SF.DefaultEnvironment.assert = function(ok, msg) if not ok then error(msg or "assertion failed!",2) end end --- Same as Lua's unpack -- @name SF.DefaultEnvironment.unpack -- @class function -- @param tbl SF.DefaultEnvironment.unpack = unpack --- Same as Lua's setmetatable. Doesn't work on most internal metatables SF.DefaultEnvironment.setmetatable = function(tbl, meta) SF.CheckType(tbl,"table") SF.CheckType(meta,"table") if dgetmeta(tbl).__metatable then error("cannot change a protected metatable",2) end return setmetatable(tbl,meta) end --- Same as Lua's getmetatable. Doesn't work on most internal metatables SF.DefaultEnvironment.getmetatable = function(tbl) SF.CheckType(tbl,"table") return getmetatable(tbl) end --- Throws an error. Can't change the level yet. SF.DefaultEnvironment.error = function(msg) error(msg,2) end SF.DefaultEnvironment.CLIENT = CLIENT SF.DefaultEnvironment.SERVER = SERVER --- Gets the amount of ops used so far function SF.DefaultEnvironment.opsUsed() return SF.instance.ops end --- Gets the ops hard quota function SF.DefaultEnvironment.opsMax() return SF.instance.context.ops end -- The below modules have the Gmod functions removed (the ones that begin with a capital letter), -- as requested by Divran -- Filters Gmod Lua files based on Garry's naming convention. local function filterGmodLua(lib, original, gm) original = original or {} gm = gm or {} for name, func in pairs(lib) do if name:match("^[A-Z]") then gm[name] = func else original[name] = func end end return original, gm end -- String library local string_methods, string_metatable = SF.Typedef("Library: string") filterGmodLua(string,string_methods) string_metatable.__newindex = function() end --- Lua's (not glua's) string library -- @name SF.DefaultEnvironment.string -- @class table SF.DefaultEnvironment.string = setmetatable({},string_metatable) -- Math library local math_methods, math_metatable = SF.Typedef("Library: math") filterGmodLua(math,math_methods) math_metatable.__newindex = function() end math_methods.clamp = math.Clamp math_methods.round = math.Round math_methods.randfloat = math.Rand math_methods.calcBSplineN = nil --- Lua's (not glua's) math library, plus clamp, round, and randfloat -- @name SF.DefaultEnvironment.math -- @class table SF.DefaultEnvironment.math = setmetatable({},math_metatable) local table_methods, table_metatable = SF.Typedef("Library: table") filterGmodLua(string,table_methods) table_metatable.__newindex = function() end --- Lua's (not glua's) table library -- @name SF.DefaultEnvironment.table -- @class table SF.DefaultEnvironment.table = setmetatable({},table_metatable) -- ------------------------- Functions ------------------------- -- --- Loads a library. function SF.DefaultEnvironment.loadLibrary(name) SF.CheckType(name,"string") local instance = SF.instance if instance.context.libs[name] then return setmetatable({},instance.context.libs[name]) else return SF.Libraries.Get(name) end end --- Sets a hook function function SF.DefaultEnvironment.setHook(name, func) SF.CheckType(name,"string") if func then SF.CheckType(func,"function") end local inst = SF.instance inst.hooks[name:lower()] = func or nil end if SERVER then --- Prints a message to the player's chat. Limited to 255 characters on the server. function SF.DefaultEnvironment.print(s) SF.instance.player:PrintMessage(HUD_PRINTTALK, tostring(s):sub(1,255)) end else function SF.DefaultEnvironment.print(s) LocalPlayer():PrintMessage(HUD_PRINTTALK, tostring(s)) end end -- ------------------------- Restrictions ------------------------- -- -- Restricts access to builtin type's metatables local function createSafeIndexFunc(mt) local old_index = mt.__index local new_index if type(old_index) == "function" then function new_index(self, k) return k:sub(1,2) ~= "__" and old_index(self,k) or nil end else function new_index(self,k) return k:sub(1,2) ~= "__" and old_index[k] or nil end end local function protect() old_index = mt.__index mt.__index = new_index end local function unprotect() mt.__index = old_index end return protect, unprotect end local vector_restrict, vector_unrestrict = createSafeIndexFunc(_R.Vector) local angle_restrict, angle_unrestrict = createSafeIndexFunc(_R.Angle) local matrix_restrict, matrix_unrestrict = createSafeIndexFunc(_R.VMatrix) local function restrict(instance, hook) vector_restrict() angle_restrict() matrix_restrict() end local function unrestrict(instance, hook) vector_unrestrict() angle_unrestrict() matrix_unrestrict() end SF.Libraries.AddHook("prepare", restrict) SF.Libraries.AddHook("cleanup", unrestrict)
Fixed builtins using the old Typedef
Fixed builtins using the old Typedef
Lua
bsd-3-clause
Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall
3b1799c5036ac64046127135f3524e83ecf2cea9
test_scripts/Polices/Policy_Table_Update/020_ATF_P_TC_PoliciesManager_changes_status_UPDATING.lua
test_scripts/Polices/Policy_Table_Update/020_ATF_P_TC_PoliciesManager_changes_status_UPDATING.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UPDATING” -- [HMI API] OnStatusUpdate -- -- Description: -- PoliciesManager must change the status to “UPDATING” and notify HMI with -- OnStatusUpdate("UPDATING") right after SnapshotPT is sent out to to mobile -- app via OnSystemRequest() RPC. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. Device is not consented -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) -- 2. Performed steps -- -- Expected result: -- SDL->HMI: SDL.OnStatusUpdate(UPDATING) right after SDL->app: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_status_UPDATING() local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") local is_test_fail = false local endpoints = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil} end if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "app1") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID} end end local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", appID = config.application1.registerAppInterfaceParams.appID}, "files/ptu.json") EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}) EXPECT_HMICALL("BasicCommunication.SystemRequest",{ requestType = "PROPRIETARY", fileName = SystemFilesPath.."/PolicyTableUpdate" }) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) --self.hmiConnection:SendNotification ("SDL.OnReceivedPolicyUpdate", { policyfile = SystemFilesPath.."/PolicyTableUpdate"}) end) EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) end) end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UPDATING” -- [HMI API] OnStatusUpdate -- -- Description: -- PoliciesManager must change the status to “UPDATING” and notify HMI with -- OnStatusUpdate("UPDATING") right after SnapshotPT is sent out to to mobile -- app via OnSystemRequest() RPC. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. Device is not consented -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) -- 2. Performed steps -- -- Expected result: -- SDL->HMI: SDL.OnStatusUpdate(UPDATING) right after SDL->app: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_status_UPDATING() local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS" } } ) :Do(function() self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function() local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", appID = config.application1.registerAppInterfaceParams.appID}, "files/ptu.json") EXPECT_HMICALL("BasicCommunication.SystemRequest",{ requestType = "PROPRIETARY", fileName = SystemFilesPath.."/PolicyTableUpdate" }) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) end) EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) end) end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
Fix issues in script
Fix issues in script
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
bf7c36f3b54347a888f9036f1cad51cea4224d16
script/c80400029.lua
script/c80400029.lua
--サイバー・ネットワーク function c80400029.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c80400029.ncon) e1:SetTarget(c80400029.ntg) c:RegisterEffect(e1) --Activate2 local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_ACTIVATE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,TIMING_END_PHASE) e2:SetCondition(c80400029.condition) e2:SetTarget(c80400029.target1) e2:SetOperation(c80400029.operation) c:RegisterEffect(e2) --remove local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(80400029,1)) e3:SetCategory(CATEGORY_REMOVE) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetRange(LOCATION_SZONE) e3:SetCode(EVENT_FREE_CHAIN) e3:SetHintTiming(0,TIMING_END_PHASE) e3:SetCondition(c80400029.condition) e3:SetTarget(c80400029.target2) e3:SetOperation(c80400029.operation) e3:SetLabel(1) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(80400029,2)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e4:SetCode(EVENT_TO_GRAVE) e4:SetCondition(c80400029.spcon) e4:SetCost(c80400029.spcost) e4:SetTarget(c80400029.sptg) e4:SetOperation(c80400029.spop) c:RegisterEffect(e4) end function c80400029.cfilter(c) return c:IsSetCard(0x103c) end function c80400029.ncon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetMatchingGroupCount(c80400029.cfilter,tp,LOCATION_MZONE,0,nil)==0 end function c80400029.ntg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local c=e:GetHandler() c:SetTurnCounter(0) --destroy local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetCountLimit(1) e1:SetRange(LOCATION_SZONE) e1:SetOperation(c80400029.desop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3) c:RegisterEffect(e1) end function c80400029.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c80400029.cfilter,tp,LOCATION_MZONE,0,1,nil) end function c80400029.dfilter(c) return c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToRemove() end function c80400029.target1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end if Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(80400029,0)) then e:SetCategory(CATEGORY_REMOVE) e:SetLabel(1) e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) else e:SetCategory(0) e:SetLabel(0) end e:GetHandler():SetTurnCounter(0) --destroy local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetCountLimit(1) e1:SetRange(LOCATION_SZONE) e1:SetOperation(c80400029.desop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3) e:GetHandler():RegisterEffect(e1) end function c80400029.desop(e,tp,eg,ep,ev,re,r,rp) if tp~=Duel.GetTurnPlayer() then return end local c=e:GetHandler() local ct=c:GetTurnCounter() ct=ct+1 c:SetTurnCounter(ct) if ct==3 then Duel.Destroy(c,REASON_EFFECT) end end function c80400029.target2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(80400029)==0 and Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK) e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end function c80400029.operation(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end if e:GetLabel()==0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c80400029.dfilter,tp,LOCATION_DECK,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.Remove(tc,POS_FACEUP,REASON_EFFECT) end end function c80400029.filter(c,e,tp) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c80400029.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c80400029.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not (Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()>PHASE_MAIN1 and Duel.GetCurrentPhase()<PHASE_END) end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c80400029.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c80400029.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED) end function c80400029.dgfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable() end function c80400029.spop(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsPlayerCanSpecialSummonMonster(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) then return end local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft1<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) if g:GetCount()>0 then local tc=g:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) --cannot trigger local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_TRIGGER) e1:SetRange(LOCATION_MZONE) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) tc=g:GetNext() end Duel.SpecialSummonComplete() Duel.BreakEffect() local dg=Duel.GetMatchingGroup(c80400029.dgfilter,tp,LOCATION_ONFIELD,0,nil) if dg:GetCount()>0 then Duel.Destroy(dg,REASON_EFFECT) end end end
--サイバー・ネットワーク function c80400029.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c80400029.ncon) e1:SetTarget(c80400029.ntg) c:RegisterEffect(e1) --Activate2 local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_ACTIVATE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,TIMING_END_PHASE) e2:SetCondition(c80400029.condition) e2:SetTarget(c80400029.target1) e2:SetOperation(c80400029.operation) c:RegisterEffect(e2) --remove local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(80400029,1)) e3:SetCategory(CATEGORY_REMOVE) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetRange(LOCATION_SZONE) e3:SetCode(EVENT_FREE_CHAIN) e3:SetHintTiming(0,TIMING_END_PHASE) e3:SetCondition(c80400029.condition) e3:SetTarget(c80400029.target2) e3:SetOperation(c80400029.operation) e3:SetLabel(1) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(80400029,2)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e4:SetCode(EVENT_TO_GRAVE) e4:SetCondition(c80400029.spcon) e4:SetCost(c80400029.spcost) e4:SetTarget(c80400029.sptg) e4:SetOperation(c80400029.spop) c:RegisterEffect(e4) end function c80400029.cfilter(c) return c:IsCode(70095154) end function c80400029.ncon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetMatchingGroupCount(c80400029.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)==0 end function c80400029.ntg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local c=e:GetHandler() c:SetTurnCounter(0) --destroy local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetCountLimit(1) e1:SetRange(LOCATION_SZONE) e1:SetOperation(c80400029.desop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3) c:RegisterEffect(e1) end function c80400029.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c80400029.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end function c80400029.dfilter(c) return c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToRemove() end function c80400029.target1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end if Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(80400029,0)) then e:SetCategory(CATEGORY_REMOVE) e:SetLabel(1) e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) else e:SetCategory(0) e:SetLabel(0) end e:GetHandler():SetTurnCounter(0) --destroy local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetCountLimit(1) e1:SetRange(LOCATION_SZONE) e1:SetOperation(c80400029.desop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,3) e:GetHandler():RegisterEffect(e1) end function c80400029.desop(e,tp,eg,ep,ev,re,r,rp) if tp~=Duel.GetTurnPlayer() then return end local c=e:GetHandler() local ct=c:GetTurnCounter() ct=ct+1 c:SetTurnCounter(ct) if ct==3 then Duel.Destroy(c,REASON_EFFECT) end end function c80400029.target2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(80400029)==0 and Duel.IsExistingMatchingCard(c80400029.dfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK) e:GetHandler():RegisterFlagEffect(80400029,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end function c80400029.operation(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end if e:GetLabel()==0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c80400029.dfilter,tp,LOCATION_DECK,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.Remove(tc,POS_FACEUP,REASON_EFFECT) end end function c80400029.filter(c,e,tp) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c80400029.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c80400029.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not (Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()>PHASE_MAIN1 and Duel.GetCurrentPhase()<PHASE_END) end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c80400029.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c80400029.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED) end function c80400029.dgfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable() end function c80400029.spop(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsPlayerCanSpecialSummonMonster(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) then return end local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft1<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c80400029.filter,tp,LOCATION_REMOVED,0,ft1,ft1,nil,e,tp) if g:GetCount()>0 then local tc=g:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) --cannot trigger local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_TRIGGER) e1:SetRange(LOCATION_MZONE) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) tc=g:GetNext() end Duel.SpecialSummonComplete() Duel.BreakEffect() local dg=Duel.GetMatchingGroup(c80400029.dgfilter,tp,LOCATION_ONFIELD,0,nil) if dg:GetCount()>0 then Duel.Destroy(dg,REASON_EFFECT) end end end
Cyber Network fix
Cyber Network fix
Lua
mit
sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher
2011596de04ebc9a67a861420d16a9f027339847
service/clusterd.lua
service/clusterd.lua
local skynet = require "skynet" require "skynet.manager" local sc = require "skynet.socketchannel" local socket = require "skynet.socket" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_session = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local function read_response(sock) local sz = socket.header(sock:read(2)) local msg = sock:read(sz) return cluster.unpackresponse(msg) -- session, ok, data, padding end local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice "clustersender" if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name if proxy[fullname] == nil then proxy[fullname] = skynet.newservice("clusterproxy", node, name) end skynet.ret(skynet.pack(proxy[fullname])) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
local skynet = require "skynet" require "skynet.manager" local sc = require "skynet.socketchannel" local socket = require "skynet.socket" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_session = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local function read_response(sock) local sz = socket.header(sock:read(2)) local msg = sock:read(sz) return cluster.unpackresponse(msg) -- session, ok, data, padding end local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice "clustersender" if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
fix #979
fix #979
Lua
mit
JiessieDawn/skynet,bigrpg/skynet,xcjmine/skynet,icetoggle/skynet,ag6ag/skynet,hongling0/skynet,korialuo/skynet,pigparadise/skynet,JiessieDawn/skynet,bigrpg/skynet,cloudwu/skynet,hongling0/skynet,wangyi0226/skynet,cloudwu/skynet,wangyi0226/skynet,icetoggle/skynet,ag6ag/skynet,wangyi0226/skynet,jxlczjp77/skynet,xcjmine/skynet,JiessieDawn/skynet,sanikoyes/skynet,cloudwu/skynet,icetoggle/skynet,pigparadise/skynet,jxlczjp77/skynet,korialuo/skynet,xjdrew/skynet,xcjmine/skynet,korialuo/skynet,sanikoyes/skynet,pigparadise/skynet,xjdrew/skynet,xjdrew/skynet,hongling0/skynet,sanikoyes/skynet,bigrpg/skynet,ag6ag/skynet,jxlczjp77/skynet
69acc8e8df10ed945392a31182d074b593d09386
extension/client/serverFactory.lua
extension/client/serverFactory.lua
local proto = require 'protocol' local select = require 'select' local function create(t) local m = {} local session local srvfd local write = '' local stat = {} function t.event(_, fd) session = fd select.send(session, write) write = '' if not t.client then select.close(srvfd) end end if t.client then srvfd = assert(select.connect(t)) else srvfd = assert(select.listen(t)) end function m.debug(v) stat.debug = v end function m.send(pkg) if not session then write = write .. proto.send(pkg, stat) return end select.send(session, proto.send(pkg, stat)) end function m.recv() if not session then return end return proto.recv(select.recv(session), stat) end return m end return create
local proto = require 'protocol' local select = require 'select' local function create(t) local m = {} local session local srvfd local write = '' local stat = {} function t.event(status, fd) if status == 'failed' then assert(t.client) select.close(srvfd) srvfd = assert(select.connect(t)) return end session = fd select.send(session, write) write = '' if not t.client then select.close(srvfd) end end if t.client then srvfd = assert(select.connect(t)) else srvfd = assert(select.listen(t)) end function m.debug(v) stat.debug = v end function m.send(pkg) if not session then write = write .. proto.send(pkg, stat) return end select.send(session, proto.send(pkg, stat)) end function m.recv() if not session then return end return proto.recv(select.recv(session), stat) end return m end return create
Fixes #42
Fixes #42
Lua
mit
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
52a9ff6f726b42bc35d165e2639ed76446fe3c2d
lua/packer.lua
lua/packer.lua
--The packerryption function is someway useless, however you may feel better by comparing to plain text :) local string=string local packer={} local function rechar(str,offset) local byte=string.byte(str) return string.char(byte+offset<128 and byte+offset or byte) end function packer.pack(func) local str=string.dump(func) local obj={} for i=1,#str,2 do obj[#obj+1]=rechar(str:sub(i,i),1) end for i=2,#str,2 do obj[#obj+1]=rechar(str:sub(i,i),1) end return "FUNC:"..table.concat(obj,"") end function packer.unpack(str) if not str or str:sub(1,5)~= "FUNC:" then return end str=str:sub(6) local ind=#str local half,start=math.floor(ind/2),math.ceil(ind/2) local obj={} for i=1,half,1 do obj[#obj+1]=rechar(str:sub(i,i),-1) obj[#obj+1]=rechar(str:sub(i+start,i+start),-1) end if half~=start then obj[#obj+1]=rechar(str:sub(start,start),-1) end str=loadstring(table.concat(obj,"")) return str end function packer.pack_str(str) local func=loadstring("return function() local tmp=[["..tostring({}).."]];return [["..str.."]] end")() return packer.pack(func) end function packer.unpack_str(str) return str and packer.unpack(str) and packer.unpack(str)() or str end return packer
--The packerryption function is someway useless, however you may feel better by comparing to plain text :) local string=string local packer={} local function rechar(str,offset) local byte=string.byte(str) return string.char(byte+offset<128 and byte+offset or byte) end function packer.pack(func) local str=string.dump(func) local obj={} for i=1,#str,2 do obj[#obj+1]=rechar(str:sub(i,i),1) end for i=2,#str,2 do obj[#obj+1]=rechar(str:sub(i,i),1) end return "FUNC:"..table.concat(obj,"") end function packer.unpack(str) if not str or str:sub(1,5)~= "FUNC:" then return str end str=str:sub(6) local ind=#str local half,start=math.floor(ind/2),math.ceil(ind/2) local obj={} for i=1,half,1 do obj[#obj+1]=rechar(str:sub(i,i),-1) obj[#obj+1]=rechar(str:sub(i+start,i+start),-1) end if half~=start then obj[#obj+1]=rechar(str:sub(start,start),-1) end str=loadstring(table.concat(obj,"")) return str end function packer.pack_str(str) local func=loadstring("return function() local tmp=[["..tostring({}).."]];return [["..str.."]] end")() return packer.pack(func) end function packer.unpack_str(str) while true do str=packer.unpack(str) if type(str)=="function" then str=str() end if not str or tostring(str):sub(1,5)~= "FUNC:" then break end end return str end return packer
fix sqlplus unavailable in some cases
fix sqlplus unavailable in some cases
Lua
mit
hyee/dbcli,hyee/dbcli,hyee/dbcli,hyee/dbcli
271eebb79585b1f20d0243f392e0c59d067df1e0
twokeys.lua
twokeys.lua
local key_tmr=3 local key_int=50 local key1_len=0 local key2_len=0 status.mode=0 status.uptime_ms=0 gpio.mode(key1_pin,gpio.INPUT,gpio.PULLUP) gpio.mode(key2_pin,gpio.INPUT,gpio.PULLDOWN) local wifi_max_outage=10000 local wifi_check_int=1000 local wifi_outage=0 local owtemp_int = 5000 ldr_pin=5 -- GPIO14 local ldr_t0=0 local ldr_int = 2000 status.wifi_reconns = 0 tmr.alarm(key_tmr, key_int, 1, function() status.uptime_ms=status.uptime_ms+key_int -- MODE Key if gpio.read(key1_pin) == key1_on then key1_len = key1_len + key_int else if key1_len >= 50 and key1_len < 300 then beep(523) -- c modeset(1) elseif key1_len >= 300 and key1_len < 1000 then beep(261) -- C modeset(-1) -- elseif key1_len >= 1000 and key1_len < 3000 then -- play(250,20,"G elseif key1_len >= 3000 then beep(349,500) -- F node.restart() end key1_len=0 end -- SELECT Key if gpio.read(key2_pin) == key2_on then key2_len = key2_len + key_int else if key2_len >= 50 and key2_len < 300 then beep(659) -- e modekey(1) elseif key2_len >= 300 and key2_len < 1000 then beep(329) -- E modekey(-1) elseif key2_len >= 1000 and key2_len < 3000 then beep(391) -- G modekey(0) -- elseif key2_len >= 3000 then -- b end key2_len=0 end --- Wifi Check (should one time use callback registry and go into into own file - but new files complicate the upgrade process) if status.uptime_ms % wifi_check_int == 0 then if(wifi.sta.getip()==nil) then wifi_outage = wifi_outage + wifi_check_int if wifi_outage >= wifi_max_outage then status.wifi_reconns = status.wifi_reconns + 1 dofile("wifiautoconnect.lc") wifi_outage = 0 end else wifi_outage = 0 end end if status.uptime_ms % owtemp_int == 0 then if status.mode == 0 then status.temp = dofile("owtemp.lc") else status.temp = nil end end if status.uptime_ms % ldr_int == 0 then if ldr_t0 > 0 then status.ldr=-1 end gpio.trig(ldr_pin,"none") gpio.mode(ldr_pin,gpio.OUTPUT) gpio.write(ldr_pin,gpio.LOW) end if status.uptime_ms % ldr_int == ldr_int/10 then gpio.mode(ldr_pin,gpio.INPUT,gpio.FLOAT) ldr_t0=tmr.now() gpio.trig(ldr_pin,"high",function(level) status.ldr=tmr.now()-ldr_t0 ldr_t0=0 gpio.trig(ldr_pin,"none") end) end end)
local key_tmr=3 local key_int=50 local key1_len=0 local key2_len=0 status.mode=0 status.uptime_ms=0 gpio.mode(key1_pin,gpio.INPUT,gpio.PULLUP) gpio.mode(key2_pin,gpio.INPUT,gpio.PULLDOWN) local wifi_max_outage=10000 local wifi_check_int=1000 local wifi_outage=0 local owtemp_int = 5000 ldr_pin=5 -- GPIO14 local ldr_t0=0 local ldr_int = 2000 local ldr_max = ldr_int * 1000 status.wifi_reconns = 0 tmr.alarm(key_tmr, key_int, 1, function() status.uptime_ms=status.uptime_ms+key_int -- MODE Key if gpio.read(key1_pin) == key1_on then key1_len = key1_len + key_int else if key1_len >= 50 and key1_len < 300 then beep(523) -- c modeset(1) elseif key1_len >= 300 and key1_len < 1000 then beep(261) -- C modeset(-1) -- elseif key1_len >= 1000 and key1_len < 3000 then -- play(250,20,"G elseif key1_len >= 3000 then beep(349,500) -- F node.restart() end key1_len=0 end -- SELECT Key if gpio.read(key2_pin) == key2_on then key2_len = key2_len + key_int else if key2_len >= 50 and key2_len < 300 then beep(659) -- e modekey(1) elseif key2_len >= 300 and key2_len < 1000 then beep(329) -- E modekey(-1) elseif key2_len >= 1000 and key2_len < 3000 then beep(391) -- G modekey(0) -- elseif key2_len >= 3000 then -- b end key2_len=0 end --- Wifi Check (should one time use callback registry and go into into own file - but new files complicate the upgrade process) if status.uptime_ms % wifi_check_int == 0 then if(wifi.sta.getip()==nil) then wifi_outage = wifi_outage + wifi_check_int if wifi_outage >= wifi_max_outage then status.wifi_reconns = status.wifi_reconns + 1 dofile("wifiautoconnect.lc") wifi_outage = 0 end else wifi_outage = 0 end end if status.uptime_ms % owtemp_int == 0 then if status.mode == 0 then status.temp = dofile("owtemp.lc") else status.temp = nil end end if status.uptime_ms % ldr_int == 0 then if ldr_t0 > 0 then status.ldr=ldr_max end gpio.trig(ldr_pin,"none") gpio.mode(ldr_pin,gpio.OUTPUT) gpio.write(ldr_pin,gpio.LOW) end if status.uptime_ms % ldr_int == ldr_int/10 then gpio.mode(ldr_pin,gpio.INPUT,gpio.FLOAT) ldr_t0=tmr.now() gpio.trig(ldr_pin,"high",function(level) status.ldr=tmr.now()-ldr_t0 ldr_t0=0 gpio.trig(ldr_pin,"none") end) end end)
Fixed LDR max value
Fixed LDR max value
Lua
mit
matgoebl/nodemcu-wifimusicledclock,matgoebl/nodemcu-wifimusicledclock
28896329dd53c27aaf6fb1f76fa7bc49b4d5408b
roles/dotfiles/files/.hammerspoon/eventtap.lua
roles/dotfiles/files/.hammerspoon/eventtap.lua
-- -- Trying to limp along without Karabiner in Sierra. -- local deepEquals = require 'deepEquals' local log = require 'log' -- Forward function declarations. local cancelTimers = nil local modifierHandler = nil local keyHandler = nil local keyDown = hs.eventtap.event.types.keyDown local keyUp = hs.eventtap.event.types.keyUp local keyCodes = { control = 59, -- TODO that's leftControl; figure out rightControl leftShift = 56, rightShift = 60, } local controlDown = {ctrl = true} local controlUp = {} local controlPressed = nil local shiftDown = {shift = true} local repeatDelay = hs.eventtap.keyRepeatDelay() local repeatInterval = hs.eventtap.keyRepeatInterval() local controlTimer = nil local controlRepeatTimer = nil cancelTimers = (function() if controlTimer ~= nil then controlTimer:stop() controlTimer = nil end if controlRepeatTimer ~= nil then controlRepeatTimer:stop() controlRepeatTimer = nil end end) modifierHandler = (function(evt) local flags=evt:getFlags() local keyCode = evt:getKeyCode() -- Going to fire a fake delete key-press so that we can handle this in the -- keyHandler function along with return. if keyCode == keyCodes.control then -- We only start timers when Control is pressed alone, but we clean them up -- unconditionally when it is released, so as not to leak. if flags['ctrl'] == nil and controlPressed == true then controlPressed = false hs.eventtap.event.newKeyEvent({}, 'delete', false):post() cancelTimers() elseif deepEquals(flags, controlDown) then controlPressed = true hs.eventtap.event.newKeyEvent({}, 'delete', true):post() -- We don't get repeat events for modifiers. Have to fake them. cancelTimers() controlTimer = hs.timer.doAfter( repeatDelay, (function() if controlPressed then controlRepeatTimer = hs.timer.doUntil( (function() return controlPressed == false end), (function() hs.eventtap.event.newKeyEvent({}, 'delete', true):post() end), repeatInterval ) end end) ) end elseif keyCode == keyCodes.leftShift or keyCode == keyCodes.rightShift then if deepEquals(flags, shiftDown) then if false then -- TODO: something like the following, which seems unlikely to work -- given what the internets say (requires custom keyboard driver). hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', true):post() hs.timer.doAfter( .5, (function() hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', false):post() end) ) end else -- TODO: other modifiers pressed, reset state. end end end) local repeatThreshold = .5 local syntheticEvent = 94025 -- magic number chosen "at random" local eventSourceUserData = hs.eventtap.event.properties['eventSourceUserData'] local keyboardEventKeyboardType = hs.eventtap.event.properties['keyboardEventKeyboardType'] local internalKeyboardType = 43 local externalKeyboardType = 40 -- YubiKey as well... local stopPropagation = true -- These are keys that do one thing when tapped but act like modifiers when -- chorded. local conditionalKeys = { delete = { tapped = 'delete', chorded = 'ctrl', downAt = nil, isChording = false, -- Caps Lock is mapped to control, so during chording, keyDown events should -- have these flags. expectedFlags = {ctrl = true}, }, } -- "return" is a reserved word, so have to use longhand: conditionalKeys['return'] = { tapped = 'return', chorded = 'ctrl', downAt = nil, isChording = false, expectedFlags = {}, } keyHandler = (function(evt) local userData = evt:getProperty(eventSourceUserData) if userData == syntheticEvent then return end local eventType = evt:getType() local keyboardType = evt:getProperty(keyboardEventKeyboardType) local keyCode = evt:getKeyCode() local flags = evt:getFlags() local when = hs.timer.secondsSinceEpoch() if eventType == keyDown then if keyCode == hs.keycodes.map['i'] then if deepEquals(flags, {ctrl = true}) then local frontmost = hs.application.frontmostApplication():bundleID() if frontmost == 'com.googlecode.iterm2' or frontmost == 'org.vim.MacVim' then hs.eventtap.event.newKeyEvent({}, 'f6', true):setProperty(eventSourceUserData, syntheticEvent):post() return stopPropagation end end end -- Check for conditional keys. -- Along the way, note which conditional key(s) are already down. local activeConditionals = {} for keyName, config in pairs(conditionalKeys) do if keyCode == hs.keycodes.map[keyName] then if not deepEquals(flags, {}) or (config.downAt and when - config.downAt > repeatThreshold) then if not config.isChording then local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() end elseif not config.downAt then config.downAt = when end return stopPropagation elseif config.downAt then activeConditionals[keyName] = config end end -- Potentially begin chording against the active conditionals. for keyName, config in pairs(activeConditionals) do if config.isChording or when - config.downAt < repeatThreshold then if deepEquals(flags, config.expectedFlags) then config.isChording = true local synthetic = evt:copy() local syntheticFlags = {} syntheticFlags[config.chorded] = true synthetic:setFlags(syntheticFlags) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() return stopPropagation end end end elseif eventType == keyUp then for keyName, config in pairs(conditionalKeys) do if keyCode == hs.keycodes.map[keyName] then if config.isChording then config.isChording = false else local downAt = config.downAt config.downAt = nil if deepEquals(flags, {}) and when - downAt <= repeatThreshold then local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() end end return stopPropagation end end end end) return { init = (function() local modifierTap = hs.eventtap.new( {hs.eventtap.event.types.flagsChanged}, modifierHandler ) modifierTap:start() local keyTap = hs.eventtap.new({keyDown, keyUp}, keyHandler) keyTap:start() end) }
-- -- Trying to limp along without Karabiner in Sierra. -- local deepEquals = require 'deepEquals' local log = require 'log' -- Forward function declarations. local cancelTimers = nil local modifierHandler = nil local keyHandler = nil local keyDown = hs.eventtap.event.types.keyDown local keyUp = hs.eventtap.event.types.keyUp local keyCodes = { control = 59, -- TODO that's leftControl; figure out rightControl leftShift = 56, rightShift = 60, } local controlDown = {ctrl = true} local controlUp = {} local controlPressed = nil local shiftDown = {shift = true} local repeatDelay = hs.eventtap.keyRepeatDelay() local repeatInterval = hs.eventtap.keyRepeatInterval() local controlTimer = nil local controlRepeatTimer = nil cancelTimers = (function() if controlTimer ~= nil then controlTimer:stop() controlTimer = nil end if controlRepeatTimer ~= nil then controlRepeatTimer:stop() controlRepeatTimer = nil end end) modifierHandler = (function(evt) local flags=evt:getFlags() local keyCode = evt:getKeyCode() -- Going to fire a fake delete key-press so that we can handle this in the -- keyHandler function along with return. if keyCode == keyCodes.control then -- We only start timers when Control is pressed alone, but we clean them up -- unconditionally when it is released, so as not to leak. if flags['ctrl'] == nil and controlPressed == true then controlPressed = false hs.eventtap.event.newKeyEvent({}, 'delete', false):post() cancelTimers() elseif deepEquals(flags, controlDown) then controlPressed = true hs.eventtap.event.newKeyEvent({}, 'delete', true):post() -- We don't get repeat events for modifiers. Have to fake them. cancelTimers() controlTimer = hs.timer.doAfter( repeatDelay, (function() if controlPressed then controlRepeatTimer = hs.timer.doUntil( (function() return controlPressed == false end), (function() hs.eventtap.event.newKeyEvent({}, 'delete', true):post() end), repeatInterval ) end end) ) end elseif keyCode == keyCodes.leftShift or keyCode == keyCodes.rightShift then if deepEquals(flags, shiftDown) then if false then -- TODO: something like the following, which seems unlikely to work -- given what the internets say (requires custom keyboard driver). hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', true):post() hs.timer.doAfter( .5, (function() hs.eventtap.event.newSystemKeyEvent('CAPS_LOCK', false):post() end) ) end else -- TODO: other modifiers pressed, reset state. end end end) local repeatThreshold = .5 local syntheticEvent = 94025 -- magic number chosen "at random" local eventSourceUserData = hs.eventtap.event.properties['eventSourceUserData'] local keyboardEventKeyboardType = hs.eventtap.event.properties['keyboardEventKeyboardType'] local internalKeyboardType = 43 local externalKeyboardType = 40 -- YubiKey as well... local stopPropagation = true -- These are keys that do one thing when tapped but act like modifiers when -- chorded. local conditionalKeys = { delete = { tapped = 'delete', chorded = 'ctrl', downAt = nil, isChording = false, -- Caps Lock is mapped to control, so during chording, keyDown events should -- have these flags. expectedFlags = {ctrl = true}, }, } -- "return" is a reserved word, so have to use longhand: conditionalKeys['return'] = { tapped = 'return', chorded = 'ctrl', downAt = nil, isChording = false, expectedFlags = {}, } keyHandler = (function(evt) local userData = evt:getProperty(eventSourceUserData) if userData == syntheticEvent then return end local eventType = evt:getType() local keyboardType = evt:getProperty(keyboardEventKeyboardType) local keyCode = evt:getKeyCode() local flags = evt:getFlags() local when = hs.timer.secondsSinceEpoch() if eventType == keyDown then if keyCode == hs.keycodes.map['i'] then if deepEquals(flags, {ctrl = true}) then local frontmost = hs.application.frontmostApplication():bundleID() if frontmost == 'com.googlecode.iterm2' or frontmost == 'org.vim.MacVim' then hs.eventtap.event.newKeyEvent({}, 'f6', true):setProperty(eventSourceUserData, syntheticEvent):post() return stopPropagation end end end -- Check for conditional keys. -- Along the way, note which conditional key(s) are already down. local activeConditionals = {} for keyName, config in pairs(conditionalKeys) do if keyCode == hs.keycodes.map[keyName] then if not deepEquals(flags, {}) or (config.downAt and when - config.downAt > repeatThreshold) then if not config.isChording then local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() end elseif not config.downAt then config.downAt = when end return stopPropagation elseif config.downAt then activeConditionals[keyName] = config end end -- Potentially begin chording against the active conditionals. for keyName, config in pairs(activeConditionals) do if config.isChording or when - config.downAt < repeatThreshold then if deepEquals(flags, config.expectedFlags) then config.isChording = true local synthetic = evt:copy() local syntheticFlags = {} syntheticFlags[config.chorded] = true synthetic:setFlags(syntheticFlags) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() return stopPropagation end end end elseif eventType == keyUp then for keyName, config in pairs(conditionalKeys) do if keyCode == hs.keycodes.map[keyName] then local downAt = config.downAt config.downAt = nil if config.isChording then config.isChording = false else if deepEquals(flags, {}) and when - downAt <= repeatThreshold then local synthetic = hs.eventtap.event.newKeyEvent({}, config.tapped, true) synthetic:setProperty(eventSourceUserData, syntheticEvent) synthetic:post() end end return stopPropagation end end end end) return { init = (function() local modifierTap = hs.eventtap.new( {hs.eventtap.event.types.flagsChanged}, modifierHandler ) modifierTap:start() local keyTap = hs.eventtap.new({keyDown, keyUp}, keyHandler) keyTap:start() end) }
hammerspoon: attempt to fix broken chording
hammerspoon: attempt to fix broken chording I think I had this wrong; I've had a couple of occasions now where one of Caps Lock or Enter stops working properly (only the tap functionality works, not the chord functionality).
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
81e72fc7c5cd49216b2c088e3779083b22672700
projects/premake/thirdparty_build_scripts/glfw.lua
projects/premake/thirdparty_build_scripts/glfw.lua
#!lua -- -- @file glfw.lua -- @author PJ O Halloran -- @date 25/09/2017 -- -- For building the glfw library. -- local lib_name = "glfw" local target_lib_name = lib_name .. "3" local lib_src_dir = path.join(ember_thirdparty_src, lib_name) local function build() do_pre_build(lib_name) os.execute("cmake -DGLFW_BUILD_EXAMPLES=OFF -DGLFW_BUILD_TESTS=OFF -DGLFW_BUILD_DOCS=OFF -DCMAKE_INSTALL_PREFIX:PATH=\"" .. ember_home .. "\" \"" .. lib_src_dir .. "\"") os.execute("cmake --build . --target install") append_lib(target_lib_name) append_shared_link_flag("-framework OpenGL") append_shared_link_flag("-framework Cocoa") append_shared_link_flag("-framework IOKit") append_shared_link_flag("-framework CoreVideo") append_exe_link_flag("-framework OpenGL") append_exe_link_flag("-framework Cocoa") append_exe_link_flag("-framework IOKit") append_exe_link_flag("-framework CoreVideo") do_post_build(lib_name) end build()
#!lua -- -- @file glfw.lua -- @author PJ O Halloran -- @date 25/09/2017 -- -- For building the glfw library. -- local lib_name = "glfw" local target_lib_name = lib_name .. "3" local lib_src_dir = path.join(ember_thirdparty_src, lib_name) local function build() do_pre_build(lib_name) os.execute("cmake -DGLFW_BUILD_EXAMPLES=OFF -DGLFW_BUILD_TESTS=OFF -DGLFW_BUILD_DOCS=OFF -DCMAKE_INSTALL_PREFIX:PATH=\"" .. ember_home .. "\" \"" .. lib_src_dir .. "\"") os.execute("cmake --build . --target install") append_lib(target_lib_name) append_shared_link_flag("OpenGL.framework") append_shared_link_flag("Cocoa.framework") append_shared_link_flag("IOKit.framework") append_shared_link_flag("CoreVideo.framework") append_exe_link_flag("OpenGL.framework") append_exe_link_flag("Cocoa.framework") append_exe_link_flag("IOKit.framework") append_exe_link_flag("CoreVideo.framework") do_post_build(lib_name) end build()
Fixing how osx frameworks are added/linked against.
Fixing how osx frameworks are added/linked against.
Lua
mit
pjohalloran/ember,pjohalloran/ember,pjohalloran/ember
815c258684749cba413e55b00e3c587404d54a17
src/program/lwaftr/tests/propbased/genyang.lua
src/program/lwaftr/tests/propbased/genyang.lua
module(..., package.seeall) --local S = require("syscall") --local snabb_cmd = ("/proc/%d/exe"):format(S.getpid()) local schema = require("lib.yang.schema") local capabilities = {['ietf-softwire']={feature={'binding', 'br'}}} require('lib.yang.schema').set_default_capabilities(capabilities) local schemas = { "ietf-softwire", "snabb-softwire-v1" } function generate_get(pid, schema, query) if not query then query, schema = generate_config_xpath(schema) end return string.format("./snabb config get -s %s %s \"%s\"", schema, pid, query) end function generate_get_state(pid, schema, query) if not query then query, schema = generate_config_xpath_state(schema) end return string.format("./snabb config get-state -s %s %s \"%s\"", schema, pid, query) end function generate_set(pid, schema, query, val) return string.format("./snabb config set -s %s %s \"%s\" \"%s\"", schema, pid, query, val) end function run_yang(yang_cmd) local f = io.popen(yang_cmd) local result = f:read("*a") f:close() return result end -- choose an element of an array randomly local function choose(choices) local idx = math.random(#choices) return choices[idx] end -- choose from unbounded array indices, decreasing likelihood local function choose_pos() local r = math.random() local function flip(next) local r = math.random() if r < 0.5 then return next else return flip(next + 1) end end -- evenly weight first five indices if r < 0.5 then return choose({1, 2, 3, 4, 5}) else return flip(6) end end local function value_from_type(a_type) local prim = a_type.primitive_type if prim == "int8" then return math.random(-128, 127) elseif prim == "int16" then return math.random(-32768, 32767) elseif prim == "int32" then return math.random(-2147483648, 2147483647) elseif prim == "int64" then return math.random(-9223372036854775808, 9223372036854775807) elseif prim == "uint8" then return math.random(0, 255) elseif prim == "uint16" then return math.random(0, 65535) elseif prim == "uint32" then return math.random(0, 4294967295) elseif prim == "uint64" then return math.random(0, 18446744073709551615) --elseif prim == "decimal64" then -- local int64 = value_from_type("int64") -- local exp = math.random(1, 18) -- return int64 * (10 ^ -exp) elseif prim == "boolean" then return choose({ true, false }) elseif prim == "ipv4-address" then return math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) end -- TODO: generate these: -- string -- binary -- bits -- empty -- enumeration -- identityref -- instance-identifier -- leafref -- union -- unknown type return nil end -- from a config schema, generate an xpath query string -- this code is patterned off of the visitor used in lib.yang.data local function generate_xpath(schema, for_state) local path = "" local handlers = {} local function visit(node) local handler = handlers[node.kind] if handler then handler(node) end end local function visit_body(node) local ids = {} for id, node in pairs(node.body) do -- only choose nodes that are used in configs unless -- for_state is passed if for_state or node.config ~= false then table.insert(ids, id) end end local id = choose(ids) if id then visit(node.body[id]) end end function handlers.container(node) path = path .. "/" .. node.id -- don't always go into containers, since we need to test -- fetching all sub-items too if math.random() < 0.9 then visit_body(node) end end handlers['leaf-list'] = function(node) local selector = string.format("[position()=%d]", choose_pos()) path = path .. "/" .. node.id .. selector end function handlers.list(node) local key_types = {} local r = math.random() path = path .. "/" .. node.id -- occasionally drop the selectors if r < 0.9 then for key in (node.key):split(" +") do key_types[key] = node.body[key].type end for key, type in pairs(key_types) do local val = assert(value_from_type(type), type) path = path .. string.format("[%s=%s]", key, val) end end end function handlers.leaf(node) path = path .. "/" .. node.id end -- just produce "/" on rare occasions if math.random() > 0.01 then visit_body(schema) end return path end function generate_config_xpath(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) return generate_xpath(schema, false), schema_name end function generate_config_xpath_state(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) local path = generate_xpath(schema.body["softwire-state"], true) return "/softwire-state" .. path, schema_name end function selftest() local data = require("lib.yang.data") local path = require("lib.yang.path") local schema = schema.load_schema_by_name("snabb-softwire-v1") local grammar = data.data_grammar_from_schema(schema) path.convert_path(grammar, generate_xpath(schema)) end
module(..., package.seeall) --local S = require("syscall") --local snabb_cmd = ("/proc/%d/exe"):format(S.getpid()) local schema = require("lib.yang.schema") local capabilities = {['ietf-softwire']={feature={'binding', 'br'}}} require('lib.yang.schema').set_default_capabilities(capabilities) local schemas = { "ietf-softwire", "snabb-softwire-v1" } function generate_get(pid, schema, query) if not query then query, schema = generate_config_xpath(schema) end return string.format("./snabb config get -s %s %s \"%s\"", schema, pid, query) end function generate_get_state(pid, schema, query) if not query then query, schema = generate_config_xpath_state(schema) end return string.format("./snabb config get-state -s %s %s \"%s\"", schema, pid, query) end function generate_set(pid, schema, query, val) return string.format("./snabb config set -s %s %s \"%s\" \"%s\"", schema, pid, query, val) end function run_yang(yang_cmd) local f = io.popen(yang_cmd) local result = f:read("*a") f:close() return result end -- choose an element of an array randomly local function choose(choices) local idx = math.random(#choices) return choices[idx] end -- choose from unbounded array indices, decreasing likelihood local function choose_pos() local r = math.random() local function flip(next) local r = math.random() if r < 0.5 then return next else return flip(next + 1) end end -- evenly weight first five indices if r < 0.5 then return choose({1, 2, 3, 4, 5}) else return flip(6) end end local function random_hexes() local str = "" for i=1, 4 do str = str .. string.format("%x", math.random(0, 15)) end return str end local function value_from_type(a_type) local prim = a_type.primitive_type if prim == "int8" then return math.random(-128, 127) elseif prim == "int16" then return math.random(-32768, 32767) elseif prim == "int32" then return math.random(-2147483648, 2147483647) elseif prim == "int64" then return math.random(-9223372036854775808, 9223372036854775807) elseif prim == "uint8" then return math.random(0, 255) elseif prim == "uint16" then return math.random(0, 65535) elseif prim == "uint32" then return math.random(0, 4294967295) elseif prim == "uint64" then return math.random(0, 18446744073709551615) --elseif prim == "decimal64" then -- local int64 = value_from_type("int64") -- local exp = math.random(1, 18) -- return int64 * (10 ^ -exp) elseif prim == "boolean" then return choose({ true, false }) elseif prim == "ipv4-address" then return math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) elseif prim == "ipv6-address" then local addr = random_hexes() for i=1, 7 do addr = addr .. ":" .. random_hexes() end return addr elseif prim == "ipv6-prefix" then local addr = value_from_type({ primitive_type = "ipv6-address" }) return addr .. "/" .. math.random(0, 128) elseif prim == "union" then return value_from_type(choose(a_type.union)) end -- TODO: generate these: -- string -- binary -- bits -- empty -- enumeration -- identityref -- instance-identifier -- leafref -- unknown type return nil end -- from a config schema, generate an xpath query string -- this code is patterned off of the visitor used in lib.yang.data local function generate_xpath(schema, for_state) local path = "" local handlers = {} local function visit(node) local handler = handlers[node.kind] if handler then handler(node) end end local function visit_body(node) local ids = {} for id, node in pairs(node.body) do -- only choose nodes that are used in configs unless -- for_state is passed if for_state or node.config ~= false then table.insert(ids, id) end end local id = choose(ids) if id then visit(node.body[id]) end end function handlers.container(node) path = path .. "/" .. node.id -- don't always go into containers, since we need to test -- fetching all sub-items too if math.random() < 0.9 then visit_body(node) end end handlers['leaf-list'] = function(node) local selector = string.format("[position()=%d]", choose_pos()) path = path .. "/" .. node.id .. selector end function handlers.list(node) local key_types = {} local r = math.random() path = path .. "/" .. node.id -- occasionally drop the selectors if r < 0.9 then for key in (node.key):split(" +") do key_types[key] = node.body[key].type end for key, type in pairs(key_types) do local val = assert(value_from_type(type), type.primitive_type) path = path .. string.format("[%s=%s]", key, val) end end if math.random() < 0.9 then visit_body(node) end end function handlers.leaf(node) path = path .. "/" .. node.id end -- just produce "/" on rare occasions if math.random() > 0.01 then visit_body(schema) end return path end function generate_config_xpath(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) return generate_xpath(schema, false), schema_name end function generate_config_xpath_state(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) local path = generate_xpath(schema.body["softwire-state"], true) return "/softwire-state" .. path, schema_name end function selftest() local data = require("lib.yang.data") local path = require("lib.yang.path") local schema = schema.load_schema_by_name("snabb-softwire-v1") local grammar = data.data_grammar_from_schema(schema) path.convert_path(grammar, generate_xpath(schema)) end
Traverse 'list' nodes for random generation better
Traverse 'list' nodes for random generation better Also generate values for ipv6 addresses/prefixes and unions to better explore the schema
Lua
apache-2.0
alexandergall/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,SnabbCo/snabbswitch,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,eugeneia/snabbswitch,Igalia/snabb,Igalia/snabb,heryii/snabb,dpino/snabb,eugeneia/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,heryii/snabb,Igalia/snabbswitch,dpino/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,heryii/snabb,dpino/snabb,snabbco/snabb,snabbco/snabb,heryii/snabb,dpino/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,eugeneia/snabb,dpino/snabbswitch,snabbco/snabb,dpino/snabbswitch,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,heryii/snabb,Igalia/snabbswitch,eugeneia/snabb
3753998f66458a7c5a545c0ef64d3b7b1a232fa2
src/plugins/finalcutpro/midi/controls/timeline.lua
src/plugins/finalcutpro/midi/controls/timeline.lua
--- === plugins.finalcutpro.midi.controls.timeline === --- --- Final Cut Pro MIDI Timeline Controls. local require = require --local log = require "hs.logger".new "timeline" local eventtap = require "hs.eventtap" local fcp = require "cp.apple.finalcutpro" local i18n = require "cp.i18n" local keyStroke = eventtap.keyStroke local function doNextFrame() keyStroke({"shift"}, "right", 0) end local function doPreviousFrame() keyStroke({"shift"}, "left", 0) end local function createTimelineScrub() local lastValue return function(metadata) local currentValue = metadata.controllerValue if lastValue then if currentValue == 0 and lastValue == 0 then doPreviousFrame() elseif currentValue == 127 and lastValue == 127 then doNextFrame() elseif lastValue == 127 and currentValue == 0 then doNextFrame() elseif lastValue == 0 and currentValue == 127 then doPreviousFrame() elseif currentValue > lastValue then doNextFrame() elseif currentValue < lastValue then doPreviousFrame() end end lastValue = currentValue end end local plugin = { id = "finalcutpro.midi.controls.timeline", group = "finalcutpro", dependencies = { ["core.midi.manager"] = "manager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Scrub Timeline: -------------------------------------------------------------------------------- local manager = deps.manager local params = { group = "fcpx", text = i18n("scrubTimeline") .. " ()" .. i18n("relative") .. ")", subText = i18n("scrubTimelineDescription"), fn = createTimelineScrub(), } manager.controls:new("timelineScrub", params) -------------------------------------------------------------------------------- -- Trim Toggle: -------------------------------------------------------------------------------- local params = { group = "fcpx", text = i18n("trimToggle"), subText = i18n("trimToggleDescription"), fn = function(metadata) if metadata.controllerValue == 127 then fcp:doShortcut("SelectToolTrim"):Now() elseif metadata.controllerValue == 0 then fcp:doShortcut("SelectToolArrowOrRangeSelection"):Now() end end, } manager.controls:new("trimToggle", params) end return plugin
--- === plugins.finalcutpro.midi.controls.timeline === --- --- Final Cut Pro MIDI Timeline Controls. local require = require --local log = require "hs.logger".new "timeline" local eventtap = require "hs.eventtap" local fcp = require "cp.apple.finalcutpro" local i18n = require "cp.i18n" local keyStroke = eventtap.keyStroke local function doNextFrame() keyStroke({"shift"}, "right", 0) end local function doPreviousFrame() keyStroke({"shift"}, "left", 0) end local function createTimelineScrub() local lastValue return function(metadata) local currentValue = metadata.controllerValue if lastValue then if currentValue == 0 and lastValue == 0 then doPreviousFrame() elseif currentValue == 127 and lastValue == 127 then doNextFrame() elseif lastValue == 127 and currentValue == 0 then doNextFrame() elseif lastValue == 0 and currentValue == 127 then doPreviousFrame() elseif currentValue > lastValue then doNextFrame() elseif currentValue < lastValue then doPreviousFrame() end end lastValue = currentValue end end local plugin = { id = "finalcutpro.midi.controls.timeline", group = "finalcutpro", dependencies = { ["core.midi.manager"] = "manager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Scrub Timeline: -------------------------------------------------------------------------------- local manager = deps.manager manager.controls:new("timelineScrub", { group = "fcpx", text = i18n("scrubTimeline") .. " ()" .. i18n("relative") .. ")", subText = i18n("scrubTimelineDescription"), fn = createTimelineScrub(), }) -------------------------------------------------------------------------------- -- Trim Toggle: -------------------------------------------------------------------------------- local params = manager.controls:new("trimToggle", { group = "fcpx", text = i18n("trimToggle"), subText = i18n("trimToggleDescription"), fn = function(metadata) if metadata.controllerValue == 127 then fcp:doShortcut("SelectToolTrim"):Now() elseif metadata.controllerValue == 0 then fcp:doShortcut("SelectToolArrowOrRangeSelection"):Now() end end, }) end return plugin
Fixed @stickler-ci Bug
Fixed @stickler-ci Bug
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks
8433caad2703d56fb0efb7a01abf6dbd95222aee
examples/udf/records.lua
examples/udf/records.lua
local function _join(r,delim,...) local out = '' local len = select('#',...) for i=1, len do if i > 1 then out = out .. (delim or ',') end out = out .. r[select(i,...)] end return out end function join(r,delim,...) return _join(r,delim,...) end function cat(r,...) return _join(r,'',...) end -- Generic example function example_lua(r,arg1,arg2,arg3,arg4) r[arg1] = arg2; r[arg3] = arg4; aerospike:update(r); return r['b']; end -- Get a particular bin function getbin(r,name) return r[name] end -- Set a particular bin function setbin(r,name,value) if not aerospike:exists(r) then aerospike:create(r) end local old = r[name] r[name] = value aerospike:update(r) return old end -- Set a particular bin function setbin2(r,name,value) local old = r[name] r[name] = value if not aerospike:exists(r) then aerospike:create(r) else aerospike:create(r) end return old end -- Set a particular bin function set_and_get(r,name,value) r[name] = value aerospike:update(r) return r[name] end -- Remove a paritcular bin function remove(r,name) local old = r[name] r[name] = nil aerospike:update(r) return old end -- Create a record function create_record(r,b1,v1,b2,v2) if not aerospike:exists(r) then aerospike:create(r); info("created"); else info("not created record already exists"); end if b1 and v1 then r[b1] = v1 if b2 and v2 then r[b2] = v2 end aerospike:update(r); info("updated!") end return r[b1] end -- delete a record function delete_record(r,name) info ("here"); if aerospike:exist(r) then info("exist. delete now"); return aerospike.remove(r) else info("not exist, delete should do nothing"); return aerospike.remove(r) end end -- @TODO return record as is -- function echo_record(record) -- return record; -- end
local function _join(r,delim,...) local out = '' local len = select('#',...) for i=1, len do if i > 1 then out = out .. (delim or ',') end out = out .. r[select(i,...)] end return out end function join(r,delim,...) return _join(r,delim,...) end function cat(r,...) return _join(r,'',...) end -- Generic example function example_lua(r,arg1,arg2,arg3,arg4) r[arg1] = arg2; r[arg3] = arg4; aerospike:update(r); return r['b']; end -- Get a particular bin function getbin(r,name) return r[name] end -- Set a particular bin function setbin(r,name,value) if not aerospike:exists(r) then aerospike:create(r) end local old = r[name] r[name] = value aerospike:update(r) return old end -- Set a particular bin function setbin2(r,name,value) local old = r[name] r[name] = value if not aerospike:exists(r) then aerospike:create(r) else aerospike:create(r) end return old end -- Set a particular bin function set_and_get(r,name,value) r[name] = value aerospike:update(r) return r[name] end -- Remove a paritcular bin function remove(r,name) local old = r[name] r[name] = nil aerospike:update(r) return old end -- Create a record function create_record(r,b1,v1,b2,v2) if not aerospike:exists(r) then aerospike:create(r); info("created"); else info("not created record already exists"); end if b1 and v1 then r[b1] = v1 if b2 and v2 then r[b2] = v2 end aerospike:update(r); info("updated!") end return r[b1] end -- delete a record function delete_record(r) if aerospike:exists(r) then return aerospike:remove(r) else return 1 end end -- @TODO return record as is -- function echo_record(record) -- return record; -- end
Fix delete_record.
Fix delete_record.
Lua
apache-2.0
wgpshashank/aerospike-client-java,alexandrnikitin/aerospike-client-java,pradeepsrinivasan/aerospike-client-java,pradeepsrinivasan/aerospike-client-java,Stratio/aerospike-client-java,Stratio/aerospike-client-java,wgpshashank/aerospike-client-java,alexandrnikitin/aerospike-client-java
8422bb56b650da5595b4070a5e3988fc5162c7a7
src/npge/alignment/goodSlices.lua
src/npge/alignment/goodSlices.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- Arguments: -- 1. list of column statuses (true is good column) -- 2. min_length (integer) -- 3. min_end (integer) -- number of begin and end good columns -- 4. min_identity (from 0.0 to 1.0) -- Results: -- 1. List of good slices -- Each slice is a table {start, stop} -- Indices start and stop start from 0 return function(good_col, min_length, min_end, min_identity) assert(min_length >= min_end) local block_length = #good_col -- convert values in good_col to 0 or 1 local good_col1 = {} for i = 1, #good_col do good_col1[i] = good_col[i] and 1 or 0 end -- class Slice local slice_mt local function Slice(start, length) local self = {} self.start = start self.length = length return setmetatable(self, slice_mt) end slice_mt = { stop = function(self) return self.start + self.length - 1 end, -- compare by length __lt = function(self, other) return self.length < other.length or (self.length == other.length and self.start < other.start) end, overlaps = function(self, other) if other.start <= self.start and self.start <= other:stop() then return true end if other.start <= self:stop() and self:stop() <= other:stop() then return true end return false end, exclude = function(self, other) local start1 = self.start local stop1 = self:stop() if other.start <= self.start and self.start <= other:stop() then start1 = other:stop() + 1 end if other.start <= self:stop() and self:stop() <= other:stop() then stop1 = other.start - 1 end local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, strip = function(self) if not self:valid() then return self end local start1 = self.start local stop1 = self:stop() -- begin local good_count = 0 for i = start1, start1 + min_end - 1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 + min_end - 1 < stop1 do good_count = good_count - good_col1[start1 + 1] start1 = start1 + 1 local new_pos = start1 + min_end - 1 good_count = good_count + good_col1[new_pos + 1] end -- end local good_count = 0 for i = stop1, stop1 - min_end + 1, -1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 + min_end - 1 < stop1 do good_count = good_count - good_col1[stop1 + 1] stop1 = stop1 - 1 local new_pos = stop1 - min_end + 1 good_count = good_count + good_col1[new_pos + 1] end -- result local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, valid = function(self) return self.length >= min_length and self.start >= 0 and self:stop() < block_length end, } slice_mt.__index = slice_mt -- Return if identity (good_count / min_length) is good local identity = require 'npge.alignment.identity' local less = require 'npge.block.identity'.less local min_good = min_length * min_identity local function goodIdentity(good_count) return not less(good_count, min_good) end -- Return list of statuses of slices of length min_length local function findGoodSlices() local good_slice = {} local good_count = 0 for i = 1, min_length do good_count = good_count + good_col1[i] end good_slice[1] = goodIdentity(good_count) for new_pos = min_length + 1, block_length do local old_pos = new_pos - min_length good_count = good_count + good_col1[new_pos] good_count = good_count - good_col1[old_pos] local start = old_pos + 1 good_slice[start] = goodIdentity(good_count) end return good_slice end -- Return list of joined slices local function joinSlices(good_slice) local slices0 = {} local last_slice for i = 1, block_length - min_length + 1 do if good_slice[i] then if i > 1 and good_slice[i - 1] then -- increase previous slice assert(#slices0 > 0) last_slice.length = last_slice.length + 1 else -- add new slice last_slice = Slice(i - 1, min_length) table.insert(slices0, last_slice) end end end local slices = {} for _, slice in ipairs(slices0) do slice = slice:strip() if slice:valid() then table.insert(slices, slice) end end return slices end local function maxSlice(slices) local result = slices[1] for _, slice in ipairs(slices) do if slice > result then result = slice end end return result end -- Exclude selected slice from slices, return new slices local function excludeSlice(slices, selected) local slices1 = {} for _, slice in ipairs(slices) do if not slice:overlaps(selected) then table.insert(slices1, slice) else slice = slice:exclude(selected):strip() if slice:valid() then table.insert(slices1, slice) end end end return slices1 end local good_slice = findGoodSlices() local slices = joinSlices(good_slice) local result = {} while #slices > 0 do local selected = maxSlice(slices) if selected.length >= min_length then local r = {selected.start, selected:stop()} table.insert(result, r) slices = excludeSlice(slices, selected) end end return result end
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- Arguments: -- 1. list of column statuses (true is good column) -- 2. min_length (integer) -- 3. min_end (integer) -- number of begin and end good columns -- 4. min_identity (from 0.0 to 1.0) -- Results: -- 1. List of good slices -- Each slice is a table {start, stop} -- Indices start and stop start from 0 return function(good_col, min_length, min_end, min_identity) assert(min_length >= min_end) local block_length = #good_col -- count number of good columns at pos <= index local good_sum = {} good_sum[0] = 0 for i = 1, block_length do good_sum[i] = good_sum[i-1] + (good_col[i] and 1 or 0) end -- start and stop are 0-based local function countGood(start, stop) return good_sum[stop + 1] - good_sum[start - 1 + 1] end local function allGood(start, stop) local length = stop - start + 1 return countGood(start, stop) == length end -- class Slice local slice_mt local function Slice(start, length) local self = {} self.start = start self.length = length return setmetatable(self, slice_mt) end slice_mt = { stop = function(self) return self.start + self.length - 1 end, -- compare by length __lt = function(self, other) return self.length < other.length or (self.length == other.length and self.start < other.start) end, overlaps = function(self, other) if other.start <= self.start and self.start <= other:stop() then return true end if other.start <= self:stop() and self:stop() <= other:stop() then return true end return false end, exclude = function(self, other) local start1 = self.start local stop1 = self:stop() if other.start <= self.start and self.start <= other:stop() then start1 = other:stop() + 1 end if other.start <= self:stop() and self:stop() <= other:stop() then stop1 = other.start - 1 end local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, strip = function(self) if not self:valid() then return self end local start1 = self.start local stop1 = self:stop() while not allGood(start1, start1 + min_end - 1) and start1 + min_end - 1 < stop1 do start1 = start1 + 1 end while not allGood(stop1 - min_end + 1, stop1) and start1 + min_end - 1 < stop1 do stop1 = stop1 - 1 end -- result local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, valid = function(self) return self.length >= min_length and self.start >= 0 and self:stop() < block_length end, } slice_mt.__index = slice_mt -- Return if identity (good_count / min_length) is good local identity = require 'npge.alignment.identity' local less = require 'npge.block.identity'.less local min_good = min_length * min_identity local function goodIdentity(good_count) return not less(good_count, min_good) end -- Return if slice {start, start + min_length - 1} is good local function goodSlice(start) local stop = start + min_length - 1 return goodIdentity(countGood(start, stop)) end -- Return list of joined slices local function joinedSlices() local slices0 = {} local last_slice local prev_good for i = 0, block_length - min_length do local curr_good = goodSlice(i) if curr_good then if i > 0 and prev_good then -- increase previous slice assert(#slices0 > 0) last_slice.length = last_slice.length + 1 else -- add new slice last_slice = Slice(i, min_length) table.insert(slices0, last_slice) end end prev_good = curr_good end local slices = {} for _, slice in ipairs(slices0) do slice = slice:strip() if slice:valid() then table.insert(slices, slice) end end return slices end local function maxSlice(slices) local result = slices[1] for _, slice in ipairs(slices) do if slice > result then result = slice end end return result end -- Exclude selected slice from slices, return new slices local function excludeSlice(slices, selected) local slices1 = {} for _, slice in ipairs(slices) do if not slice:overlaps(selected) then table.insert(slices1, slice) else slice = slice:exclude(selected):strip() if slice:valid() then table.insert(slices1, slice) end end end return slices1 end local slices = joinedSlices() local result = {} while #slices > 0 do local selected = maxSlice(slices) if selected.length >= min_length then local r = {selected.start, selected:stop()} table.insert(result, r) slices = excludeSlice(slices, selected) end end return result end
rewrite goodSlices with table of good columns sum
rewrite goodSlices with table of good columns sum The algorithm was not changed. Array good_sum is used to cache number of good columns in each prefix. It can be used to get number of good columns in each slice. This code is clearer than frame chaining.
Lua
mit
starius/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge
fec95a8ace000b2d805bd20c24d28f24b705256b
src/base/os.lua
src/base/os.lua
-- -- os.lua -- Additions to the OS namespace. -- Copyright (c) 2002-2011 Jason Perkins and the Premake project -- -- -- Same as os.execute(), but accepts string formatting arguments. -- function os.executef(cmd, ...) cmd = string.format(cmd, unpack(arg)) return os.execute(cmd) end -- -- Scan the well-known system locations for a particular library. -- local function parse_ld_so_conf(conf_file) -- Linux ldconfig file parser to find system library locations local first, last local dirs = { } local file = io.open(conf_file) -- Handle missing ld.so.conf (BSDs) gracefully if file == nil then return dirs end for line in file:lines() do -- ignore comments first = line:find("#", 1, true) if first ~= nil then line = line:sub(1, first - 1) end if line ~= "" then -- check for include files first, last = line:find("include%s+") if first ~= nil then -- found include glob local include_glob = line:sub(last + 1) local includes = os.matchfiles(include_glob) for _, v in ipairs(includes) do dirs = table.join(dirs, parse_ld_so_conf(v)) end else -- found an actual ld path entry table.insert(dirs, line) end end end return dirs end function os.findlib(libname) local path, formats -- assemble a search path, depending on the platform if os.is("windows") then formats = { "%s.dll", "%s" } path = os.getenv("PATH") elseif os.is("haiku") then formats = { "lib%s.so", "%s.so" } path = os.getenv("LIBRARY_PATH") else if os.is("macosx") then formats = { "lib%s.dylib", "%s.dylib" } path = os.getenv("DYLD_LIBRARY_PATH") else formats = { "lib%s.so", "%s.so" } path = os.getenv("LD_LIBRARY_PATH") or "" for _, v in ipairs(parse_ld_so_conf("/etc/ld.so.conf")) do path = path .. ":" .. v end end table.insert(formats, "%s") path = path or "" if os.is64bit() then path = path .. ":/lib64:/usr/lib64/:usr/local/lib64" end path = path .. ":/lib:/usr/lib:/usr/local/lib" end for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) local result = os.pathsearch(name, path) if result then return result end end end -- -- Retrieve the current operating system ID string. -- function os.get() return _OPTIONS.os or _OS end -- -- Check the current operating system; may be set with the /os command line flag. -- function os.is(id) return (os.get():lower() == id:lower()) end -- -- Determine if the current system is running a 64-bit architecture -- local _64BitHostTypes = { "x86_64", "ia64", "amd64", "ppc64", "powerpc64", "sparc64" } function os.is64bit() -- Call the native code implementation. If this returns true then -- we're 64-bit, otherwise do more checking locally if (os._is64bit()) then return true end -- Identify the system local arch if _OS == "windows" then arch = os.getenv("PROCESSOR_ARCHITECTURE") elseif _OS == "macosx" then arch = os.outputof("echo $HOSTTYPE") else arch = os.outputof("uname -m") end -- Check our known 64-bit identifiers arch = arch:lower() for _, hosttype in ipairs(_64BitHostTypes) do if arch:find(hosttype) then return true end end return false end -- -- The os.matchdirs() and os.matchfiles() functions -- local function domatch(result, mask, wantfiles) -- need to remove extraneous path info from the mask to ensure a match -- against the paths returned by the OS. Haven't come up with a good -- way to do it yet, so will handle cases as they come up if mask:startswith("./") then mask = mask:sub(3) end -- strip off any leading directory information to find out -- where the search should take place local basedir = mask local starpos = mask:find("%*") if starpos then basedir = basedir:sub(1, starpos - 1) end basedir = path.getdirectory(basedir) if (basedir == ".") then basedir = "" end -- recurse into subdirectories? local recurse = mask:find("**", nil, true) -- convert mask to a Lua pattern mask = path.wildcards(mask) local function matchwalker(basedir) local wildcard = path.join(basedir, "*") -- retrieve files from OS and test against mask local m = os.matchstart(wildcard) while (os.matchnext(m)) do local isfile = os.matchisfile(m) if ((wantfiles and isfile) or (not wantfiles and not isfile)) then local fname = path.join(basedir, os.matchname(m)) if fname:match(mask) == fname then table.insert(result, fname) end end end os.matchdone(m) -- check subdirectories if recurse then m = os.matchstart(wildcard) while (os.matchnext(m)) do if not os.matchisfile(m) then local dirname = os.matchname(m) if (not dirname:startswith(".")) then matchwalker(path.join(basedir, dirname)) end end end os.matchdone(m) end end matchwalker(basedir) end function os.matchdirs(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, false) end return result end function os.matchfiles(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, true) end return result end -- -- An overload of the os.mkdir() function, which will create any missing -- subdirectories along the path. -- local builtin_mkdir = os.mkdir function os.mkdir(p) local dir = iif(p:startswith("/"), "/", "") for part in p:gmatch("[^/]+") do dir = dir .. part if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then local ok, err = builtin_mkdir(dir) if (not ok) then return nil, err end end dir = dir .. "/" end return true end -- -- Run a shell command and return the output. -- function os.outputof(cmd) local pipe = io.popen(cmd) local result = pipe:read('*a') pipe:close() return result end -- -- Remove a directory, along with any contained files or subdirectories. -- local builtin_rmdir = os.rmdir function os.rmdir(p) -- recursively remove subdirectories local dirs = os.matchdirs(p .. "/*") for _, dname in ipairs(dirs) do os.rmdir(dname) end -- remove any files local files = os.matchfiles(p .. "/*") for _, fname in ipairs(files) do os.remove(fname) end -- remove this directory builtin_rmdir(p) end
-- -- os.lua -- Additions to the OS namespace. -- Copyright (c) 2002-2011 Jason Perkins and the Premake project -- -- -- Same as os.execute(), but accepts string formatting arguments. -- function os.executef(cmd, ...) cmd = string.format(cmd, unpack(arg)) return os.execute(cmd) end -- -- Scan the well-known system locations for a particular library. -- local function parse_ld_so_conf(conf_file) -- Linux ldconfig file parser to find system library locations local first, last local dirs = { } local file = io.open(conf_file) -- Handle missing ld.so.conf (BSDs) gracefully if file == nil then return dirs end for line in file:lines() do -- ignore comments first = line:find("#", 1, true) if first ~= nil then line = line:sub(1, first - 1) end if line ~= "" then -- check for include files first, last = line:find("include%s+") if first ~= nil then -- found include glob local include_glob = line:sub(last + 1) local includes = os.matchfiles(include_glob) for _, v in ipairs(includes) do dirs = table.join(dirs, parse_ld_so_conf(v)) end else -- found an actual ld path entry table.insert(dirs, line) end end end return dirs end function os.findlib(libname) local path, formats -- assemble a search path, depending on the platform if os.is("windows") then formats = { "%s.dll", "%s" } path = os.getenv("PATH") elseif os.is("haiku") then formats = { "lib%s.so", "%s.so" } path = os.getenv("LIBRARY_PATH") else if os.is("macosx") then formats = { "lib%s.dylib", "%s.dylib" } path = os.getenv("DYLD_LIBRARY_PATH") else formats = { "lib%s.so", "%s.so" } path = os.getenv("LD_LIBRARY_PATH") or "" for _, v in ipairs(parse_ld_so_conf("/etc/ld.so.conf")) do path = path .. ":" .. v end end table.insert(formats, "%s") path = path or "" if os.is64bit() then path = path .. ":/lib64:/usr/lib64/:usr/local/lib64" end path = path .. ":/lib:/usr/lib:/usr/local/lib" end for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) local result = os.pathsearch(name, path) if result then return result end end end -- -- Retrieve the current operating system ID string. -- function os.get() return _OPTIONS.os or _OS end -- -- Check the current operating system; may be set with the /os command line flag. -- function os.is(id) return (os.get():lower() == id:lower()) end -- -- Determine if the current system is running a 64-bit architecture -- local _64BitHostTypes = { "x86_64", "ia64", "amd64", "ppc64", "powerpc64", "sparc64" } function os.is64bit() -- Call the native code implementation. If this returns true then -- we're 64-bit, otherwise do more checking locally if (os._is64bit()) then return true end -- Identify the system local arch if _OS == "windows" then arch = os.getenv("PROCESSOR_ARCHITECTURE") elseif _OS == "macosx" then arch = os.outputof("echo $HOSTTYPE") else arch = os.outputof("uname -m") end -- Check our known 64-bit identifiers arch = arch:lower() for _, hosttype in ipairs(_64BitHostTypes) do if arch:find(hosttype) then return true end end return false end -- -- The os.matchdirs() and os.matchfiles() functions -- local function domatch(result, mask, wantfiles) -- need to remove extraneous path info from the mask to ensure a match -- against the paths returned by the OS. Haven't come up with a good -- way to do it yet, so will handle cases as they come up if mask:startswith("./") then mask = mask:sub(3) end -- strip off any leading directory information to find out -- where the search should take place local basedir = mask local starpos = mask:find("%*") if starpos then basedir = basedir:sub(1, starpos - 1) end basedir = path.getdirectory(basedir) if (basedir == ".") then basedir = "" end -- recurse into subdirectories? local recurse = mask:find("**", nil, true) -- convert mask to a Lua pattern mask = path.wildcards(mask) local function matchwalker(basedir) local wildcard = path.join(basedir, "*") -- retrieve files from OS and test against mask local m = os.matchstart(wildcard) while (os.matchnext(m)) do local isfile = os.matchisfile(m) if ((wantfiles and isfile) or (not wantfiles and not isfile)) then local basename = os.matchname(m) local fullname = path.join(basedir, basename) if basename ~= ".." and fullname:match(mask) == fullname then table.insert(result, fullname) end end end os.matchdone(m) -- check subdirectories if recurse then m = os.matchstart(wildcard) while (os.matchnext(m)) do if not os.matchisfile(m) then local dirname = os.matchname(m) if (not dirname:startswith(".")) then matchwalker(path.join(basedir, dirname)) end end end os.matchdone(m) end end matchwalker(basedir) end function os.matchdirs(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, false) end return result end function os.matchfiles(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, true) end return result end -- -- An overload of the os.mkdir() function, which will create any missing -- subdirectories along the path. -- local builtin_mkdir = os.mkdir function os.mkdir(p) local dir = iif(p:startswith("/"), "/", "") for part in p:gmatch("[^/]+") do dir = dir .. part if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then local ok, err = builtin_mkdir(dir) if (not ok) then return nil, err end end dir = dir .. "/" end return true end -- -- Run a shell command and return the output. -- function os.outputof(cmd) local pipe = io.popen(cmd) local result = pipe:read('*a') pipe:close() return result end -- -- Remove a directory, along with any contained files or subdirectories. -- local builtin_rmdir = os.rmdir function os.rmdir(p) -- recursively remove subdirectories local dirs = os.matchdirs(p .. "/*") for _, dname in ipairs(dirs) do os.rmdir(dname) end -- remove any files local files = os.matchfiles(p .. "/*") for _, fname in ipairs(files) do os.remove(fname) end -- remove this directory builtin_rmdir(p) end
Fix Issue #242: Recursive deletion in os.rmdir() goes up to root level on Windows 7 (Ben Henning)
Fix Issue #242: Recursive deletion in os.rmdir() goes up to root level on Windows 7 (Ben Henning)
Lua
bsd-3-clause
lizh06/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x,lizh06/premake-4.x,premake/premake-4.x
8cba23531ee302b85e4ac66329074b89e7dc47d9
mods/pipeworks/signal_tubes.lua
mods/pipeworks/signal_tubes.lua
if pipeworks.enable_detector_tube then local detector_tube_step = 2 * tonumber(minetest.setting_get("dedicated_server_step")) pipeworks.register_tube("pipeworks:detector_tube_on", { description = "Detecting Pneumatic Tube Segment on (you hacker you)", inventory_image = "pipeworks_detector_tube_inv.png", plain = { "pipeworks_detector_tube_plain.png" }, node_def = { tube = {can_go = function(pos, node, velocity, stack) local meta = minetest.get_meta(pos) local name = minetest.get_node(pos).name local nitems = meta:get_int("nitems")+1 meta:set_int("nitems", nitems) local saved_pos = vector.new(pos) minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos) return pipeworks.notvel(pipeworks.meseadjlist,velocity) end}, groups = {mesecon = 2, not_in_creative_inventory = 1}, drop = "pipeworks:detector_tube_off_1", mesecons = {receptor = {state = "on", rules = pipeworks.mesecons_rules}}, item_exit = function(pos) local meta = minetest.get_meta(pos) local nitems = meta:get_int("nitems")-1 local node = minetest.get_node(pos) local name = node.name local fdir = node.param2 if nitems == 0 then minetest.set_node(pos, {name = string.gsub(name, "on", "off"), param2 = fdir}) mesecon.receptor_off(pos, pipeworks.mesecons_rules) else meta:set_int("nitems", nitems) end end, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_int("nitems", 1) local name = minetest.get_node(pos).name local saved_pos = vector.new(pos) minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos) end, }, }) pipeworks.register_tube("pipeworks:detector_tube_off", { description = "Detecting Pneumatic Tube Segment", inventory_image = "pipeworks_detector_tube_inv.png", plain = { "pipeworks_detector_tube_plain.png" }, node_def = { tube = {can_go = function(pos, node, velocity, stack) local node = minetest.get_node(pos) local name = node.name local fdir = node.param2 minetest.set_node(pos,{name = string.gsub(name, "off", "on"), param2 = fdir}) mesecon.receptor_on(pos, pipeworks.mesecons_rules) return pipeworks.notvel(pipeworks.meseadjlist, velocity) end}, groups = {mesecon = 2}, mesecons = {receptor = {state = "off", rules = pipeworks.mesecons_rules }}, }, }) minetest.register_craft( { output = "pipeworks:conductor_tube_off_1 6", recipe = { { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }, { "mesecons:mesecon", "mesecons:mesecon", "mesecons:mesecon" }, { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" } }, }) end if pipeworks.enable_conductor_tube then pipeworks.register_tube("pipeworks:conductor_tube_off", { description = "Conducting Pneumatic Tube Segment", inventory_image = "pipeworks_conductor_tube_inv.png", short = "pipeworks_conductor_tube_short.png", plain = { "pipeworks_conductor_tube_plain.png" }, noctr = { "pipeworks_conductor_tube_noctr.png" }, ends = { "pipeworks_conductor_tube_end.png" }, node_def = { groups = {mesecon = 2}, mesecons = {conductor = {state = "off", rules = pipeworks.mesecons_rules, onstate = "pipeworks:conductor_tube_on_#id"}} }, }) pipeworks.register_tube("pipeworks:conductor_tube_on", { description = "Conducting Pneumatic Tube Segment on (you hacker you)", inventory_image = "pipeworks_conductor_tube_inv.png", short = "pipeworks_conductor_tube_short.png", plain = { "pipeworks_conductor_tube_on_plain.png" }, noctr = { "pipeworks_conductor_tube_on_noctr.png" }, ends = { "pipeworks_conductor_tube_on_end.png" }, node_def = { groups = {mesecon = 2, not_in_creative_inventory = 1}, drop = "pipeworks:conductor_tube_off_1", mesecons = {conductor = {state = "on", rules = pipeworks.mesecons_rules, offstate = "pipeworks:conductor_tube_off_#id"}} }, }) minetest.register_craft( { output = "pipeworks:detector_tube_off_1 2", recipe = { { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }, { "mesecons:mesecon", "mesecons_materials:silicon", "mesecons:mesecon" }, { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" } }, }) end
if pipeworks.enable_detector_tube then local detector_tube_step = 1 --MFF crabman(2/1/2016 bug,step too short) 2 * tonumber(minetest.setting_get("dedicated_server_step")) pipeworks.register_tube("pipeworks:detector_tube_on", { description = "Detecting Pneumatic Tube Segment on (you hacker you)", inventory_image = "pipeworks_detector_tube_inv.png", plain = { "pipeworks_detector_tube_plain.png" }, node_def = { tube = {can_go = function(pos, node, velocity, stack) local meta = minetest.get_meta(pos) local name = minetest.get_node(pos).name local nitems = meta:get_int("nitems")+1 meta:set_int("nitems", nitems) local saved_pos = vector.new(pos) minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos) return pipeworks.notvel(pipeworks.meseadjlist,velocity) end}, groups = {mesecon = 2, not_in_creative_inventory = 1}, drop = "pipeworks:detector_tube_off_1", mesecons = {receptor = {state = "on", rules = pipeworks.mesecons_rules}}, item_exit = function(pos) local meta = minetest.get_meta(pos) local nitems = meta:get_int("nitems")-1 local node = minetest.get_node(pos) local name = node.name local fdir = node.param2 if nitems == 0 then minetest.set_node(pos, {name = string.gsub(name, "on", "off"), param2 = fdir}) mesecon.receptor_off(pos, pipeworks.mesecons_rules) else meta:set_int("nitems", nitems) end end, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_int("nitems", 1) local name = minetest.get_node(pos).name local saved_pos = vector.new(pos) minetest.after(detector_tube_step, minetest.registered_nodes[name].item_exit, saved_pos) end, }, }) pipeworks.register_tube("pipeworks:detector_tube_off", { description = "Detecting Pneumatic Tube Segment", inventory_image = "pipeworks_detector_tube_inv.png", plain = { "pipeworks_detector_tube_plain.png" }, node_def = { tube = {can_go = function(pos, node, velocity, stack) local node = minetest.get_node(pos) local name = node.name local fdir = node.param2 minetest.set_node(pos,{name = string.gsub(name, "off", "on"), param2 = fdir}) mesecon.receptor_on(pos, pipeworks.mesecons_rules) return pipeworks.notvel(pipeworks.meseadjlist, velocity) end}, groups = {mesecon = 2}, mesecons = {receptor = {state = "off", rules = pipeworks.mesecons_rules }}, }, }) minetest.register_craft( { output = "pipeworks:conductor_tube_off_1 6", recipe = { { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }, { "mesecons:mesecon", "mesecons:mesecon", "mesecons:mesecon" }, { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" } }, }) end if pipeworks.enable_conductor_tube then pipeworks.register_tube("pipeworks:conductor_tube_off", { description = "Conducting Pneumatic Tube Segment", inventory_image = "pipeworks_conductor_tube_inv.png", short = "pipeworks_conductor_tube_short.png", plain = { "pipeworks_conductor_tube_plain.png" }, noctr = { "pipeworks_conductor_tube_noctr.png" }, ends = { "pipeworks_conductor_tube_end.png" }, node_def = { groups = {mesecon = 2}, mesecons = {conductor = {state = "off", rules = pipeworks.mesecons_rules, onstate = "pipeworks:conductor_tube_on_#id"}} }, }) pipeworks.register_tube("pipeworks:conductor_tube_on", { description = "Conducting Pneumatic Tube Segment on (you hacker you)", inventory_image = "pipeworks_conductor_tube_inv.png", short = "pipeworks_conductor_tube_short.png", plain = { "pipeworks_conductor_tube_on_plain.png" }, noctr = { "pipeworks_conductor_tube_on_noctr.png" }, ends = { "pipeworks_conductor_tube_on_end.png" }, node_def = { groups = {mesecon = 2, not_in_creative_inventory = 1}, drop = "pipeworks:conductor_tube_off_1", mesecons = {conductor = {state = "on", rules = pipeworks.mesecons_rules, offstate = "pipeworks:conductor_tube_off_#id"}} }, }) minetest.register_craft( { output = "pipeworks:detector_tube_off_1 2", recipe = { { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }, { "mesecons:mesecon", "mesecons_materials:silicon", "mesecons:mesecon" }, { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" } }, }) end
fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/355
fix issue https://github.com/MinetestForFun/server-minetestforfun/issues/355
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
e0f59d309a3aadcfd6a577e9f44dc981af3cd4b5
BIOS/setup.lua
BIOS/setup.lua
--BIOS Setup Screen local Handled = ... --Handled is passed by BIOS POST, love is available too. local BIOS = Handled.BIOS local GPU = Handled.GPU local CPU = Handled.CPU local fs = Handled.HDD local KB = Handled.Keyboard local coreg = require("Engine.coreg") local stopWhile = false local wipingMode = false GPU.clear(0) GPU.color(7) KB.textinput(true) local function drawInfo() GPU.clear(0) GPU.printCursor(0,0,0) GPU.print("LIKO-12 Setup ------ Press R to reboot") GPU.print("Press O to reflash DiskOS") GPU.print("Press B to boot from D:") GPU.print("Press W then C or D to wipe a disk") end local function attemptBootFromD() fs.drive("D") local bootchunk, err = fs.load("/boot.lua") if not bootchunk then error(err or "") end local coglob = coreg:sandbox(bootchunk) local co = coroutine.create(bootchunk) local HandledAPIS = BIOS.HandledAPIS() coroutine.yield("echo",HandledAPIS) coreg:setCoroutine(co,coglob) --Switch to boot.lua coroutine end drawInfo() while not stopWhile do for event, a, _, c, _, _, _ in CPU.pullEvent do if event == "keypressed" and c == false then if a == "o" then GPU.print("Flashing in 5 seconds...") CPU.sleep(5) love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false) CPU.reboot() end if a == "r" then CPU.reboot() end if a == "w" then wipingMode = true GPU.print("Wiping mode enabled") GPU.flip() end if a == "b" then if not fs.exists("/boot.lua") then GPU.print("Could not find boot.lua") CPU.sleep(1) drawInfo() else stopWhile = true break end end if wipingMode then if a == "c" then GPU.print("Wiping C: in 15 seconds!") CPU.sleep(15) GPU.print("Please wait, wiping...") fs.drive("C") fs.delete("/") GPU.print("Wipe done.") GPU.flip() CPU.sleep(1) drawInfo() end if a == "d" and c == false then GPU.print("Wiping D: in 15 seconds!") CPU.sleep(15) GPU.print("Please wait, wiping...") fs.drive("D") fs.delete("/") GPU.print("Wipe done.") CPU.sleep(1) drawInfo() end end end if event == "touchpressed" then KB.textinput(true) end end end attemptBootFromD()
--BIOS Setup Screen local Handled = ... --Handled is passed by BIOS POST local BIOS = Handled.BIOS local GPU = Handled.GPU local CPU = Handled.CPU local fs = Handled.HDD local KB = Handled.Keyboard local coreg = require("Engine.coreg") local stopWhile = false local wipingMode = false GPU.clear(0) GPU.color(7) KB.textinput(true) local function drawInfo() GPU.clear(0) GPU.printCursor(0,0,0) GPU.print("LIKO-12 Setup ------ Press R to reboot") GPU.print("Press O to reflash DiskOS") GPU.print("Press B to boot from D:") GPU.print("Press W then C or D to wipe a disk") if CPU.isMobile() then GPU.print("Press F to show LIKO-12 folder") else GPU.print("Press F to open LIKO-12 folder") end end local function attemptBootFromD() local bootchunk, err = fs.load("/boot.lua") if not bootchunk then error(err or "") end local coglob = coreg:sandbox(bootchunk) local co = coroutine.create(bootchunk) local HandledAPIS = BIOS.HandledAPIS() coroutine.yield("echo",HandledAPIS) coreg:setCoroutine(co,coglob) --Switch to boot.lua coroutine end drawInfo() while not stopWhile do for event, a, _, c, _, _, _ in CPU.pullEvent do if event == "keypressed" and c == false then if a == "o" then GPU.print("Flashing in 5 seconds...") CPU.sleep(5) love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false) CPU.reboot() end if a == "r" then CPU.reboot() end if a == "w" then wipingMode = true GPU.print("Wiping mode enabled") GPU.flip() end if a == "b" then fs.drive("D") if not fs.exists("/boot.lua") then GPU.print("Could not find boot.lua") CPU.sleep(1) drawInfo() else stopWhile = true break end end if a == "f" then if CPU.isMobile() then drawInfo() GPU.print(CPU.getSaveDirectory()) else CPU.openAppData("/") end end if wipingMode then if a == "c" then GPU.print("Wiping C: in 15 seconds!") CPU.sleep(15) GPU.print("Please wait, wiping...") fs.drive("C") fs.delete("/") GPU.print("Wipe done.") GPU.flip() CPU.sleep(1) drawInfo() end if a == "d" and c == false then GPU.print("Wiping D: in 15 seconds!") CPU.sleep(15) GPU.print("Please wait, wiping...") fs.drive("D") fs.delete("/") GPU.print("Wipe done.") CPU.sleep(1) drawInfo() end end end if event == "touchpressed" then KB.textinput(true) end end end attemptBootFromD()
Fix crash & add view save folder option in setup
Fix crash & add view save folder option in setup Former-commit-id: 8bca1a3f3ac9e7d3ad27aee15ddce7b27964d9a5
Lua
mit
RamiLego4Game/LIKO-12
fd61c350299a4d888bb3e81594077224e5fb4252
xmake/modules/private/action/trybuild/ndkbuild.lua
xmake/modules/private/action/trybuild/ndkbuild.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file ndkbuild.lua -- -- imports import("core.base.option") import("core.project.config") import("lib.detect.find_file") -- get ndk directory function _get_ndkdir() local ndk = assert(config.get("ndk"), "ndkbuild: please uses `xmake f --ndk=` to set the ndk path!") return path.absolute(ndk) end -- detect build-system and configuration file function detect() return find_file("Android.mk", path.join(os.curdir(), "jni")) end -- do clean function clean() -- get the ndk root directory local ndk = _get_ndkdir() assert(os.isdir(ndk), "%s not found!", ndk) -- do clean os.vexecv(path.join(ndk, "ndk-build"), {"clean"}, {envs = {NDK_ROOT = ndk}}) end -- do build function build() -- only support the android platform now! assert(is_plat("android"), "ndkbuild: please uses `xmake f -p android --trybuild=ndkbuild` to switch to android platform!") -- get the ndk root directory local ndk = _get_ndkdir() assert(os.isdir(ndk), "%s not found!", ndk) -- do build local argv = {} if option.get("verbose") then table.insert(argv, "V=1") end os.vexecv(path.join(ndk, "ndk-build"), argv, {envs = {NDK_ROOT = ndk}}) cprint("${bright}build ok!") end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file ndkbuild.lua -- -- imports import("core.base.option") import("core.project.config") import("lib.detect.find_file") -- get ndk directory function _get_ndkdir() local ndk = assert(config.get("ndk"), "ndkbuild: please uses `xmake f --ndk=` to set the ndk path!") return path.absolute(ndk) end -- detect build-system and configuration file function detect() return find_file("Android.mk", path.join(os.curdir(), "jni")) end -- do clean function clean() -- get the ndk root directory local ndk = _get_ndkdir() assert(os.isdir(ndk), "%s not found!", ndk) -- do clean os.vexecv(path.join(ndk, "ndk-build"), {"clean"}, {envs = {NDK_ROOT = ndk}}) end -- do build function build() -- only support the android platform now! assert(is_plat("android"), "ndkbuild: please uses `xmake f -p android --trybuild=ndkbuild` to switch to android platform!") -- get the ndk root directory local ndk = _get_ndkdir() assert(os.isdir(ndk), "%s not found!", ndk) -- do build local argv = {} if option.get("verbose") then table.insert(argv, "V=1") end local ndkbuild = path.join(ndk, "ndk-build") if is_host("windows") then ndkbuild = ndkbuild .. ".cmd" end os.vexecv(ndkbuild, argv, {envs = {NDK_ROOT = ndk}}) cprint("${bright}build ok!") end
fix ndkbuild for windows
fix ndkbuild for windows
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
84c8c8a6dcfbb2b25a70fdd4463e1798033cd7c4
core/componentmanager.lua
core/componentmanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local core_route_stanza = core_route_stanza; local jid_split = require "util.jid".split; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local serialize = require "util.serialization".serialize local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; prosody.events.add_handler("server-starting", function () core_route_stanza = _G.core_route_stanza; end); module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" then core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end local components_loaded_once; function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = { type = "component", host = host, connected = false, s2sout = {}, events = events_new() }; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: " .. (stanza.attr.to or serialize(stanza))); end end function create_component(host, component) -- TODO check for host well-formedness return { type = "component", host = host, connected = true, s2sout = {}, events = events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end -- FIXME only load for a.b.c if b.c has dialback, and/or check in config modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local core_route_stanza = core_route_stanza; local jid_split = require "util.jid".split; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; prosody.events.add_handler("server-starting", function () core_route_stanza = _G.core_route_stanza; end); module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" then core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end local components_loaded_once; function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = { type = "component", host = host, connected = false, s2sout = {}, events = events_new() }; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza)); end end function create_component(host, component) -- TODO check for host well-formedness return { type = "component", host = host, connected = true, s2sout = {}, events = events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end -- FIXME only load for a.b.c if b.c has dialback, and/or check in config modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
ComponentManager: Fixed a bit of logging.
ComponentManager: Fixed a bit of logging.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
59cd41e49745cbd0538dfb7ca39d12a92d8cc917
core/portmanager.lua
core/portmanager.lua
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = set.new(config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do close(interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do close(interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
portmanager: Fix selecting bind_interfaces from pre-0.9 config options.
portmanager: Fix selecting bind_interfaces from pre-0.9 config options.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
740b91533dadee1cfa4f69a16d5a2528ac5c4375
lualib/http/internal.lua
lualib/http/internal.lua
local table = table local type = type local sockethelper = require "http.sockethelper" local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end if #header > LIMIT then return end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end function M.request(interface, method, host, url, recvheader, header, content) local is_ws = interface.websocket local read = interface.read local write = interface.write local header_content = "" if header then if not header.host then header.host = host end for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end else header_content = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%sContent-length:%d\r\n\r\n", method, url, header_content, #content) write(data) write(content) else local request_header = string.format("%s %s HTTP/1.1\r\n%sContent-length:0\r\n\r\n", method, url, header_content) write(request_header) end local tmpline = {} local body = M.recvheader(read, tmpline, "") if not body then error(sockethelper.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = M.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = M.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end elseif code == 204 or code == 304 or code < 200 then body = "" -- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response elseif is_ws and code == 101 then -- if websocket handshake success return code, body else -- no content-length, read all body = body .. interface.readall() end end return code, body end return M
local table = table local type = type local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end if #header > LIMIT then return end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end function M.request(interface, method, host, url, recvheader, header, content) local is_ws = interface.websocket local read = interface.read local write = interface.write local header_content = "" if header then if not header.host then header.host = host end for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end else header_content = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%sContent-length:%d\r\n\r\n", method, url, header_content, #content) write(data) write(content) else local request_header = string.format("%s %s HTTP/1.1\r\n%sContent-length:0\r\n\r\n", method, url, header_content) write(request_header) end local tmpline = {} local body = M.recvheader(read, tmpline, "") if not body then error("Recv header failed") end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = M.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = M.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end elseif code == 204 or code == 304 or code < 200 then body = "" -- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response elseif is_ws and code == 101 then -- if websocket handshake success return code, body else -- no content-length, read all body = body .. interface.readall() end end return code, body end return M
Fix #1452
Fix #1452
Lua
mit
sanikoyes/skynet,korialuo/skynet,wangyi0226/skynet,cloudwu/skynet,xjdrew/skynet,xjdrew/skynet,cloudwu/skynet,wangyi0226/skynet,sanikoyes/skynet,wangyi0226/skynet,korialuo/skynet,xjdrew/skynet,korialuo/skynet,sanikoyes/skynet,cloudwu/skynet
94576ab5b56810bbeb025efc7091f60467e639f2
tests/lua/test.lua
tests/lua/test.lua
-- -- Created by IntelliJ IDEA. -- User: alex -- Date: 21/09/2015 -- Time: 16:22 -- To change this template use File | Settings | File Templates. -- local handle, msg if (not python) then -- LUA -> PYTHON - LUA handle, msg = loadlib(getenv("LIBRARY_PATH")) if (not handle or handle == -1) then error(msg) end callfromlib(handle, 'luaopen_python') assert(python, "undefined python object") -- python home python.system_init("C:\\Python27"); end print(format("python ext <%s> is embedded in lua <%s>", python.get_version(), tostring(python.is_embedded()))) local builtins = python.builtins() local os = python.import("os") local str = "maçã" assert(builtins.unicode(str, 'utf-8') == str) local types = python.import("types") assert(builtins.isinstance(python.None, types.NoneType), "None type check error") assert(builtins.isinstance(python.False, types.BooleanType), "False type check error") assert(builtins.isinstance(python.True, types.BooleanType), "True type check error") assert(builtins.bool(python.None) == nil, "None object check error") assert(builtins.bool(python.False) == nil, "False boolean check error") assert(builtins.bool(python.True) == 1, "True boolean check error") local sys = python.import("sys") local index = builtins.len(sys.path) print("Python sys.path") while (index > 0) do print(index, sys.path[index - 1]) index = index - 1 end local globals = python.globals() assert(type(globals) == "userdata", "globals is not a table") local builtins = python.builtins() assert(type(builtins) == "userdata", "builtins is not a table") python.execute('import sys') local sys = python.eval("sys") sys.MYVAR = 100 local path = "/user/local" sys.path[0] = path assert(python.eval("sys.MYVAR") == 100, "set attribute error") assert(python.eval("sys.path[0]") == path, "set index error") local string = [[ Lua is an extension programming language designed to support general procedural programming with data description facilities. Lua also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, lightweight, embeddable scripting language for any program that needs one. Lua is implemented as a library, written in clean C, the common subset of Standard C and C++. ]] assert(builtins.len(string) == strlen(string)) local struct = python.import("struct") local bstr = struct.pack('hhl', 1, 2, 3) local temfile = python.import("tempfile") local filepath = os.path.join(temfile.gettempdir(), "tempfiletext.bin") local file = builtins.open(filepath, "wb") file.write(bstr) file.close() local res = struct.unpack('hhl', builtins.open(filepath, "rb").read()) assert(res[0] == 1, "binary string no match") assert(res[1] == 2, "binary string no match") assert(res[2] == 3, "binary string no match") python.execute('import json') local loadjson = python.eval([[json.loads('{"a": 100, "b": 2000, "c": 300, "items": 100}')]]) assert(type(loadjson) == "table") assert(loadjson["a"] == 100) assert(loadjson["b"] == 2000) assert(loadjson["c"] == 300) assert(loadjson["items"] == 100, "key 'items' not found") local filename = "data.json" local path = python.import("os").path assert(path.exists(filename) == nil or path.exists(filename) == 1, "file does not exists") if (python.import("os.path").exists(filename)) then local filedata = builtins.open(filename).read() assert(builtins.len(filedata) > 0, "file size is zero") end local dict = python.eval("{'a': 'a value'}") local keys = python.asattr(dict).keys() assert(python.str(keys) == "['a']", "dict repr object error") assert(builtins.len(keys) == 1, "dict size no match") assert(keys[0] == 'a', "dict key no match") local list = python.eval("[1,2,3,3]") local lsize = builtins.len(list) assert(list[0] == 1, "list by index invalid value") assert(python.asattr(list).pop(0) == 1, "list pop invalid value") assert(lsize - 1 == builtins.len(list), "size of unexpected list") local re = python.import('re') local pattern = re.compile("Hel(lo) world!") local match = pattern.match("Hello world!") assert(builtins.len(match.groups()) > 0, "patten without groups") assert(match.group(1) == "lo", "group value no match") local jsond = '["a", "b", "c"]' local json = python.import('json') assert(json.loads(jsond)[0] == 'a', "json parsed list 0 index invalid value") assert(json.loads(jsond)[1] == 'b', "json parsed list 1 index invalid value") assert(json.loads(jsond)[2] == 'c', "json parsed list 2 index invalid value") assert(python.eval("1") == 1, "eval int no match") assert(python.eval("1.0001") == 1.0001, "eval float no match") python.execute([[ def fn_args(arg): assert len(arg) == 5, "no args!" ]]) python.eval("fn_args")({sys, string, re, list, pattern}) python.execute([[ def fn_kwargs(arg): for name in ['sys', 'string', 'list', 're', 'pattern']: assert arg[name], "arg: %s missing!" % (name,) ]]) python.eval("fn_kwargs")({sys=sys, string=string, re=re, list=list, pattern=pattern}) -- special case local dict = builtins.dict() dict[os] = "os module" dict[sys] = "sys module" dict["str"] = "simple str" assert(dict[sys] and dict[os]) local string = python.import("string") assert(string.split("1", ",")[0] == "1") -- Ends the Python interpreter, freeing resources to OS if (python.is_embedded()) then python.system_exit() end
-- -- Created by IntelliJ IDEA. -- User: alex -- Date: 21/09/2015 -- Time: 16:22 -- To change this template use File | Settings | File Templates. -- local handle, msg if (not python) then -- LUA -> PYTHON - LUA handle, msg = loadlib(getenv("LIBRARY_PATH")) if (not handle or handle == -1) then error(msg) end callfromlib(handle, 'luaopen_python') assert(python, "undefined python object") -- python home python.system_init("C:\\Python27"); end print(format("python ext <%s> is embedded in lua <%s>", python.get_version(), tostring(python.is_embedded()))) local builtins = python.builtins() local os = python.import("os") local str = "maçã" assert(builtins.unicode(str, 'utf-8') == str) local types = python.import("types") assert(builtins.isinstance(python.None, types.NoneType), "None type check error") assert(builtins.isinstance(python.False, types.BooleanType), "False type check error") assert(builtins.isinstance(python.True, types.BooleanType), "True type check error") assert(builtins.bool(python.None) == nil, "None object check error") assert(builtins.bool(python.False) == nil, "False boolean check error") assert(builtins.bool(python.True) == 1, "True boolean check error") local sys = python.import("sys") local index = builtins.len(sys.path) print("Python sys.path") while (index > 0) do print(index, sys.path[index - 1]) index = index - 1 end local globals = python.globals() assert(type(globals) == "userdata", "globals is not a table") local builtins = python.builtins() assert(type(builtins) == "userdata", "builtins is not a table") python.execute('import sys') local sys = python.eval("sys") sys.MYVAR = 100 local path = "/user/local" sys.path[0] = path assert(python.eval("sys.MYVAR") == 100, "set attribute error") assert(python.eval("sys.path[0]") == path, "set index error") local string = [[ Lua is an extension programming language designed to support general procedural programming with data description facilities. Lua also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, lightweight, embeddable scripting language for any program that needs one. Lua is implemented as a library, written in clean C, the common subset of Standard C and C++. ]] assert(builtins.len(string) == strlen(string), "strlen no match") local struct = python.import("struct") local bstr = struct.pack('hhl', 1, 2, 3) local temfile = python.import("tempfile") local filepath = os.path.join(temfile.gettempdir(), "tempfiletext.bin") local file = builtins.open(filepath, "wb") file.write(bstr) file.close() local res = struct.unpack('hhl', builtins.open(filepath, "rb").read()) assert(res[0] == 1, "binary string no match") assert(res[1] == 2, "binary string no match") assert(res[2] == 3, "binary string no match") python.execute('import json') local loadjson = python.eval([[json.loads('{"a": 100, "b": 2000, "c": 300, "items": 100}')]]) assert(type(loadjson) == "userdata", "json type error") assert(loadjson["a"] == 100) assert(loadjson["b"] == 2000) assert(loadjson["c"] == 300) assert(loadjson["items"] == 100, "key 'items' not found") local filename = "data.json" local path = python.import("os").path assert(path.exists(filename) == nil or path.exists(filename) == 1, "file does not exists") if (python.import("os.path").exists(filename)) then local filedata = builtins.open(filename).read() assert(builtins.len(filedata) > 0, "file size is zero") end local dict = python.eval("{'a': 'a value'}") local keys = python.asattr(dict).keys() assert(python.str(keys) == "['a']", "dict repr object error") assert(builtins.len(keys) == 1, "dict size no match") assert(keys[0] == 'a', "dict key no match") local list = python.eval("[1,2,3,3]") local lsize = builtins.len(list) assert(list[0] == 1, "list by index invalid value") assert(python.asattr(list).pop(0) == 1, "list pop invalid value") assert(lsize - 1 == builtins.len(list), "size of unexpected list") local re = python.import('re') local pattern = re.compile("Hel(lo) world!") local match = pattern.match("Hello world!") assert(builtins.len(match.groups()) > 0, "patten without groups") assert(match.group(1) == "lo", "group value no match") local jsond = '["a", "b", "c"]' local json = python.import('json') assert(json.loads(jsond)[0] == 'a', "json parsed list 0 index invalid value") assert(json.loads(jsond)[1] == 'b', "json parsed list 1 index invalid value") assert(json.loads(jsond)[2] == 'c', "json parsed list 2 index invalid value") assert(python.eval("1") == 1, "eval int no match") assert(python.eval("1.0001") == 1.0001, "eval float no match") python.execute([[ def fn_args(arg): assert len(arg) == 5, "no args!" ]]) python.eval("fn_args")({sys, string, re, list, pattern}) python.execute([[ def fn_kwargs(arg): for name in ['sys', 'string', 'list', 're', 'pattern']: assert arg[name], "arg: %s missing!" % (name,) ]]) python.eval("fn_kwargs")({sys=sys, string=string, re=re, list=list, pattern=pattern}) -- special case local dict = builtins.dict() dict[os] = "os module" dict[sys] = "sys module" dict["str"] = "simple str" assert(dict[sys] and dict[os]) local string = python.import("string") assert(string.split("1", ",")[0] == "1") -- Ends the Python interpreter, freeing resources to OS if (python.is_embedded()) then python.system_exit() end
Fix assert messages.
Fix assert messages.
Lua
lgpl-2.1
alexsilva/lunatic-python,alexsilva/lunatic-python,alexsilva/lunatic-python
25abfb9476cac32d8db59b73f8bdfc60ba85ff79
MCServer/Plugins/MagicCarpet/plugin.lua
MCServer/Plugins/MagicCarpet/plugin.lua
local PLUGIN = {} local Carpets = {} function Initialize( Plugin ) PLUGIN = Plugin Plugin:SetName( "MagicCarpet" ) Plugin:SetVersion( 1 ) PluginManager = cRoot:Get():GetPluginManager() PluginManager:AddHook(Plugin, cPluginManager.HOOK_PLAYER_MOVING) PluginManager:AddHook(Plugin, cPluginManager.HOOK_DISCONNECT) PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet"); LOG( "Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() ) return true end function OnDisable() LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." ) for i, Carpet in pairs( Carpets ) do Carpet:remove() end end function HandleCarpetCommand( Split, Player ) Carpet = Carpets[ Player ] if( Carpet == nil ) then Carpets[ Player ] = cCarpet:new() Player:SendMessage("You're on a magic carpet!" ) else Carpet:remove() Carpets[ Player ] = nil Player:SendMessage("The carpet vanished!" ) end return true end function OnDisconnect( Reason, Player ) local Carpet = Carpets[ Player ] if( Carpet ~= nil ) then Carpet:remove() end Carpets[ Player ] = nil end function OnPlayerMoving(Player) local Carpet = Carpets[ Player ] if( Carpet == nil ) then return end if( Player:GetPitch() == 90 ) then Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) ) else if( Player:GetPosY() < Carpet:getY() ) then LOGINFO("Fell tru mc!") Player:TeleportTo( Player:GetPosX(), Carpet:getY(), Player:GetPosZ() ) end Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) ) end end
local PLUGIN = {} local Carpets = {} function Initialize( Plugin ) PLUGIN = Plugin Plugin:SetName( "MagicCarpet" ) Plugin:SetVersion( 1 ) PluginManager = cRoot:Get():GetPluginManager() PluginManager:AddHook(Plugin, cPluginManager.HOOK_PLAYER_MOVING) PluginManager:AddHook(Plugin, cPluginManager.HOOK_DISCONNECT) PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet"); LOG( "Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() ) return true end function OnDisable() LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." ) for i, Carpet in pairs( Carpets ) do Carpet:remove() end end function HandleCarpetCommand( Split, Player ) Carpet = Carpets[ Player ] if( Carpet == nil ) then Carpets[ Player ] = cCarpet:new() Player:SendMessage("You're on a magic carpet!" ) Player:SendMessage("Look straight down to descend. Jump to ascend!" ) else Carpet:remove() Carpets[ Player ] = nil Player:SendMessage("The carpet vanished!" ) end return true end function OnDisconnect( Reason, Player ) local Carpet = Carpets[ Player ] if( Carpet ~= nil ) then Carpet:remove() end Carpets[ Player ] = nil end function OnPlayerMoving(Player) local Carpet = Carpets[ Player ] if( Carpet == nil ) then return end if( Player:GetPitch() == 90 ) then Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) ) else if( Player:GetPosY() < Carpet:getY() ) then Player:TeleportToCoords(Player:GetPosX(), Carpet:getY(), Player:GetPosZ()) end Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) ) end end
Updated MagicCarpet to use new API [SEE DESC]
Updated MagicCarpet to use new API [SEE DESC] Fixed non-teleportation upon falling through carpet due to use of deprecated function. Fixed spam of console upon falling through carpet. Added descriptive upon-enable message.
Lua
apache-2.0
birkett/cuberite,tonibm19/cuberite,mc-server/MCServer,mjssw/cuberite,nicodinh/cuberite,zackp30/cuberite,nicodinh/cuberite,QUSpilPrgm/cuberite,bendl/cuberite,nevercast/cuberite,guijun/MCServer,Altenius/cuberite,jammet/MCServer,ionux/MCServer,zackp30/cuberite,SamOatesPlugins/cuberite,nevercast/cuberite,mmdk95/cuberite,electromatter/cuberite,Howaner/MCServer,linnemannr/MCServer,mjssw/cuberite,QUSpilPrgm/cuberite,electromatter/cuberite,HelenaKitty/EbooMC,mjssw/cuberite,jammet/MCServer,nounoursheureux/MCServer,nichwall/cuberite,linnemannr/MCServer,mc-server/MCServer,nounoursheureux/MCServer,Howaner/MCServer,marvinkopf/cuberite,mmdk95/cuberite,Fighter19/cuberite,birkett/cuberite,marvinkopf/cuberite,ionux/MCServer,mmdk95/cuberite,ionux/MCServer,Altenius/cuberite,electromatter/cuberite,Tri125/MCServer,MuhammadWang/MCServer,linnemannr/MCServer,guijun/MCServer,HelenaKitty/EbooMC,Frownigami1/cuberite,mc-server/MCServer,Howaner/MCServer,Haxi52/cuberite,HelenaKitty/EbooMC,ionux/MCServer,jammet/MCServer,Haxi52/cuberite,nounoursheureux/MCServer,MuhammadWang/MCServer,mmdk95/cuberite,SamOatesPlugins/cuberite,Schwertspize/cuberite,Howaner/MCServer,guijun/MCServer,nichwall/cuberite,zackp30/cuberite,HelenaKitty/EbooMC,nichwall/cuberite,QUSpilPrgm/cuberite,Howaner/MCServer,bendl/cuberite,mjssw/cuberite,kevinr/cuberite,kevinr/cuberite,SamOatesPlugins/cuberite,nevercast/cuberite,Frownigami1/cuberite,Altenius/cuberite,birkett/cuberite,Fighter19/cuberite,mjssw/cuberite,johnsoch/cuberite,kevinr/cuberite,mc-server/MCServer,Schwertspize/cuberite,marvinkopf/cuberite,Fighter19/cuberite,marvinkopf/cuberite,birkett/MCServer,bendl/cuberite,mc-server/MCServer,Altenius/cuberite,birkett/MCServer,nicodinh/cuberite,nevercast/cuberite,guijun/MCServer,nicodinh/cuberite,thetaeo/cuberite,jammet/MCServer,nicodinh/cuberite,nevercast/cuberite,Tri125/MCServer,Frownigami1/cuberite,QUSpilPrgm/cuberite,Frownigami1/cuberite,birkett/MCServer,mc-server/MCServer,johnsoch/cuberite,tonibm19/cuberite,QUSpilPrgm/cuberite,QUSpilPrgm/cuberite,nichwall/cuberite,thetaeo/cuberite,Tri125/MCServer,nounoursheureux/MCServer,birkett/cuberite,MuhammadWang/MCServer,guijun/MCServer,thetaeo/cuberite,Tri125/MCServer,SamOatesPlugins/cuberite,Haxi52/cuberite,Schwertspize/cuberite,Fighter19/cuberite,tonibm19/cuberite,kevinr/cuberite,thetaeo/cuberite,tonibm19/cuberite,electromatter/cuberite,zackp30/cuberite,nevercast/cuberite,kevinr/cuberite,Howaner/MCServer,ionux/MCServer,linnemannr/MCServer,zackp30/cuberite,birkett/cuberite,electromatter/cuberite,mmdk95/cuberite,jammet/MCServer,Haxi52/cuberite,thetaeo/cuberite,HelenaKitty/EbooMC,guijun/MCServer,nounoursheureux/MCServer,mjssw/cuberite,thetaeo/cuberite,zackp30/cuberite,SamOatesPlugins/cuberite,MuhammadWang/MCServer,birkett/cuberite,electromatter/cuberite,MuhammadWang/MCServer,Haxi52/cuberite,johnsoch/cuberite,nichwall/cuberite,jammet/MCServer,ionux/MCServer,Tri125/MCServer,kevinr/cuberite,linnemannr/MCServer,marvinkopf/cuberite,Haxi52/cuberite,birkett/MCServer,tonibm19/cuberite,Altenius/cuberite,johnsoch/cuberite,Schwertspize/cuberite,mmdk95/cuberite,bendl/cuberite,Fighter19/cuberite,birkett/MCServer,marvinkopf/cuberite,Fighter19/cuberite,nounoursheureux/MCServer,nichwall/cuberite,Frownigami1/cuberite,johnsoch/cuberite,linnemannr/MCServer,tonibm19/cuberite,nicodinh/cuberite,bendl/cuberite,Schwertspize/cuberite,Tri125/MCServer,birkett/MCServer
88e841d86941bbdcc8203eae01998fd0dbc951fd
Interface/AddOns/RayUI/modules/misc/durability.lua
Interface/AddOns/RayUI/modules/misc/durability.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local M = R:GetModule("Misc") local mod = M:NewModule("Durability", "AceEvent-3.0") --Cache global variables --Lua functions local _G = _G local pairs, math, string, rawget, select = pairs, math, string, rawget, select --WoW API / Variables local CreateFrame = CreateFrame local GetInventoryItemDurability = GetInventoryItemDurability local GetInventoryItemLink = GetInventoryItemLink local GetDetailedItemLevelInfo = GetDetailedItemLevelInfo local GetItemInfo = GetItemInfo local GetItemQualityColor = GetItemQualityColor --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: LE_ITEM_QUALITY_ARTIFACT, INVSLOT_OFFHAND, INVSLOT_MAINHAND local SLOTIDS, LEFT_SLOT = {}, {} for _, slot in pairs({"Head","Neck","Shoulder","Shirt","Chest","Waist","Legs","Feet","Wrist","Hands","Finger0","Finger1","Trinket0","Trinket1","Back","MainHand","SecondaryHand","Tabard"}) do SLOTIDS[slot] = GetInventorySlotInfo(slot .. "Slot") end for _, slot in pairs({ 1, 2, 3, 4, 5, 9, 15, 17, 19 }) do LEFT_SLOT[slot] = true end local frame = CreateFrame("Frame", nil, CharacterFrame) local function RYGColorGradient(perc) local relperc = perc*2 % 1 if perc <= 0 then return 1, 0, 0 elseif perc < 0.5 then return 1, relperc, 0 elseif perc == 0.5 then return 1, 1, 0 elseif perc < 1.0 then return 1 - relperc, 1, 0 else return 0, 1, 0 end end local itemLevel = setmetatable({}, { __index = function(t,i) local gslot = _G["Character"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, 0) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, 0) end t[i] = text return text end, }) local inspectItemLevel = setmetatable({}, { __index = function(t,i) local gslot = _G["Inspect"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, 0) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, 0) end t[i] = text return text end, }) local durability = setmetatable({}, { __index = function(t,i) local gslot = _G["Character"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, -10) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, -10) end t[i] = text return text end, }) function mod:UpdateDurability() local min = 1 for slot, id in pairs(SLOTIDS) do local v1, v2 = GetInventoryItemDurability(id) if v1 and v2 and v2 ~= 0 then min = math.min(v1/v2, min) local text = durability[slot] if not text then return end text:SetTextColor(RYGColorGradient(v1/v2)) text:SetText(string.format("%d%%", v1/v2*100)) else local text = rawget(durability, slot) if not text then return end if text then text:SetText(nil) end end end local r, g, b = RYGColorGradient(min) end function mod:UpdateItemlevel(event) local t = itemLevel local unit = "player" if event == "INSPECT_READY" then unit = "target" t = inspectItemLevel end for slot, id in pairs(SLOTIDS) do local text = t[slot] if not text then return end text:SetText("") local clink = GetInventoryItemLink(unit, id) if clink then local iLvl = GetDetailedItemLevelInfo(clink) local rarity = select(3, GetItemInfo(clink)) if iLvl and rarity then if iLvl == 750 and rarity == LE_ITEM_QUALITY_ARTIFACT and id == INVSLOT_OFFHAND then iLvl = GetDetailedItemLevelInfo(GetInventoryItemLink(unit, INVSLOT_MAINHAND)) end local r, g, b = GetItemQualityColor(rarity) text:SetText(iLvl) text:SetTextColor(r, g, b) end end end end function mod:Initialize() self:RegisterEvent("ADDON_LOADED", "UpdateDurability") self:RegisterEvent("UPDATE_INVENTORY_DURABILITY", "UpdateDurability") self:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", "UpdateItemlevel") self:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateItemlevel") self:RegisterEvent("INSPECT_READY", "UpdateItemlevel") end M:RegisterMiscModule(mod:GetName())
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local M = R:GetModule("Misc") local mod = M:NewModule("Durability", "AceEvent-3.0") --Cache global variables --Lua functions local _G = _G local pairs, math, string, rawget, select = pairs, math, string, rawget, select --WoW API / Variables local CreateFrame = CreateFrame local GetInventoryItemDurability = GetInventoryItemDurability local GetInventoryItemLink = GetInventoryItemLink local GetDetailedItemLevelInfo = GetDetailedItemLevelInfo local GetItemInfo = GetItemInfo local GetItemQualityColor = GetItemQualityColor local GetInventorySlotInfo = GetInventorySlotInfo --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: LE_ITEM_QUALITY_ARTIFACT, INVSLOT_OFFHAND, INVSLOT_MAINHAND local SLOTIDS, LEFT_SLOT = {}, {} local function RYGColorGradient(perc) local relperc = perc*2 % 1 if perc <= 0 then return 1, 0, 0 elseif perc < 0.5 then return 1, relperc, 0 elseif perc == 0.5 then return 1, 1, 0 elseif perc < 1.0 then return 1 - relperc, 1, 0 else return 0, 1, 0 end end local itemLevel = setmetatable({}, { __index = function(t,i) local gslot = _G["Character"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, 0) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, 0) end t[i] = text return text end, }) local inspectItemLevel = setmetatable({}, { __index = function(t,i) local gslot = _G["Inspect"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, 0) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, 0) end t[i] = text return text end, }) local durability = setmetatable({}, { __index = function(t,i) local gslot = _G["Character"..i.."Slot"] if not gslot then return nil end local text = gslot:CreateFontString(nil, "OVERLAY") text:SetFont(R["media"].pxfont, 10*R.mult, "THINOUTLINE,MONOCHROME") text:SetShadowColor(0, 0, 0) text:SetShadowOffset(R.mult, -R.mult) if LEFT_SLOT[SLOTIDS[i]] then text:Point("TOPLEFT", gslot, "TOPRIGHT", 3, -10) else text:Point("TOPRIGHT", gslot, "TOPLEFT", -2, -10) end t[i] = text return text end, }) function mod:UpdateDurability(event) local min = 1 for slot, id in pairs(SLOTIDS) do local v1, v2 = GetInventoryItemDurability(id) local text = durability[slot] text:SetText("") if v1 and v2 and v2 ~= 0 then min = math.min(v1/v2, min) if not text then return end text:SetTextColor(RYGColorGradient(v1/v2)) text:SetText(string.format("%d%%", v1/v2*100)) end end local r, g, b = RYGColorGradient(min) end function mod:UpdateItemlevel(event) local t = itemLevel local unit = "player" if event == "INSPECT_READY" then unit = "target" t = inspectItemLevel end for slot, id in pairs(SLOTIDS) do local text = t[slot] if not text then return end text:SetText("") local clink = GetInventoryItemLink(unit, id) if clink then local iLvl = GetDetailedItemLevelInfo(clink) local rarity = select(3, GetItemInfo(clink)) if iLvl and rarity then if iLvl == 750 and rarity == LE_ITEM_QUALITY_ARTIFACT and id == INVSLOT_OFFHAND then iLvl = GetDetailedItemLevelInfo(GetInventoryItemLink(unit, INVSLOT_MAINHAND)) end local r, g, b = GetItemQualityColor(rarity) text:SetText(iLvl) text:SetTextColor(r, g, b) end end end end function mod:PLAYER_ENTERING_WORLD() self:UpdateDurability() self:UpdateItemlevel() end function mod:Initialize() for _, slot in pairs({"Head","Neck","Shoulder","Shirt","Chest","Waist","Legs","Feet","Wrist","Hands","Finger0","Finger1","Trinket0","Trinket1","Back","MainHand","SecondaryHand","Tabard"}) do SLOTIDS[slot] = GetInventorySlotInfo(slot .. "Slot") end for _, slot in pairs({ 1, 2, 3, 4, 5, 9, 15, 17, 19 }) do LEFT_SLOT[slot] = true end self:RegisterEvent("UPDATE_INVENTORY_DURABILITY", "UpdateDurability") self:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", "UpdateItemlevel") self:RegisterEvent("PLAYER_ENTERING_WORLD") self:RegisterEvent("INSPECT_READY", "UpdateItemlevel") end M:RegisterMiscModule(mod:GetName())
fix an issue that cause durability text not shown
fix an issue that cause durability text not shown
Lua
mit
fgprodigal/RayUI
2dd6dcaf403c0f17a850c7bc2e84e5e4f576d303
packages/frametricks.lua
packages/frametricks.lua
local breakFrameVertical = function(after) local cFrame = SILE.typesetter.frame if after then totalHeight = after else totalHeight = 0 SILE.typesetter:leaveHmode(1) local q = SILE.typesetter.state.outputQueue for i=1,#q do totalHeight = totalHeight + q[i].height + q[i].depth end SILE.typesetter:chuck() end if type(totalHeight) == "table" then totalHeight= totalHeight.length end local newFrame = SILE.newFrame({ bottom = cFrame:bottom(), left = cFrame:left(), right = cFrame:right(), next = cFrame.next, previous = cFrame, id = cFrame.id .. "'" }) cFrame._height = totalHeight cFrame.next = newFrame.id SILE.documentState.thisPageTemplate.frames[newFrame.id] = newFrame newFrame._top = cFrame:top() + totalHeight if (after) then SILE.typesetter:initFrame(cFrame) else SILE.typesetter:initFrame(newFrame) end -- SILE.outputter:debugFrame(cFrame) -- SILE.outputter:debugFrame(newFrame) end local breakFrameHorizontalAt = function (offset) local cFrame = SILE.typesetter.frame local newFrame = SILE.newFrame({ bottom = cFrame:bottom(), top = cFrame:top(), left = cFrame:left() + offset, right = cFrame:right(), next = cFrame.next, previous = cFrame, id = cFrame.id .. "'" }) local oldLeft = cFrame:left() cFrame.left = (function() return oldLeft end) cFrame.right = (function() return oldLeft + offset end) -- SILE.outputter:debugFrame(cFrame) -- SILE.outputter:debugFrame(newFrame) SILE.typesetter:initFrame(newFrame) end local shiftframeedge = function(frame, options) if options.left then local oldLeft = frame.left frame.left = function() return oldLeft(frame) + SILE.length.parse(options.left).length end end if options.right then local oldRight = frame.right frame.right = function() return oldRight(frame) + SILE.length.parse(options.right).length end end end SILE.registerCommand("shiftframeedge", function(options, content) local cFrame = SILE.typesetter.frame shiftframeedge(cFrame, options) SILE.typesetter:initFrame(cFrame) --SILE.outputter:debugFrame(cFrame) end) SILE.registerCommand("breakframevertical", function ( options, content ) breakFrameVertical() end) SILE.registerCommand("breakframehorizontal", function ( options, content ) breakFrameHorizontalAt(SILE.length.parse(options.offset).length) end) SILE.registerCommand("dropcap", function(options, content) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) local hbox = SILE.Commands["hbox"]({}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back local t = {} t[1] = hbox local boundary = hbox.width.length + SILE.length.parse(options.rightboundary).length breakFrameHorizontalAt(boundary) SILE.typesetNaturally(SILE.typesetter.frame.previous, t) local undoSkip = SILE.length.new({}) - SILE.settings.get("document.baselineskip").height.length + SILE.length.parse("1ex") undoSkip.stretch = hbox.height SILE.typesetter:pushHbox({value = {}}) SILE.typesetter:pushVglue({height = undoSkip }) breakFrameVertical(hbox.height + SILE.length.parse(options.bottomboundary).length) shiftframeedge(SILE.getFrame(SILE.typesetter.frame.next), {left = ""..(SILE.length.new() - boundary)}) --SILE.outputter:debugFrame(SILE.typesetter.frame) SILE.settings.set("current.parindent", SILE.settings.get("document.parindent")) end) return { init = function () end, exports = { breakFrameVertical = breakFrameVertical } }
local breakFrameVertical = function(after) local cFrame = SILE.typesetter.frame if after then totalHeight = after else totalHeight = 0 SILE.typesetter:leaveHmode(1) local q = SILE.typesetter.state.outputQueue for i=1,#q do totalHeight = totalHeight + q[i].height + q[i].depth end SILE.typesetter:chuck() end if type(totalHeight) == "table" then totalHeight= totalHeight.length end local newFrame = SILE.newFrame({ bottom = cFrame:bottom(), left = cFrame:left(), right = cFrame:right(), next = cFrame.next, previous = cFrame, id = cFrame.id .. "'" }) cFrame._height = totalHeight cFrame.next = newFrame.id SILE.documentState.thisPageTemplate.frames[newFrame.id] = newFrame newFrame._top = cFrame:top() + totalHeight if (after) then SILE.typesetter:initFrame(cFrame) else SILE.typesetter:initFrame(newFrame) end -- SILE.outputter:debugFrame(cFrame) -- SILE.outputter:debugFrame(newFrame) end local breakFrameHorizontalAt = function (offset) local cFrame = SILE.typesetter.frame local newFrame = SILE.newFrame({ bottom = cFrame:bottom(), top = cFrame:top(), left = cFrame:left() + offset, right = cFrame:right(), next = cFrame.next, previous = cFrame, id = cFrame.id .. "'" }) local oldLeft = cFrame:left() cFrame.left = (function() return oldLeft end) cFrame.right = (function() return oldLeft + offset end) -- SILE.outputter:debugFrame(cFrame) -- SILE.outputter:debugFrame(newFrame) SILE.typesetter:initFrame(newFrame) end local shiftframeedge = function(frame, options) if options.left then local oldLeft = frame.left frame.left = function() return oldLeft(frame) + SILE.length.parse(options.left).length end end if options.right then local oldRight = frame.right frame.right = function() return oldRight(frame) + SILE.length.parse(options.right).length end end end SILE.registerCommand("shiftframeedge", function(options, content) local cFrame = SILE.typesetter.frame shiftframeedge(cFrame, options) SILE.typesetter:initFrame(cFrame) --SILE.outputter:debugFrame(cFrame) end, "Adjusts the edge of the frame horizontally by amounts specified in <left> and <right>") SILE.registerCommand("breakframevertical", function ( options, content ) breakFrameVertical() end, "Breaks the current frame in two vertically at the current location") SILE.registerCommand("breakframehorizontal", function ( options, content ) breakFrameHorizontalAt(SILE.length.parse(options.offset).length) end, "Breaks the current frame in two horizontally either at the current location or at a point <offset> below the current location") SILE.registerCommand("float", function(options, content) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) local hbox = SILE.Commands["hbox"]({}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back local t = {} t[1] = hbox local boundary = hbox.width.length + SILE.length.parse(options.rightboundary).length breakFrameHorizontalAt(boundary) SILE.typesetNaturally(SILE.typesetter.frame.previous, t) local undoSkip = SILE.length.new({}) - SILE.settings.get("document.baselineskip").height.length + SILE.length.parse("1ex") undoSkip.stretch = hbox.height SILE.typesetter:pushHbox({value = {}}) SILE.typesetter:pushVglue({height = undoSkip }) breakFrameVertical(hbox.height + SILE.length.parse(options.bottomboundary).length) shiftframeedge(SILE.getFrame(SILE.typesetter.frame.next), {left = ""..(SILE.length.new() - boundary)}) --SILE.outputter:debugFrame(SILE.typesetter.frame) SILE.settings.set("current.parindent", SILE.settings.get("document.parindent")) end, "Sets the given content in its own frame, flowing the remaining content around it") return { init = function () end, exports = { breakFrameVertical = breakFrameVertical } }
Fix up documentation.
Fix up documentation.
Lua
mit
Nathan22Miles/sile,Nathan22Miles/sile,shirat74/sile,alerque/sile,neofob/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,neofob/sile,shirat74/sile,anthrotype/sile,Nathan22Miles/sile,simoncozens/sile,simoncozens/sile,alerque/sile,simoncozens/sile,simoncozens/sile,WAKAMAZU/sile_fe,neofob/sile,anthrotype/sile,alerque/sile,WAKAMAZU/sile_fe,anthrotype/sile,shirat74/sile,anthrotype/sile,Nathan22Miles/sile,shirat74/sile,WAKAMAZU/sile_fe,neofob/sile,alerque/sile
886d2609c713c882b242e56f57a8a9fdf232c446
Engine/coreg.lua
Engine/coreg.lua
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={}} local basexx = require("Engine.basexx") local bit = require("bit") --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co, self.coglob end --Sets the current active coroutine function coreg:setCoroutine(co,glob) self.co = co self.coglob = glob return self end local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,...)} if not args[1] then error(args[2]) end --Should have a better error handelling if not args[2] then --if self.co:status() == "dead" then error("done") return end --OS finished ?? --self:resumeCoroutine() self.co = nil return end args = {self:trigger(args[2],unpack(extractArgs(args,2)))} if not args[1] then self:resumeCoroutine(args[1],unpack(extractArgs(args,1))) end if not(type(args[1]) == "number" and args[1] == 2) then self:resumeCoroutine(true,unpack(extractArgs(args,1))) end end function coreg:sandbox(f) if self.co and self.coglob then setfenv(f,self.coglob) return end local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, getfenv=getfenv, setfenv=setfenv, setmetatable=setmetatable, getmetatable=getmetatable, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort, concat=table.concat }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise, --LOVE releated apis b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11 b64dec = basexx.from_base64, hexenc = basexx.to_hex, hexdec = basexx.from_hex, compress = function(...) return love.math.compress(...):getString() end, decompress = love.math.decompress }, coroutine={ resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock }, bit={ cast=bit.cast, bnot=bit.bnot, band=bit.band, bor=bit.bor, bxor=bit.bxor, lshift=bit.lshift, rshift=bit.rshift, arshift=bit.arshift, tobit=bit.tobit, tohex=bit.tohex, rol=bit.rol, ror=bit.ror, bswap=bit.swap } } GLOB.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.create = function(chunk) --if type(chunk) == "function" then setfenv(chunk,GLOB) end local ok,co = pcall(coroutine.create,chunk) if not ok then return error(co) end return co end GLOB.coroutine.sethook = function(co,...) if type(co) ~= "thread" then return error("wrong argument #1 (thread expected, got "..type(co)..")") end local ok, err = pcall(debug.sethook,co,...) if not ok then return error(err) end return err end GLOB._G=GLOB --Mirror Mirror setfenv(f,GLOB) return GLOB end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={}} local basexx = require("Engine.basexx") local bit = require("bit") --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co, self.coglob end --Sets the current active coroutine function coreg:setCoroutine(co,glob) self.co = co self.coglob = glob return self end local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) local lastargs = {...} while true do if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,unpack(lastargs))} if not args[1] then error(args[2]) end --Should have a better error handelling if not args[2] then --if self.co:status() == "dead" then error("done") return end --OS finished ?? --self:resumeCoroutine() self.co = nil return end args = {self:trigger(args[2],unpack(extractArgs(args,2)))} if not args[1] then lastargs = {args[1],unpack(extractArgs(args,1))} elseif not(type(args[1]) == "number" and args[1] == 2) then lastargs = {true,unpack(extractArgs(args,1))} else break end end end function coreg:sandbox(f) if self.co and self.coglob then setfenv(f,self.coglob) return end local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, getfenv=getfenv, setfenv=setfenv, setmetatable=setmetatable, getmetatable=getmetatable, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort, concat=table.concat }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise, --LOVE releated apis b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11 b64dec = basexx.from_base64, hexenc = basexx.to_hex, hexdec = basexx.from_hex, compress = function(...) return love.math.compress(...):getString() end, decompress = love.math.decompress }, coroutine={ resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock }, bit={ cast=bit.cast, bnot=bit.bnot, band=bit.band, bor=bit.bor, bxor=bit.bxor, lshift=bit.lshift, rshift=bit.rshift, arshift=bit.arshift, tobit=bit.tobit, tohex=bit.tohex, rol=bit.rol, ror=bit.ror, bswap=bit.swap } } GLOB.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.create = function(chunk) --if type(chunk) == "function" then setfenv(chunk,GLOB) end local ok,co = pcall(coroutine.create,chunk) if not ok then return error(co) end return co end GLOB.coroutine.sethook = function(co,...) if type(co) ~= "thread" then return error("wrong argument #1 (thread expected, got "..type(co)..")") end local ok, err = pcall(debug.sethook,co,...) if not ok then return error(err) end return err end GLOB._G=GLOB --Mirror Mirror setfenv(f,GLOB) return GLOB end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
Fixed a serios stupid bug (stack overflow)
Fixed a serios stupid bug (stack overflow)
Lua
mit
RamiLego4Game/LIKO-12