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
0141ed07de34b89d5a709d1d33515292abfb07b3
kong/db/migrations/core/007_140_to_200.lua
kong/db/migrations/core/007_140_to_200.lua
return { postgres = { up = [[ -- If migrating from 1.x, the "path_handling" column does not exist yet. -- Create it with a default of 'v1' to fill existing rows, then change the default. DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "path_handling" TEXT DEFAULT 'v1'; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ALTER TABLE IF EXISTS ONLY "routes" ALTER COLUMN "path_handling" SET DEFAULT 'v0'; ]], teardown = function(connector) assert(connector:query([[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "plugins" DROP COLUMN "run_on"; EXCEPTION WHEN UNDEFINED_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN DROP TABLE IF EXISTS "cluster_ca"; END; $$; ]])) end, }, cassandra = { up = [[ ALTER TABLE routes ADD path_handling text; ]], teardown = function(connector) local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate([[SELECT * FROM routes]]) do if err then return nil, err end for _, row in ipairs(rows) do if row.path_handling ~= "v0" then assert(connector:query([[ UPDATE routes SET path_handling = 'v1' WHERE partition = 'routes' AND id = ]] .. row.id)) end end end assert(connector:query([[ DROP INDEX IF EXISTS plugins_run_on_idx; ALTER TABLE plugins DROP run_on; DROP TABLE IF EXISTS cluster_ca; ]])) end, }, }
return { postgres = { up = [[ -- If migrating from 1.x, the "path_handling" column does not exist yet. -- Create it with a default of 'v1' to fill existing rows, then change the default. DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "path_handling" TEXT DEFAULT 'v1'; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ALTER TABLE IF EXISTS ONLY "routes" ALTER COLUMN "path_handling" SET DEFAULT 'v0'; ]], teardown = function(connector) assert(connector:query([[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "plugins" DROP COLUMN "run_on"; EXCEPTION WHEN UNDEFINED_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN DROP TABLE IF EXISTS "cluster_ca"; END; $$; ]])) end, }, cassandra = { up = [[ ALTER TABLE routes ADD path_handling text; ]], teardown = function(connector) local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate([[SELECT * FROM routes]]) do if err then return nil, err end for _, row in ipairs(rows) do if row.path_handling ~= "v0" then assert(connector:query([[ UPDATE routes SET path_handling = 'v1' WHERE partition = 'routes' AND id = ]] .. row.id)) end end end assert(connector:query([[ DROP INDEX IF EXISTS plugins_run_on_idx; DROP TABLE IF EXISTS cluster_ca; ]])) -- no need to drop the actual row from the database -- (this operation is not reentrant in Cassandra) --[===[ assert(connector:query([[ ALTER TABLE plugins DROP run_on; ]])) ]===] end, }, }
hotfix(db) avoid non-reentrant operation in C* migration
hotfix(db) avoid non-reentrant operation in C* migration
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
11ff544594f4fceae45a885657921251ab7fa5d9
deps/semver.lua
deps/semver.lua
exports.name = "creationix/semver" exports.version = "1.0.2" local parse, normalize, match -- Make the module itself callable setmetatable(exports, { __call = function (_, ...) return match(...) end }) function parse(version) if not version then return end return assert(tonumber(string.match(version, "^v?(%d+)")), "Not a semver"), tonumber(string.match(version, "^v?%d+%.(%d+)") or 0), tonumber(string.match(version, "^v?%d+%.%d+%.(%d+)") or 0), tonumber(string.match(version, "^v?%d+%.%d+%.%d+-(%d+)") or 0) end exports.parse = parse function normalize(version) if not version then return "*" end local a, b, c, d = parse(version) return a .. '.' .. b .. '.' .. c .. (d and ('-' .. d) or ('')) end exports.normalize = normalize -- Return true is first is greater than ot equal to the second -- nil counts as lowest value in this case function exports.gte(first, second) if not second or first == second then return true end if not first then return false end local a, b, c, x = parse(second) local d, e, f, y = parse(first) return (d > a) or (d == a and (e > b or (e == b and (f > c or (y > x))))) end -- Sanity check for gte code assert(exports.gte(nil, nil)) assert(exports.gte("0.0.0", nil)) assert(exports.gte("9.9.9", "9.9.9")) assert(exports.gte("9.9.10", "9.9.9")) assert(exports.gte("9.10.0", "9.9.99")) assert(exports.gte("10.0.0", "9.99.99")) assert(exports.gte("10.0.0-1", "10.0.0-0")) assert(not exports.gte(nil, "0.0.0")) assert(not exports.gte("9.9.9", "9.9.10")) assert(not exports.gte("9.9.99", "9.10.0")) assert(not exports.gte("9.99.99", "10.0.0")) assert(not exports.gte("10.0.0-0", "10.0.0-1")) -- Given a semver string in the format a.b.c, and a list of versions in the -- same format, return the newest version that is compatable. This means for -- 0.b.c versions, 0.b.(>= c) will match, and for a.b.c, versions a.(>=b).* -- will match. function match(version, iterator) -- Major Minor Patch -- found a b c -- possible d e f -- minimum g h i local a, b, c if not version then -- With a n empty match, simply grab the newest version for possible in iterator do local d, e, f = parse(possible) if (not a) or (d > a) or (d == a and (e > b or (e == b and f > c))) then a, b, c = d, e, f end end else local g, h, i = parse(version) if g > 0 then -- From 1.0.0 and onward, minor updates are allowed since they mean non- -- breaking changes or additons. for possible in iterator do local d, e, f = parse(possible) if d == g and ((e == h and f >= i) or e > h) and ((not a) or e > b or (e == b and f > c)) then a, b, c = d, e, f end end else -- Before 1.0.0 we only allow patch updates assuming less stability at -- this period. for possible in iterator do local d, e, f = parse(possible) if d == g and e == h and f >= i and ((not a) or f > c) then a, b, c = d, e, f end end end end return a and (a .. '.' .. b .. '.' .. c) end exports.match = match local function iterator() local versions = {"0.0.1", "0.0.2", "0.1.0", "0.1.1", "0.2.0", "0.2.1", "1.0.0", "1.1.0", "1.1.3", "2.0.0", "2.1.2", "3.1.4"} local i = 0 return function () i = i + 1 return versions[i] end end -- Sanity check for match code assert(match("0.0.1", iterator()) == "0.0.2") assert(match("0.1.0", iterator()) == "0.1.1") assert(match("0.2.0", iterator()) == "0.2.1") assert(not match("0.3.0", iterator())) assert(match("1.0.0", iterator()) == "1.1.3") assert(not match("1.1.4", iterator())) assert(not match("1.2.0", iterator())) assert(match("2.0.0", iterator()) == "2.1.2") assert(not match("2.1.3", iterator())) assert(not match("2.2.0", iterator())) assert(match("3.0.0", iterator()) == "3.1.4") assert(not match("3.1.5", iterator())) assert(match(nil, iterator()) == "3.1.4")
exports.name = "creationix/semver" exports.version = "1.0.2" local parse, normalize, match -- Make the module itself callable setmetatable(exports, { __call = function (_, ...) return match(...) end }) function parse(version) if not version then return end return assert(tonumber(string.match(version, "^v?(%d+)")), "Not a semver"), tonumber(string.match(version, "^v?%d+%.(%d+)") or 0), tonumber(string.match(version, "^v?%d+%.%d+%.(%d+)") or 0), tonumber(string.match(version, "^v?%d+%.%d+%.%d+-(%d+)") or 0) end exports.parse = parse function normalize(version) if not version then return "*" end local a, b, c, d = parse(version) return a .. '.' .. b .. '.' .. c .. (d and ('-' .. d) or ('')) end exports.normalize = normalize -- Return true is first is greater than ot equal to the second -- nil counts as lowest value in this case function exports.gte(first, second) if not second or first == second then return true end if not first then return false end local a, b, c, x = parse(second) local d, e, f, y = parse(first) return (d > a) or (d == a and (e > b or (e == b and (f > c or (f == c and y > x))))) end -- Sanity check for gte code assert(exports.gte(nil, nil)) assert(exports.gte("0.0.0", nil)) assert(exports.gte("9.9.9", "9.9.9")) assert(exports.gte("9.9.10", "9.9.9")) assert(exports.gte("9.10.0", "9.9.99")) assert(exports.gte("10.0.0", "9.99.99")) assert(exports.gte("10.0.0-1", "10.0.0-0")) assert(exports.gte("10.0.1-0", "10.0.0-0")) assert(not exports.gte(nil, "0.0.0")) assert(not exports.gte("9.9.9", "9.9.10")) assert(not exports.gte("9.9.99", "9.10.0")) assert(not exports.gte("9.99.99", "10.0.0")) assert(not exports.gte("10.0.0-0", "10.0.0-1")) -- Given a semver string in the format a.b.c, and a list of versions in the -- same format, return the newest version that is compatable. This means for -- 0.b.c versions, 0.b.(>= c) will match, and for a.b.c, versions a.(>=b).* -- will match. function match(version, iterator) -- Major Minor Patch -- found a b c -- possible d e f -- minimum g h i local a, b, c if not version then -- With a n empty match, simply grab the newest version for possible in iterator do local d, e, f = parse(possible) if (not a) or (d > a) or (d == a and (e > b or (e == b and f > c))) then a, b, c = d, e, f end end else local g, h, i = parse(version) if g > 0 then -- From 1.0.0 and onward, minor updates are allowed since they mean non- -- breaking changes or additons. for possible in iterator do local d, e, f = parse(possible) if d == g and ((e == h and f >= i) or e > h) and ((not a) or e > b or (e == b and f > c)) then a, b, c = d, e, f end end else -- Before 1.0.0 we only allow patch updates assuming less stability at -- this period. for possible in iterator do local d, e, f = parse(possible) if d == g and e == h and f >= i and ((not a) or f > c) then a, b, c = d, e, f end end end end return a and (a .. '.' .. b .. '.' .. c) end exports.match = match local function iterator() local versions = {"0.0.1", "0.0.2", "0.1.0", "0.1.1", "0.2.0", "0.2.1", "1.0.0", "1.1.0", "1.1.3", "2.0.0", "2.1.2", "3.1.4"} local i = 0 return function () i = i + 1 return versions[i] end end -- Sanity check for match code assert(match("0.0.1", iterator()) == "0.0.2") assert(match("0.1.0", iterator()) == "0.1.1") assert(match("0.2.0", iterator()) == "0.2.1") assert(not match("0.3.0", iterator())) assert(match("1.0.0", iterator()) == "1.1.3") assert(not match("1.1.4", iterator())) assert(not match("1.2.0", iterator())) assert(match("2.0.0", iterator()) == "2.1.2") assert(not match("2.1.3", iterator())) assert(not match("2.2.0", iterator())) assert(match("3.0.0", iterator()) == "3.1.4") assert(not match("3.1.5", iterator())) assert(match(nil, iterator()) == "3.1.4")
fix the f==c
fix the f==c
Lua
apache-2.0
1yvT0s/lit,lduboeuf/lit,zhaozg/lit,kidaa/lit,DBarney/lit,kaustavha/lit,luvit/lit,james2doyle/lit,squeek502/lit
8c726c0bc3299d709f33a5285d5163aba8d1f169
agents/monitoring/tests/check/apache.lua
agents/monitoring/tests/check/apache.lua
local async = require('async') local fs = require('fs') local testUtil = require('monitoring/default/util/test') local path = require('path') local fmt = require('string').format local ApacheCheck = require('monitoring/default/check').ApacheCheck local PORT = 32321 local HOST = '127.0.0.1' local exports = {} exports['test_apache'] = function(test, asserts) local url = fmt('http://%s:%s/server-status?auto', HOST, PORT) local ch = ApacheCheck:new({id='foo', period=30, details={url=url}}) local server local response function reqCallback(req, res) if not response then local filePath = path.join(process.cwd(), '/agents/monitoring/tests/fixtures/checks/apache_server_status.txt') response = fs.readFileSync(filePath) end res:writeHead(200, { ["Content-Type"] = "text/plain", ["Content-Length"] = #response }) res:finish(response) end async.series({ function(callback) testUtil.runTestHTTPServer(PORT, HOST, reqCallback, function(err, _server) server = _server callback(err) end) end, function(callback) ch:run(function(result) local metrics = result:getMetrics()['none'] asserts.equal(result:getState(), 'available') asserts.equal(metrics['ReqPerSec']['v'], '136.982') asserts.equal(metrics['Uptime']['v'], '246417') asserts.equal(metrics['Total_Accesses']['v'], '33754723') callback() end) end }, function(err) if server then server:close() end test.done() end) end return exports
local async = require('async') local fs = require('fs') local testUtil = require('monitoring/default/util/test') local path = require('path') local fmt = require('string').format local ApacheCheck = require('monitoring/default/check').ApacheCheck local PORT = 32321 local HOST = '127.0.0.1' local exports = {} exports['test_apache'] = function(test, asserts) local url = fmt('http://%s:%s/server-status?auto', HOST, PORT) local ch = ApacheCheck:new({id='foo', period=30, details={url=url}}) local server local response function reqCallback(req, res) if not response then local filePath = path.join(process.cwd(), 'agents', 'monitoring', 'tests', 'fixtures', 'checks', 'apache_server_status.txt') response = fs.readFileSync(filePath) end res:writeHead(200, { ["Content-Type"] = "text/plain", ["Content-Length"] = #response }) res:finish(response) end async.series({ function(callback) testUtil.runTestHTTPServer(PORT, HOST, reqCallback, function(err, _server) server = _server callback(err) end) end, function(callback) ch:run(function(result) local metrics = result:getMetrics()['none'] asserts.equal(result:getState(), 'available') asserts.equal(metrics['ReqPerSec']['v'], '136.982') asserts.equal(metrics['Uptime']['v'], '246417') asserts.equal(metrics['Total_Accesses']['v'], '33754723') callback() end) end }, function(err) if server then server:close() end asserts.equals(err, nil) test.done() end) end return exports
fix pathing for win32 porting team
fix pathing for win32 porting team
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
b06cf642f861f9687b8017325289ccab06d0e083
examples/gridify.lua
examples/gridify.lua
-- -- draw some grids -- screen_width = WIDTH screen_height = HEIGHT screen_w_center = screen_width / 2 screen_h_center = screen_height / 2 colors = {} colors = { {r=255, g=0, b=255, a=1}, {r=0, g=0, b=255, a=1}, {r=255, g=0, b=0, a=1}, {r=0, g=255, b=0, a=1}, {r=27, g=73, b=100, a=1}, {r=0, g=51, b=75, a=1}, {r=100, g=35, b=15, a=1}, {r=200, g=135, b=150, a=1}, {r=100, g=0, b=0, a=1}, {r=100, g=50, b=0, a=1}, {r=153, g=150, b=50, a=1}, {r=25, g=102, b=0, a=1}, {r=25, g=102, b=0, a=1}, {r=80, g=500, b=200, a=1} } -- dunno where we should get this from .. math.?? function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function setup() background(0,0,0,0) cell_size = HEIGHT / 4 fill (27,73,100,1) background(0,0,0,0) text(10, 10, string.format("gridify, by torpor")) end function draw_XY_grid() for i = 0, screen_width, 10 do for screen_w_center = 0, screen_height do if (((i % 50) == 0) and ((screen_w_center % 50) == 0)) then fill(0, 51, 75, 1) text(i+4, screen_w_center-1, tostring(i)) fill(100, 35, 15, 1) text( i+4, screen_w_center+8, tostring(i)) -- padding for y direction rect(i, screen_w_center, 4, 4) end if ((screen_w_center % 10) == 0) then fill(200, 135, 150, 1) rect(i,screen_w_center,1,1) end end end end function draw_centered_grid() fill(100,0,0,1) rect(screen_w_center, screen_h_center, 4, 4) fill (100,50,0,1) --fill (153,150,50) line(0, screen_h_center, screen_width, screen_h_center) line(screen_w_center, 0, screen_w_center, screen_height) for z = screen_w_center, screen_width, 10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) --text(z - 8, screen_h_center + 16 ,tostring(z - screen_w_center)) -- padding end end for z = screen_w_center, 0, -10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) --text(z - 8, screen_h_center + 16, tostring(z - screen_w_center)) -- padding end end for z = screen_h_center, screen_height, 10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) --text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end for z = screen_h_center, 0, -10 do if (((z - screen_h_center) % 50) == 0) then --text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end end --[[ // This draws the 'percentage' scale for the centered grid, using // the largest axes as the base to determine the appropriate // interval ]] function draw_percentile_grid() biggest_axes = math.max (screen_width, screen_height) smallest_axes = math.min (screen_width, screen_height) difference_between_axes = ((biggest_axes - smallest_axes) / 2) difference = 0 if screen_width == biggest_axes then difference = 0 else difference = difference_between_axes end fill(80,500,200,1) i=0 for i=0, 100, 5 do -- map along the x axis first x_loc = map(i, 0, 100, 0, biggest_axes) - difference rect(x_loc, screen_h_center, 5, 5) text(x_loc -25, screen_h_center+6, tostring(i - 50)) end if (screen_height == biggest_axes) then difference = 0 else difference = difference_between_axes end for i=0, 100, 5 do -- map along the y axis next y_loc = map(i, 0, 100, 0, biggest_axes) - difference rect(screen_w_center, y_loc, 5, 5) text(screen_w_center-25, y_loc + 6, tostring(i - 50 * -1) .. "%") end end function draw_colors_grids() for x in screen_w_center, screen_width do for y in screen_h_center, screen_height do for i in colors do fill (color[i]) rect (x * 10, y * 10, 5, 5) end end end end function draw_grids() draw_percentile_grid() draw_centered_grid() draw_XY_grid() -- draw_colors_grids() end function draw() draw_grids() end
-- -- draw some grids -- screen_width = WIDTH screen_height = HEIGHT screen_w_center = screen_width / 2 screen_h_center = screen_height / 2 colors = {} colors = { {r=255, g=0, b=255, a=1}, {r=0, g=0, b=255, a=1}, {r=255, g=0, b=0, a=1}, {r=0, g=255, b=0, a=1}, {r=27, g=73, b=100, a=1}, {r=0, g=51, b=75, a=1}, {r=100, g=35, b=15, a=1}, {r=200, g=135, b=150, a=1}, {r=100, g=0, b=0, a=1}, {r=100, g=50, b=0, a=1}, {r=153, g=150, b=50, a=1}, {r=25, g=102, b=0, a=1}, {r=25, g=102, b=0, a=1}, {r=80, g=500, b=200, a=1} } -- dunno where we should get this from .. math.?? function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function setup() background(0,0,0,0) cell_size = HEIGHT / 4 fill (27,73,100,1) background(0,0,0,0) text(10, 10, string.format("gridify, by torpor")) end function draw_XY_grid() for i = 0, screen_width, 10 do for screen_w_center = 0, screen_height do if (((i % 50) == 0) and ((screen_w_center % 50) == 0)) then fill(0, 51, 75, 1) text(i+4, screen_w_center-1, tostring(i)) fill(100, 35, 15, 1) text( i+4, screen_w_center+8, tostring(i)) -- padding for y direction rect(i, screen_w_center, 4, 4) end if ((screen_w_center % 10) == 0) then fill(200, 135, 150, 1) rect(i,screen_w_center,1,1) end end end end function draw_centered_grid() fill(100,0,0,1) rect(screen_w_center, screen_h_center, 4, 4) fill (100,50,0,1) --fill (153,150,50) line(0, screen_h_center, screen_width, screen_h_center) line(screen_w_center, 0, screen_w_center, screen_height) for z = screen_w_center, screen_width, 10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) --text(z - 8, screen_h_center + 16 ,tostring(z - screen_w_center)) -- padding end end for z = screen_w_center, 0, -10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) --text(z - 8, screen_h_center + 16, tostring(z - screen_w_center)) -- padding end end for z = screen_h_center, screen_height, 10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) --text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end for z = screen_h_center, 0, -10 do if (((z - screen_h_center) % 50) == 0) then --text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end end --[[ // This draws the 'percentage' scale for the centered grid, using // the largest axes as the base to determine the appropriate // interval ]] function draw_percentile_grid() biggest_axes = math.max (screen_width, screen_height) smallest_axes = math.min (screen_width, screen_height) difference_between_axes = ((biggest_axes - smallest_axes) / 2) difference = 0 if screen_width == biggest_axes then difference = 0 else difference = difference_between_axes end fill(80,500,200,1) i=0 for i=0, 100, 5 do -- map along the x axis first x_loc = map(i, 0, 100, 0, biggest_axes) - difference rect(x_loc, screen_h_center, 5, 5) text(x_loc -25, screen_h_center+6, tostring(i - 50)) end if (screen_height == biggest_axes) then difference = 0 else difference = difference_between_axes end for i=0, 100, 5 do -- map along the y axis next y_loc = map(i, 0, 100, 0, biggest_axes) - difference rect(screen_w_center, y_loc, 5, 5) text(screen_w_center-25, y_loc + 6, tostring((i - 50) * -1) .. "%") end end function draw_colors_grids() print("screen_w_center : ", screen_w_center) print("screen_width : ", screen_width) for i = 1, #colors do for x = screen_w_center, screen_width do for y = screen_h_center, screen_height do fill (colors[i].r, colors[i].g, colors[i].b, colors[i].a) rect (x * 10, y * 10, 5, 5) end end end end function draw_grids() draw_percentile_grid() draw_centered_grid() draw_XY_grid() -- draw_colors_grids() end function draw() draw_grids() end
Fixup of gridifuy.lua sample.
Fixup of gridifuy.lua sample.
Lua
bsd-2-clause
seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81
88061b323e756cb2a3d49ab300dc802a82ec1f2e
frontend/gettext.lua
frontend/gettext.lua
local DEBUG = require("dbg") local GetText = { translation = {}, current_lang = "C", dirname = "l10n", textdomain = "koreader" } local GetText_mt = { __index = {} } function GetText_mt.__call(gettext, string) return gettext.translation[string] or string end local function c_escape(what) if what == "\n" then return "" elseif what == "a" then return "\a" elseif what == "b" then return "\b" elseif what == "f" then return "\f" elseif what == "n" then return "\n" elseif what == "r" then return "\r" elseif what == "t" then return "\t" elseif what == "v" then return "\v" elseif what == "0" then return "\0" -- shouldn't happen, though else return what end end -- for PO file syntax, see -- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html -- we only implement a sane subset for now function GetText_mt.__index.changeLang(new_lang) GetText.translation = {} GetText.current_lang = "C" -- the "C" locale disables localization alltogether if new_lang == "C" then return end local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po" local po = io.open(file, "r") if not po then DEBUG("cannot open translation file " .. file) return end local data = {} local what = nil while true do local line = po:read("*l") if line == nil or line == "" then if data.msgid and data.msgstr and data.msgstr ~= "" then GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape) end -- stop at EOF: if line == nil then break end data = {} what = nil else -- comment if not line:match("^#") then -- new data item (msgid, msgstr, ... local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$") if w then what = w else -- string continuation s = line:match("^%s*\"(.*)\"%s*$") end if what and s then data[what] = (data[what] or "") .. s end end end end GetText.current_lang = new_lang end setmetatable(GetText, GetText_mt) if os.getenv("LANGUAGE") then GetText.changeLang(os.getenv("LANGUAGE")) elseif os.getenv("LC_ALL") then GetText.changeLang(os.getenv("LC_ALL")) elseif os.getenv("LC_MESSAGES") then GetText.changeLang(os.getenv("LC_MESSAGES")) elseif os.getenv("LANG") then GetText.changeLang(os.getenv("LANG")) end return GetText
local DEBUG = require("dbg") local GetText = { translation = {}, current_lang = "C", dirname = "l10n", textdomain = "koreader" } local GetText_mt = { __index = {} } function GetText_mt.__call(gettext, string) return gettext.translation[string] or string end local function c_escape(what) if what == "\n" then return "" elseif what == "a" then return "\a" elseif what == "b" then return "\b" elseif what == "f" then return "\f" elseif what == "n" then return "\n" elseif what == "r" then return "\r" elseif what == "t" then return "\t" elseif what == "v" then return "\v" elseif what == "0" then return "\0" -- shouldn't happen, though else return what end end -- for PO file syntax, see -- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html -- we only implement a sane subset for now function GetText_mt.__index.changeLang(new_lang) GetText.translation = {} GetText.current_lang = "C" -- the "C" locale disables localization alltogether if new_lang == "C" or new_lang == nil then return end -- strip encoding suffix in locale like "zh_CN.utf8" new_lang = new_lang:sub(1, new_lang:find(".%.")) local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po" local po = io.open(file, "r") if not po then DEBUG("cannot open translation file " .. file) return end local data = {} local what = nil while true do local line = po:read("*l") if line == nil or line == "" then if data.msgid and data.msgstr and data.msgstr ~= "" then GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape) end -- stop at EOF: if line == nil then break end data = {} what = nil else -- comment if not line:match("^#") then -- new data item (msgid, msgstr, ... local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$") if w then what = w else -- string continuation s = line:match("^%s*\"(.*)\"%s*$") end if what and s then data[what] = (data[what] or "") .. s end end end end GetText.current_lang = new_lang end setmetatable(GetText, GetText_mt) if os.getenv("LANGUAGE") then GetText.changeLang(os.getenv("LANGUAGE")) elseif os.getenv("LC_ALL") then GetText.changeLang(os.getenv("LC_ALL")) elseif os.getenv("LC_MESSAGES") then GetText.changeLang(os.getenv("LC_MESSAGES")) elseif os.getenv("LANG") then GetText.changeLang(os.getenv("LANG")) end return GetText
strip encoding suffix in locale name like zh_CN.utf8 So that we can automatically change to language defined in the LANGUAGE or LANG env variable.
strip encoding suffix in locale name like zh_CN.utf8 So that we can automatically change to language defined in the LANGUAGE or LANG env variable.
Lua
agpl-3.0
noname007/koreader,frankyifei/koreader,mwoz123/koreader,robert00s/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,Markismus/koreader,lgeek/koreader,NiLuJe/koreader,chrox/koreader,apletnev/koreader,koreader/koreader,poire-z/koreader,ashhher3/koreader,houqp/koreader,ashang/koreader,Hzj-jie/koreader,NickSavage/koreader,poire-z/koreader,chihyang/koreader,Frenzie/koreader,mihailim/koreader,pazos/koreader
9aebe9c6d0e29ba7d1c4c7aeba48826eaa0019a6
mods/soundset/init.lua
mods/soundset/init.lua
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} soundset.tmp = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) if not soundset.tmp[name] then soundset.tmp[name] = {} end soundset.tmp[name]["music"] = music soundset.tmp[name]["ambience"] = ambience soundset.tmp[name]["other"] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name then return end local fmusic = soundset.tmp[name]["music"] local fambience = soundset.tmp[name]["ambience"] local fother = soundset.tmp[name]["other"] if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end soundset.tmp[name] = nil return elseif fields["abort"] == "Abort" then soundset.tmp[name] = nil return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then soundset.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} soundset.tmp = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) if not soundset.tmp[name] then soundset.tmp[name] = {} end soundset.tmp[name]["music"] = music soundset.tmp[name]["ambience"] = ambience soundset.tmp[name]["other"] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name or name == "" then return end local fmusic = soundset.tmp[name]["music"] or 50 local fambience = soundset.tmp[name]["ambience"] or 50 local fother = soundset.tmp[name]["other"] or 50 if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end soundset.tmp[name] = nil return elseif fields["abort"] == "Abort" then soundset.tmp[name] = nil return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then soundset.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
try to fix error https://github.com/MinetestForFun/server-minetestforfun-creative/issues/34
try to fix error https://github.com/MinetestForFun/server-minetestforfun-creative/issues/34
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
a8ba7f80b3a302860e9a936f132800798258f6f7
vrp/modules/money.lua
vrp/modules/money.lua
local lang = vRP.lang -- Money module, wallet/bank API -- The money is managed with direct SQL requests to prevent most potential value corruptions -- the wallet empty itself when respawning (after death) MySQL.createCommand("vRP/money_tables", [[ CREATE TABLE IF NOT EXISTS vrp_user_moneys( user_id INTEGER, wallet INTEGER, bank INTEGER, CONSTRAINT pk_user_moneys PRIMARY KEY(user_id), CONSTRAINT fk_user_moneys_users FOREIGN KEY(user_id) REFERENCES vrp_users(id) ON DELETE CASCADE ); ]]) MySQL.createCommand("vRP/money_init_user","INSERT IGNORE INTO vrp_user_moneys(user_id,wallet,bank) VALUES(@user_id,@wallet,@bank)") MySQL.createCommand("vRP/get_money","SELECT wallet,bank FROM vrp_user_moneys WHERE user_id = @user_id") MySQL.createCommand("vRP/set_money","UPDATE vrp_user_moneys SET wallet = @wallet, bank = @bank WHERE user_id = @user_id") -- init tables MySQL.query("vRP/money_tables") -- load config local cfg = module("cfg/money") -- API -- get money -- cbreturn nil if error function vRP.getMoney(user_id) local tmp = vRP.getUserTmpTable(user_id) if tmp then return tmp.wallet or 0 else return 0 end end -- set money function vRP.setMoney(user_id,value) local tmp = vRP.getUserTmpTable(user_id) if tmp then tmp.wallet = value end -- update client display local source = vRP.getUserSource(user_id) if source ~= nil then vRPclient.setDivContent(source,{"money",lang.money.display({value})}) end end -- try a payment -- return true or false (debited if true) function vRP.tryPayment(user_id,amount) local money = vRP.getMoney(user_id) if money >= amount then vRP.setMoney(user_id,money-amount) return true else return false end end -- give money function vRP.giveMoney(user_id,amount) local money = vRP.getMoney(user_id) vRP.setMoney(user_id,money+amount) end -- get bank money function vRP.getBankMoney(user_id) local tmp = vRP.getUserTmpTable(user_id) if tmp then return tmp.bank or 0 else return 0 end end -- set bank money function vRP.setBankMoney(user_id,value) local tmp = vRP.getUserTmpTable(user_id) if tmp then tmp.bank = value end end -- give bank money function vRP.giveBankMoney(user_id,amount) if amount > 0 then local money = vRP.getBankMoney(user_id) vRP.setBankMoney(user_id,money+amount) end end -- try a withdraw -- return true or false (withdrawn if true) function vRP.tryWithdraw(user_id,amount) local money = vRP.getBankMoney(user_id) if amount > 0 and money >= amount then vRP.setBankMoney(user_id,money-amount) vRP.giveMoney(user_id,amount) return true else return false end end -- try a deposit -- return true or false (deposited if true) function vRP.tryDeposit(user_id,amount) if amount > 0 and vRP.tryPayment(user_id,amount) then vRP.giveBankMoney(user_id,amount) return true else return false end end -- try full payment (wallet + bank to complete payment) -- return true or false (debited if true) function vRP.tryFullPayment(user_id,amount) local money = vRP.getMoney(user_id) if money >= amount then -- enough, simple payment return vRP.tryPayment(user_id, amount) else -- not enough, withdraw -> payment if vRP.tryWithdraw(user_id, amount-money) then -- withdraw to complete amount return vRP.tryPayment(user_id, amount) end end return false end -- events, init user account if doesn't exist at connection AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login) MySQL.query("vRP/money_init_user", {user_id = user_id, wallet = cfg.open_wallet, bank = cfg.open_bank}, function(rows, affected) -- load money (wallet,bank) local tmp = vRP.getUserTmpTable(user_id) if tmp then MySQL.query("vRP/get_money", {user_id = user_id}, function(rows, affected) if #rows > 0 then tmp.bank = rows[1].bank tmp.wallet = rows[1].wallet end end) end end) end) -- save money on leave AddEventHandler("vRP:playerLeave",function(user_id,source) -- (wallet,bank) local tmp = vRP.getUserTmpTable(user_id) if tmp then MySQL.query("vRP/set_money", {user_id = user_id, wallet = tmp.wallet or 0, bank = tmp.bank or 0}) end end) -- save money (at same time that save datatables) AddEventHandler("vRP:save", function() for k,v in pairs(vRP.user_tmp_tables) do MySQL.query("vRP/set_money", {user_id = k, wallet = v.wallet or 0, bank = v.bank or 0}) end end) -- money hud AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn) if first_spawn then -- add money display vRPclient.setDiv(source,{"money",cfg.display_css,lang.money.display({vRP.getMoney(user_id)})}) end end) local function ch_give(player,choice) -- get nearest player local user_id = vRP.getUserId(player) if user_id ~= nil then vRPclient.getNearestPlayer(player,{10},function(nplayer) if nplayer ~= nil then local nuser_id = vRP.getUserId(nplayer) if nuser_id ~= nil then -- prompt number vRP.prompt(player,lang.money.give.prompt(),"",function(player,amount) local amount = parseInt(amount) if amount > 0 and vRP.tryPayment(user_id,amount) then vRP.giveMoney(nuser_id,amount) vRPclient.notify(player,{lang.money.given({amount})}) vRPclient.notify(nplayer,{lang.money.received({amount})}) else vRPclient.notify(player,{lang.money.not_enough()}) end end) else vRPclient.notify(player,{lang.common.no_player_near()}) end else vRPclient.notify(player,{lang.common.no_player_near()}) end end) end end -- add player give money to main menu vRP.registerMenuBuilder("main", function(add, data) local user_id = vRP.getUserId(data.player) if user_id ~= nil then local choices = {} choices[lang.money.give.title()] = {ch_give, lang.money.give.description()} add(choices) end end)
local lang = vRP.lang -- Money module, wallet/bank API -- The money is managed with direct SQL requests to prevent most potential value corruptions -- the wallet empty itself when respawning (after death) MySQL.createCommand("vRP/money_tables", [[ CREATE TABLE IF NOT EXISTS vrp_user_moneys( user_id INTEGER, wallet INTEGER, bank INTEGER, CONSTRAINT pk_user_moneys PRIMARY KEY(user_id), CONSTRAINT fk_user_moneys_users FOREIGN KEY(user_id) REFERENCES vrp_users(id) ON DELETE CASCADE ); ]]) MySQL.createCommand("vRP/money_init_user","INSERT IGNORE INTO vrp_user_moneys(user_id,wallet,bank) VALUES(@user_id,@wallet,@bank)") MySQL.createCommand("vRP/get_money","SELECT wallet,bank FROM vrp_user_moneys WHERE user_id = @user_id") MySQL.createCommand("vRP/set_money","UPDATE vrp_user_moneys SET wallet = @wallet, bank = @bank WHERE user_id = @user_id") -- init tables MySQL.query("vRP/money_tables") -- load config local cfg = module("cfg/money") -- API -- get money -- cbreturn nil if error function vRP.getMoney(user_id) local tmp = vRP.getUserTmpTable(user_id) if tmp then return tmp.wallet or 0 else return 0 end end -- set money function vRP.setMoney(user_id,value) local tmp = vRP.getUserTmpTable(user_id) if tmp then tmp.wallet = value end -- update client display local source = vRP.getUserSource(user_id) if source ~= nil then vRPclient.setDivContent(source,{"money",lang.money.display({value})}) end end -- try a payment -- return true or false (debited if true) function vRP.tryPayment(user_id,amount) local money = vRP.getMoney(user_id) if money >= amount then vRP.setMoney(user_id,money-amount) return true else return false end end -- give money function vRP.giveMoney(user_id,amount) local money = vRP.getMoney(user_id) vRP.setMoney(user_id,money+amount) end -- get bank money function vRP.getBankMoney(user_id) local tmp = vRP.getUserTmpTable(user_id) if tmp then return tmp.bank or 0 else return 0 end end -- set bank money function vRP.setBankMoney(user_id,value) local tmp = vRP.getUserTmpTable(user_id) if tmp then tmp.bank = value end end -- give bank money function vRP.giveBankMoney(user_id,amount) if amount > 0 then local money = vRP.getBankMoney(user_id) vRP.setBankMoney(user_id,money+amount) end end -- try a withdraw -- return true or false (withdrawn if true) function vRP.tryWithdraw(user_id,amount) local money = vRP.getBankMoney(user_id) if amount > 0 and money >= amount then vRP.setBankMoney(user_id,money-amount) vRP.giveMoney(user_id,amount) return true else return false end end -- try a deposit -- return true or false (deposited if true) function vRP.tryDeposit(user_id,amount) if amount > 0 and vRP.tryPayment(user_id,amount) then vRP.giveBankMoney(user_id,amount) return true else return false end end -- try full payment (wallet + bank to complete payment) -- return true or false (debited if true) function vRP.tryFullPayment(user_id,amount) local money = vRP.getMoney(user_id) if money >= amount then -- enough, simple payment return vRP.tryPayment(user_id, amount) else -- not enough, withdraw -> payment if vRP.tryWithdraw(user_id, amount-money) then -- withdraw to complete amount return vRP.tryPayment(user_id, amount) end end return false end -- events, init user account if doesn't exist at connection AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login) MySQL.query("vRP/money_init_user", {user_id = user_id, wallet = cfg.open_wallet, bank = cfg.open_bank}, function(rows, affected) -- load money (wallet,bank) local tmp = vRP.getUserTmpTable(user_id) if tmp then MySQL.query("vRP/get_money", {user_id = user_id}, function(rows, affected) if #rows > 0 then tmp.bank = rows[1].bank tmp.wallet = rows[1].wallet end end) end end) end) -- save money on leave AddEventHandler("vRP:playerLeave",function(user_id,source) -- (wallet,bank) local tmp = vRP.getUserTmpTable(user_id) if tmp and tmp.wallet ~= nil and tmp.bank ~= nil then MySQL.query("vRP/set_money", {user_id = user_id, wallet = tmp.wallet, bank = tmp.bank}) end end) -- save money (at same time that save datatables) AddEventHandler("vRP:save", function() for k,v in pairs(vRP.user_tmp_tables) do if v.wallet ~= nil and v.bank ~= nil then MySQL.query("vRP/set_money", {user_id = k, wallet = v.wallet, bank = v.bank}) end end end) -- money hud AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn) if first_spawn then -- add money display vRPclient.setDiv(source,{"money",cfg.display_css,lang.money.display({vRP.getMoney(user_id)})}) end end) local function ch_give(player,choice) -- get nearest player local user_id = vRP.getUserId(player) if user_id ~= nil then vRPclient.getNearestPlayer(player,{10},function(nplayer) if nplayer ~= nil then local nuser_id = vRP.getUserId(nplayer) if nuser_id ~= nil then -- prompt number vRP.prompt(player,lang.money.give.prompt(),"",function(player,amount) local amount = parseInt(amount) if amount > 0 and vRP.tryPayment(user_id,amount) then vRP.giveMoney(nuser_id,amount) vRPclient.notify(player,{lang.money.given({amount})}) vRPclient.notify(nplayer,{lang.money.received({amount})}) else vRPclient.notify(player,{lang.money.not_enough()}) end end) else vRPclient.notify(player,{lang.common.no_player_near()}) end else vRPclient.notify(player,{lang.common.no_player_near()}) end end) end end -- add player give money to main menu vRP.registerMenuBuilder("main", function(add, data) local user_id = vRP.getUserId(data.player) if user_id ~= nil then local choices = {} choices[lang.money.give.title()] = {ch_give, lang.money.give.description()} add(choices) end end)
Money save more robust fixe.
Money save more robust fixe.
Lua
mit
ImagicTheCat/vRP,ImagicTheCat/vRP
f8c748759a3e471eb69d288ea43818ccbdfe6584
lua/geohash.lua
lua/geohash.lua
local GeoHash = {} --[[ -- Private Attributes ]]-- local _map = {} _map['0'] = '00000' _map['1'] = '00001' _map['2'] = '00010' _map['3'] = '00011' _map['4'] = '00100' _map['5'] = '00101' _map['6'] = '00110' _map['7'] = '00111' _map['8'] = '01000' _map['9'] = '01001' _map['b'] = '01010' _map['c'] = '01011' _map['d'] = '01100' _map['e'] = '01101' _map['f'] = '01110' _map['g'] = '01111' _map['h'] = '10000' _map['j'] = '10001' _map['k'] = '10010' _map['m'] = '10011' _map['n'] = '10100' _map['p'] = '10101' _map['q'] = '10110' _map['r'] = '10111' _map['s'] = '11000' _map['t'] = '11001' _map['u'] = '11010' _map['v'] = '11011' _map['w'] = '11100' _map['x'] = '11101' _map['y'] = '11110' _map['z'] = '11111' local _precision = 25 --[[ -- Private Methods ]]-- local function _decode(coord, min, max) local mid = 0.0 local val = 0.0 local c = '' for i = 1, #coord do c = coord:sub(i, i) if c == '1' then min = mid val = (mid + max) / 2 mid = val else max = mid val = (mid + min) / 2 mid = val end end return val end local function _encode(coord, min, max) local mid = 0.0 local x = 0.0 local y = 0.0 local result = '' for i = 1, _precision do if coord <= max and coord >= mid then result = result .. '1' x = mid y = max else result = result .. '0' x = min y = mid end min = x mid = x + ((y - x) / 2) max = y end return result end local function _merge(latbin, longbin) local res = '' for i = 1, #latbin do res = res .. longbin:sub(i, i) .. latbin:sub(i, i) end return res end local function _swap(tbl) local table = {} for key, val in pairs(tbl) do table[val] = key end return table end local function _translate(bstr) local hash = '' local t = _swap(_map) for i = 1, #bstr, 5 do hash = hash .. t[bstr:sub(i, i + 4)] end return hash end --[[ -- Public Methods ]]-- function GeoHash.decode(hash) local bin = '' local long = '' local lat = '' local c = '' -- Convert hash to binary string for i = 1, #hash do c = hash:sub(i, i) bin = bin .. _map[c] end -- Split binary string into latitude and longitude parts for i = 1, #bin do c = bin:sub(i, i) if i % 2 == 0 then lat = lat .. c else long = long .. c end end return _decode(lat, -90.0, 90.0), _decode(long, -180.0, 180.0) end function GeoHash.encode(lat, long) -- Translate coordinates to binary string format local a = _encode(lat, -90.0, 90.0) local b = _encode(long, -180.0, 180.0) -- Merge the two binary string local binstr = _merge(a, b) -- Calculate GeoHash for binary string return _translate(binstr) end function GeoHash.precision(p) _precision = p * 5 end return GeoHash
local GeoHash = {} --[[ -- Private Attributes ]]-- local _map = {} _map['0'] = '00000' _map['1'] = '00001' _map['2'] = '00010' _map['3'] = '00011' _map['4'] = '00100' _map['5'] = '00101' _map['6'] = '00110' _map['7'] = '00111' _map['8'] = '01000' _map['9'] = '01001' _map['b'] = '01010' _map['c'] = '01011' _map['d'] = '01100' _map['e'] = '01101' _map['f'] = '01110' _map['g'] = '01111' _map['h'] = '10000' _map['j'] = '10001' _map['k'] = '10010' _map['m'] = '10011' _map['n'] = '10100' _map['p'] = '10101' _map['q'] = '10110' _map['r'] = '10111' _map['s'] = '11000' _map['t'] = '11001' _map['u'] = '11010' _map['v'] = '11011' _map['w'] = '11100' _map['x'] = '11101' _map['y'] = '11110' _map['z'] = '11111' local _precision = nil local _digits = 0 --[[ -- Private Methods ]]-- local function _decode(coord, min, max) local mid = 0.0 local val = 0.0 local c = '' for i = 1, #coord do c = coord:sub(i, i) if c == '1' then min = mid val = (mid + max) / 2 mid = val else max = mid val = (mid + min) / 2 mid = val end end -- We want number of decimals according to hash length val = tonumber(string.format("%.".. (#coord / 5) .. "f", val)) return val end local function _encode(coord, min, max) local mid = 0.0 local x = 0.0 local y = 0.0 local p = ((_precision or _digits) * 5) local result = '' for i = 1, p do if coord <= max and coord >= mid then result = result .. '1' x = mid y = max else result = result .. '0' x = min y = mid end min = x mid = x + ((y - x) / 2) max = y end return result end local function _merge(latbin, longbin) local res = '' for i = 1, #latbin do res = res .. longbin:sub(i, i) .. latbin:sub(i, i) end return res end local function _swap(tbl) local table = {} for key, val in pairs(tbl) do table[val] = key end return table end local function _translate(bstr) local hash = '' local t = _swap(_map) for i = 1, #bstr, 5 do hash = hash .. t[bstr:sub(i, i + 4)] end return hash end local function _decimals(lat, long) local d1 = tostring(string.match(tostring(lat), "%d+.(%d+)")) local d2 = tostring(string.match(tostring(long), "%d+.(%d+)")) local ret = #d2 if #d1 > #d2 then ret = #d1 end return ret end --[[ -- Public Methods ]]-- function GeoHash.decode(hash) local bin = '' local long = '' local lat = '' local c = '' -- Convert hash to binary string for i = 1, #hash do c = hash:sub(i, i) bin = bin .. _map[c] end -- Split binary string into latitude and longitude parts for i = 1, #bin do c = bin:sub(i, i) if i % 2 == 0 then lat = lat .. c else long = long .. c end end return _decode(lat, -90.0, 90.0), _decode(long, -180.0, 180.0) end function GeoHash.encode(lat, long) -- Find precision _digits = _decimals(lat, long) -- Translate coordinates to binary string format local a = _encode(lat, -90.0, 90.0) local b = _encode(long, -180.0, 180.0) -- Merge the two binary string local binstr = _merge(a, b) -- Calculate GeoHash for binary string return _translate(binstr) end function GeoHash.precision(p) _precision = p end return GeoHash
Fixed issue with precision of digits and hash length
Fixed issue with precision of digits and hash length If precision isn't specified it is set to the longest number of decimals in either latitude or longitude specified.
Lua
mit
dauer/geohash,dauer/geohash,irr/geohash,irr/geohash
481d86366753a35d900ac52714c24184657a9a7a
libs/weblit-static.lua
libs/weblit-static.lua
exports.name = "creationix/weblit-static" exports.version = "0.3.2" exports.dependencies = { "creationix/[email protected]", "creationix/[email protected]", } exports.description = "The auto-headers middleware helps Weblit apps implement proper HTTP semantics" exports.tags = {"weblit", "middleware", "http"} exports.license = "MIT" exports.author = { name = "Tim Caswell" } exports.homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-auto-headers.lua" local getType = require("mime").getType local jsonStringify = require('json').stringify local makeChroot = require('hybrid-fs') return function (path) local fs = makeChroot(path) return function (req, res, go) if req.method ~= "GET" then return go() end local path = (req.params and req.params.path) or req.path path = path:match("^[^?#]*") if path:byte(1) == 47 then path = path:sub(2) end local stat = fs.stat(path) if not stat then return go() end local function renderFile() local body = assert(fs.readFile(path)) res.code = 200 res.headers["Content-Type"] = getType(path) res.body = body return end local function renderDirectory() if req.path:byte(-1) ~= 47 then res.code = 301 res.headers.Location = req.path .. '/' return end local files = {} for entry in fs.scandir(path) do if entry.name == "index.html" and entry.type == "file" then path = path .. "/index.html" return renderFile() end files[#files + 1] = entry entry.url = "http://" .. req.headers.host .. req.path .. entry.name end local body = jsonStringify(files) .. "\n" res.code = 200 res.headers["Content-Type"] = "application/json" res.body = body return end if stat.type == "directory" then return renderDirectory() elseif stat.type == "file" then if req.path:byte(-1) == 47 then res.code = 301 res.headers.Location = req.path:match("^(.*[^/])/+$") return end return renderFile() end end end
exports.name = "creationix/weblit-static" exports.version = "0.3.3" exports.dependencies = { "creationix/[email protected]", "creationix/[email protected]", } exports.description = "The auto-headers middleware helps Weblit apps implement proper HTTP semantics" exports.tags = {"weblit", "middleware", "http"} exports.license = "MIT" exports.author = { name = "Tim Caswell" } exports.homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-auto-headers.lua" local getType = require("mime").getType local jsonStringify = require('json').stringify local makeChroot = require('hybrid-fs') return function (rootPath) local fs = makeChroot(rootPath) return function (req, res, go) if req.method ~= "GET" then return go() end local path = (req.params and req.params.path) or req.path path = path:match("^[^?#]*") if path:byte(1) == 47 then path = path:sub(2) end local stat = fs.stat(path) if not stat then return go() end local function renderFile() local body = assert(fs.readFile(path)) res.code = 200 res.headers["Content-Type"] = getType(path) res.body = body return end local function renderDirectory() if req.path:byte(-1) ~= 47 then res.code = 301 res.headers.Location = req.path .. '/' return end local files = {} for entry in fs.scandir(path) do if entry.name == "index.html" and entry.type == "file" then path = (#path > 0 and path .. "/" or "") .. "index.html" return renderFile() end files[#files + 1] = entry entry.url = "http://" .. req.headers.host .. req.path .. entry.name end local body = jsonStringify(files) .. "\n" res.code = 200 res.headers["Content-Type"] = "application/json" res.body = body return end if stat.type == "directory" then return renderDirectory() elseif stat.type == "file" then if req.path:byte(-1) == 47 then res.code = 301 res.headers.Location = req.path:match("^(.*[^/])/+$") return end return renderFile() end end end
[email protected] - fix autoindex path
[email protected] - fix autoindex path
Lua
mit
zhaozg/weblit
ae9fc21ddb2f81a4a7ce1647bf7a66ccf6daa5fd
nvim/lua/plugins/lsp.lua
nvim/lua/plugins/lsp.lua
--- -- Global Config --- local lspconfig = require("lspconfig") local lsp_defaults = { flags = { debounce_text_changes = 150, }, capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()), on_attach = function(client, bufnr) vim.api.nvim_exec_autocmds("User", { pattern = "LspAttached" }) end, } lspconfig.util.default_config = vim.tbl_deep_extend("force", lspconfig.util.default_config, lsp_defaults) --- -- Diagnostic Config --- local sign = function(opts) vim.fn.sign_define(opts.name, { texthl = opts.name, text = opts.text, numhl = "", }) end sign({ name = "DiagnosticSignError", text = "✘" }) sign({ name = "DiagnosticSignWarn", text = "▲" }) sign({ name = "DiagnosticSignHint", text = "⚑" }) sign({ name = "DiagnosticSignInfo", text = "" }) vim.diagnostic.config({ severity_sort = true, }) --- -- LSP Servers --- lspconfig.sumneko_lua.setup({ settings = { Lua = { runtime = { -- Tell the language server we are using LuaJIT in the case of Neovim version = "LuaJIT", }, diagnostics = { -- Make the language server recognize the `vim` global globals = { "vim" }, }, workspace = { -- Make the server aware of Neovim runtime files library = { os.getenv("VIMRUNTIME") }, }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, }, }, }) lspconfig.gopls.setup({}) lspconfig.pyright.setup({}) lspconfig.terraformls.setup({}) lspconfig.tsserver.setup({})
--- -- Global Config --- local lspconfig = require("lspconfig") local lsp_defaults = { flags = { debounce_text_changes = 150, }, capabilities = require("cmp_nvim_lsp").default_capabilities(), on_attach = function(client, bufnr) vim.api.nvim_exec_autocmds("User", { pattern = "LspAttached" }) end, } lspconfig.util.default_config = vim.tbl_deep_extend("force", lspconfig.util.default_config, lsp_defaults) --- -- Diagnostic Config --- local sign = function(opts) vim.fn.sign_define(opts.name, { texthl = opts.name, text = opts.text, numhl = "", }) end sign({ name = "DiagnosticSignError", text = "✘" }) sign({ name = "DiagnosticSignWarn", text = "▲" }) sign({ name = "DiagnosticSignHint", text = "⚑" }) sign({ name = "DiagnosticSignInfo", text = "" }) vim.diagnostic.config({ severity_sort = true, }) --- -- LSP Servers --- lspconfig.sumneko_lua.setup({ settings = { Lua = { runtime = { -- Tell the language server we are using LuaJIT in the case of Neovim version = "LuaJIT", }, diagnostics = { -- Make the language server recognize the `vim` global globals = { "vim" }, }, workspace = { -- Make the server aware of Neovim runtime files library = { os.getenv("VIMRUNTIME") }, }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, }, }, }) lspconfig.gopls.setup({}) lspconfig.pyright.setup({}) lspconfig.terraformls.setup({}) lspconfig.tsserver.setup({})
fix the deprecation issue raised by cmp-nvim-lsp
fix the deprecation issue raised by cmp-nvim-lsp
Lua
mit
zhyu/dotfiles
87e6336d3de64a2be25074d90874674b3c4bfa0a
pud/ui/TextEntry.lua
pud/ui/TextEntry.lua
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods) if self._pressed then if 'l' == button then self._isEnteringText = not self._isEnteringText if self._isEnteringText then self:showCursor() else self:hideCursor() end end end end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override Frame:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- override Frame:switchToNormalStyle() function TextEntry:switchToNormalStyle() if self._isEnteringText then return end Text.switchToNormalStyle(self) end -- override Frame:switchToHoverStyle() function TextEntry:switchToHoverStyle() if self._isEnteringText then return end Text.switchToHoverStyle(self) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then -- copy the entire text local text = {} local numLines = #self._text for i=1,numLines do text[i] = self._text[i] end local lineNum = numLines if lineNum < 1 then lineNum = 1 end local line = text[lineNum] or '' local _stopEntering = function() self._isEnteringText = false self:hideCursor() self:_handleMouseRelease(love.mouse.getPosition()) end local _nextLine = function() if self._maxLines == 1 then _stopEntering() else local nextLine = lineNum + 1 if nextLine > self._maxLines then nextLine = self._maxLines end text[nextLine] = text[nextLine] or '' end end local key = e:getKey() switch(key) { backspace = function() line = string_sub(line, 1, -2) if string.len(line) < 1 then text[lineNum] = nil lineNum = lineNum - 1 if lineNum < 1 then lineNum = 1 end line = text[lineNum] or '' end end, ['return'] = _nextLine, kpenter = _nextLine, escape = _stopEntering, default = function() local unicode = e:getUnicode() if unicode then line = format('%s%s', line, unicode) end end, } text[lineNum] = line self:setText(text) self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods) if self._pressed then if 'l' == button then self._isEnteringText = not self._isEnteringText if self._isEnteringText then self:showCursor() else self:hideCursor() end end end end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override Frame:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- override Frame:switchToNormalStyle() function TextEntry:switchToNormalStyle() if self._isEnteringText then return end Text.switchToNormalStyle(self) end -- override Frame:switchToHoverStyle() function TextEntry:switchToHoverStyle() if self._isEnteringText then return end Text.switchToHoverStyle(self) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then -- copy the entire text local text = {} local numLines = #self._text for i=1,numLines do text[i] = self._text[i] end local lineNum = numLines if lineNum < 1 then lineNum = 1 end local line = text[lineNum] or '' local _stopEntering = function() self._isEnteringText = false self:hideCursor() self:_handleMouseRelease(love.mouse.getPosition()) end local _nextLine = function() if self._maxLines == 1 then _stopEntering() else local nextLine = lineNum + 1 if nextLine > self._maxLines then nextLine = self._maxLines end text[nextLine] = text[nextLine] or '' end end local key = e:getKey() switch(key) { backspace = function() local len = string.len(line) line = string_sub(line, 1, -2) if string.len(line) == len then text[lineNum] = nil lineNum = lineNum - 1 if lineNum < 1 then lineNum = 1 end line = text[lineNum] or '' end end, ['return'] = _nextLine, kpenter = _nextLine, escape = _stopEntering, default = function() local unicode = e:getUnicode() if unicode then line = format('%s%s', line, unicode) end end, } text[lineNum] = line self:setText(text) self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
fix backspace deleting newline + char (now just newline)
fix backspace deleting newline + char (now just newline)
Lua
mit
scottcs/wyx
26bcea8f3f9e17d9d8b58c36f7ac13f1bcb10d42
src/apps/rate_limiter/rate_limiter.lua
src/apps/rate_limiter/rate_limiter.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local app = require("core.app") local link = require("core.link") local config = require("core.config") local packet = require("core.packet") local timer = require("core.timer") local counter = require("core.counter") local basic_apps = require("apps.basic.basic_apps") local ffi = require("ffi") local C = ffi.C local floor, min = math.floor, math.min --- # `Rate limiter` app: enforce a byte-per-second limit -- uses http://en.wikipedia.org/wiki/Token_bucket algorithm -- single bucket, drop non-conformant packets -- bucket capacity and content - bytes -- rate - bytes per second RateLimiter = { config = { rate = {required=true}, bucket_capacity = {required=true}, initial_capacity = {required=false} } } -- Source produces synthetic packets of such size local PACKET_SIZE = 60 function RateLimiter:new (conf) conf.initial_capacity = conf.initial_capacity or conf.bucket_capacity local o = { rate = conf.rate, bucket_capacity = conf.bucket_capacity, bucket_content = conf.initial_capacity, shm = { txdrop = {counter} } } return setmetatable(o, {__index=RateLimiter}) end function RateLimiter:reset(rate, bucket_capacity, initial_capacity) assert(rate) assert(bucket_capacity) self.rate = rate self.bucket_capacity = bucket_capacity self.bucket_content = initial_capacity or bucket_capacity end -- return statistics snapshot function RateLimiter:get_stat_snapshot () return { rx = link.stats(self.input.input).txpackets, tx = link.stats(self.output.output).txpackets, time = tonumber(C.get_time_ns()), } end function RateLimiter:push () local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") do local cur_now = tonumber(app.now()) local last_time = self.last_time or cur_now self.bucket_content = min( self.bucket_content + self.rate * (cur_now - last_time), self.bucket_capacity ) self.last_time = cur_now end while not link.empty(i) do local p = link.receive(i) local length = p.length if length <= self.bucket_content then self.bucket_content = self.bucket_content - length link.transmit(o, p) else -- discard packet counter.add(self.shm.txdrop) packet.free(p) end end end local function compute_effective_rate (rl, rate, snapshot) local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 local tx = link.stats(rl.output.output).txpackets - snapshot.tx return floor(tx * PACKET_SIZE / elapsed_time) end function selftest () print("Rate limiter selftest") local c = config.new() config.app(c, "source", basic_apps.Source) -- app.apps.source = app.new(basic_apps.Source:new()) local ok = true local rate_non_busy_loop = 200000 local effective_rate_non_busy_loop -- bytes local bucket_size = rate_non_busy_loop / 4 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate local arg = { rate = rate_non_busy_loop, bucket_capacity = rate_non_busy_loop / 4 } config.app(c, "ratelimiter", RateLimiter, arg) config.app(c, "sink", basic_apps.Sink) -- Create a pipeline: -- Source --> RateLimiter --> Sink config.link(c, "source.output -> ratelimiter.input") config.link(c, "ratelimiter.output -> sink.input") app.configure(c) -- XXX do this in new () ? local rl = app.app_table.ratelimiter local seconds_to_run = 5 -- print packets statistics every second timer.activate(timer.new( "report", function () app.report() seconds_to_run = seconds_to_run - 1 end, 1e9, -- every second 'repeating' )) -- bytes per second do print("\ntest effective rate, non-busy loop") local snapshot = rl:get_stat_snapshot() -- push some packets through it while seconds_to_run > 0 do app.breathe() timer.run() C.usleep(10) -- avoid busy loop end -- print final report app.report() effective_rate_non_busy_loop = compute_effective_rate( rl, rate_non_busy_loop, snapshot ) print("configured rate is", rate_non_busy_loop, "bytes per second") print( "effective rate is", effective_rate_non_busy_loop, "bytes per second" ) local accepted_min = floor(rate_non_busy_loop * 0.9) local accepted_max = floor(rate_non_busy_loop * 1.1) if effective_rate_non_busy_loop < accepted_min or effective_rate_non_busy_loop > accepted_max then print("test failed") ok = false end end do print("measure throughput on heavy load...") -- bytes per second local rate_busy_loop = 1200000000 local effective_rate_busy_loop -- bytes local bucket_size = rate_busy_loop / 10 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate -- too big value may produce burst in the beginning rl:reset(rate_busy_loop, bucket_size) local snapshot = rl:get_stat_snapshot() for i = 1, 100000 do app.breathe() timer.run() end local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 print("elapsed time ", elapsed_time, "seconds") local rx = link.stats(rl.input.input).txpackets - snapshot.rx print("packets received", rx, floor(rx / elapsed_time / 1e6), "Mpps") effective_rate_busy_loop = compute_effective_rate( rl, rate_busy_loop, snapshot ) print("configured rate is", rate_busy_loop, "bytes per second") print( "effective rate is", effective_rate_busy_loop, "bytes per second" ) print( "throughput is", floor(effective_rate_busy_loop / PACKET_SIZE / 1e6), "Mpps") -- on poor computer effective rate may be too small -- so no formal checks end if not ok then print("selftest failed") os.exit(1) end print("selftest passed") end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local app = require("core.app") local link = require("core.link") local config = require("core.config") local packet = require("core.packet") local timer = require("core.timer") local counter = require("core.counter") local basic_apps = require("apps.basic.basic_apps") local ffi = require("ffi") local C = ffi.C local floor, min = math.floor, math.min --- # `Rate limiter` app: enforce a byte-per-second limit -- uses http://en.wikipedia.org/wiki/Token_bucket algorithm -- single bucket, drop non-conformant packets -- bucket capacity and content - bytes -- rate - bytes per second RateLimiter = { config = { rate = {required=true}, bucket_capacity = {required=true}, initial_capacity = {required=false} } } -- Source produces synthetic packets of such size local PACKET_SIZE = 60 function RateLimiter:new (conf) conf.initial_capacity = conf.initial_capacity or conf.bucket_capacity local o = { rate = conf.rate, bucket_capacity = conf.bucket_capacity, bucket_content = conf.initial_capacity, shm = { txdrop = {counter} } } return setmetatable(o, {__index=RateLimiter}) end function RateLimiter:reset(rate, bucket_capacity, initial_capacity) assert(rate) assert(bucket_capacity) self.rate = rate self.bucket_capacity = bucket_capacity self.bucket_content = initial_capacity or bucket_capacity end -- return statistics snapshot function RateLimiter:get_stat_snapshot () return { rx = link.stats(self.input.input).txpackets, tx = link.stats(self.output.output).txpackets, time = tonumber(C.get_time_ns()), } end function RateLimiter:push () local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") do local cur_now = tonumber(app.now()) local last_time = self.last_time or cur_now self.bucket_content = min( self.bucket_content + self.rate * (cur_now - last_time), self.bucket_capacity ) self.last_time = cur_now end while not link.empty(i) do local p = link.receive(i) local length = p.length if length <= self.bucket_content then self.bucket_content = self.bucket_content - length link.transmit(o, p) else -- discard packet counter.add(self.shm.txdrop) packet.free(p) end end end local function compute_effective_rate (rl, rate, snapshot) local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 local tx = link.stats(rl.output.output).txpackets - snapshot.tx return floor(tx * PACKET_SIZE / elapsed_time) end function selftest () print("Rate limiter selftest") local c = config.new() config.app(c, "source", basic_apps.Source) -- app.apps.source = app.new(basic_apps.Source:new()) local ok = true local rate_non_busy_loop = 200000 local effective_rate_non_busy_loop -- bytes local bucket_size = rate_non_busy_loop / 4 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate local arg = { rate = rate_non_busy_loop, bucket_capacity = rate_non_busy_loop / 4 } config.app(c, "ratelimiter", RateLimiter, arg) config.app(c, "sink", basic_apps.Sink) -- Create a pipeline: -- Source --> RateLimiter --> Sink config.link(c, "source.output -> ratelimiter.input") config.link(c, "ratelimiter.output -> sink.input") app.configure(c) -- XXX do this in new () ? local rl = app.app_table.ratelimiter local seconds_to_run = 5 -- print packets statistics every second timer.activate(timer.new( "report", function () app.report() seconds_to_run = seconds_to_run - 1 end, 1e9, -- every second 'repeating' )) -- bytes per second do print("\ntest effective rate, non-busy loop") local snapshot = rl:get_stat_snapshot() -- push some packets through it app.main{duration=seconds_to_run} -- print final report app.report() effective_rate_non_busy_loop = compute_effective_rate( rl, rate_non_busy_loop, snapshot ) print("configured rate is", rate_non_busy_loop, "bytes per second") print( "effective rate is", effective_rate_non_busy_loop, "bytes per second" ) local accepted_min = floor(rate_non_busy_loop * 0.9) local accepted_max = floor(rate_non_busy_loop * 1.1) if effective_rate_non_busy_loop < accepted_min or effective_rate_non_busy_loop > accepted_max then print("test failed") ok = false end end do print("measure throughput on heavy load...") -- bytes per second local rate_busy_loop = 1200000000 local effective_rate_busy_loop -- bytes local bucket_size = rate_busy_loop / 10 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate -- too big value may produce burst in the beginning rl:reset(rate_busy_loop, bucket_size) local snapshot = rl:get_stat_snapshot() app.main{duration=0.1} local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 print("elapsed time ", elapsed_time, "seconds") local rx = link.stats(rl.input.input).txpackets - snapshot.rx print("packets received", rx, floor(rx / elapsed_time / 1e6), "Mpps") effective_rate_busy_loop = compute_effective_rate( rl, rate_busy_loop, snapshot ) print("configured rate is", rate_busy_loop, "bytes per second") print( "effective rate is", effective_rate_busy_loop, "bytes per second" ) print( "throughput is", floor(effective_rate_busy_loop / PACKET_SIZE / 1e6), "Mpps") -- on poor computer effective rate may be too small -- so no formal checks end if not ok then print("selftest failed") os.exit(1) end print("selftest passed") end
apps.rate_limiter: fix selftest
apps.rate_limiter: fix selftest
Lua
apache-2.0
eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb
0edf1cca29b0e19538e43902b432a765dfb0a72a
frontend/ui/language.lua
frontend/ui/language.lua
-- high level wrapper module for gettext local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") local _ = require("gettext") local Language = {} function Language:changeLanguage(lang_locale) _.changeLang(lang_locale) G_reader_settings:saveSetting("language", lang_locale) UIManager:show(InfoMessage:new{ text = _("Please restart KOReader for the new language setting to take effect."), timeout = 3, }) end function Language:genLanguageSubItem(lang, lang_locale) return { text = lang, checked_func = function() return G_reader_settings:readSetting("language") == lang_locale end, callback = function() self:changeLanguage(lang_locale) end } end function Language:getLangMenuTable() -- cache menu table if not self.LangMenuTable then self.LangMenuTable = { text = _("Language"), -- NOTE: language with no translation are commented out for now sub_item_table = { self:genLanguageSubItem("English", "C"), self:genLanguageSubItem("Catalá", "ca"), self:genLanguageSubItem("Čeština", "cs_CZ"), self:genLanguageSubItem("Deutsch", "de"), self:genLanguageSubItem("Español", "es"), self:genLanguageSubItem("Ελληνικά", "el"), self:genLanguageSubItem("Français", "fr"), self:genLanguageSubItem("Galego", "gl"), self:genLanguageSubItem("Italiano", "it_IT"), self:genLanguageSubItem("Magyar", "hu"), self:genLanguageSubItem("Nederlands", "nl_NL"), self:genLanguageSubItem("norsk", "nb_NO"), self:genLanguageSubItem("Polski", "pl"), --self:genLanguageSubItem("Polski2", "pl_PL"), self:genLanguageSubItem("Português do Brasil", "pt_BR"), self:genLanguageSubItem("Português", "pt_PT"), self:genLanguageSubItem("Svenska", "sv"), -- self:genLanguageSubItem("Tiếng Việt", "vi"), self:genLanguageSubItem("Türkçe", "tr"), -- self:genLanguageSubItem("Viet Nam", "vi_VN"), --self:genLanguageSubItem("عربى", "ar_AA"), self:genLanguageSubItem("български", "bg_BG"), --self:genLanguageSubItem("বাঙালি", "bn"), --self:genLanguageSubItem("فارسی", "fa"), self:genLanguageSubItem("日本語", "ja"), --self:genLanguageSubItem("Қазақ", "kk"), self:genLanguageSubItem("한글", "ko_KR"), self:genLanguageSubItem("Русский язык", "ru"), self:genLanguageSubItem("Русский", "ru_RU"), self:genLanguageSubItem("Українська", "uk"), --self:genLanguageSubItem("中文", "zh"), self:genLanguageSubItem("简体中文", "zh_CN"), self:genLanguageSubItem("中文(台灣)", "zh_TW"), --self:genLanguageSubItem("中文(台灣)(Big5)", "zh_TW.Big5"), } } end return self.LangMenuTable end return Language
-- high level wrapper module for gettext local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") local _ = require("gettext") local Language = {} function Language:changeLanguage(lang_locale) _.changeLang(lang_locale) G_reader_settings:saveSetting("language", lang_locale) UIManager:show(InfoMessage:new{ text = _("Please restart KOReader for the new language setting to take effect."), timeout = 3, }) end function Language:genLanguageSubItem(lang, lang_locale) return { text = lang, checked_func = function() return G_reader_settings:readSetting("language") == lang_locale end, callback = function() self:changeLanguage(lang_locale) end } end function Language:getLangMenuTable() -- cache menu table if not self.LangMenuTable then self.LangMenuTable = { text = _("Language"), -- NOTE: language with no translation are commented out for now sub_item_table = { self:genLanguageSubItem("English", "C"), self:genLanguageSubItem("Catalá", "ca"), self:genLanguageSubItem("Čeština", "cs_CZ"), self:genLanguageSubItem("Deutsch", "de"), self:genLanguageSubItem("Español", "es"), self:genLanguageSubItem("Français", "fr"), self:genLanguageSubItem("Galego", "gl"), self:genLanguageSubItem("Italiano", "it_IT"), self:genLanguageSubItem("Magyar", "hu"), self:genLanguageSubItem("Nederlands", "nl_NL"), self:genLanguageSubItem("Norsk", "nb_NO"), self:genLanguageSubItem("Polski", "pl"), --self:genLanguageSubItem("Polski2", "pl_PL"), self:genLanguageSubItem("Português", "pt_PT"), self:genLanguageSubItem("Português do Brasil", "pt_BR"), self:genLanguageSubItem("Svenska", "sv"), --self:genLanguageSubItem("Tiếng Việt", "vi"), self:genLanguageSubItem("Türkçe", "tr"), --self:genLanguageSubItem("Viet Nam", "vi_VN"), --self:genLanguageSubItem("عربى", "ar_AA"), self:genLanguageSubItem("български", "bg_BG"), --self:genLanguageSubItem("বাঙালি", "bn"), self:genLanguageSubItem("Ελληνικά", "el"), --self:genLanguageSubItem("فارسی", "fa"), self:genLanguageSubItem("日本語", "ja"), --self:genLanguageSubItem("Қазақ", "kk"), self:genLanguageSubItem("한글", "ko_KR"), self:genLanguageSubItem("Русский язык", "ru"), self:genLanguageSubItem("Русский", "ru_RU"), self:genLanguageSubItem("Українська", "uk"), --self:genLanguageSubItem("中文", "zh"), self:genLanguageSubItem("简体中文", "zh_CN"), self:genLanguageSubItem("中文(台灣)", "zh_TW"), --self:genLanguageSubItem("中文(台灣)(Big5)", "zh_TW.Big5"), } } end return self.LangMenuTable end return Language
Minor fix in the sorting in language.lua
Minor fix in the sorting in language.lua See https://github.com/koreader/koreader/pull/2662#issuecomment-287855474
Lua
agpl-3.0
NiLuJe/koreader,Markismus/koreader,koreader/koreader,Frenzie/koreader,lgeek/koreader,mihailim/koreader,mwoz123/koreader,NiLuJe/koreader,Hzj-jie/koreader,pazos/koreader,houqp/koreader,poire-z/koreader,apletnev/koreader,Frenzie/koreader,robert00s/koreader,poire-z/koreader,koreader/koreader
38c74fda27049d38dd045809e3b655aa17dfb66d
lua/application.lua
lua/application.lua
require "variables" globalHeaders = "Host: " .. apiHost .. "\r\nAuthorization: Bearer " .. auth_token .. "\r\nContent-Type: application/json\r\n" for i,sensor in pairs(sensors) do gpio.mode(sensor.gpioPin, gpio.INPUT, gpio.PULLUP) sensor.state = gpio.read(sensor.gpioPin) gpio.trig(sensor.gpioPin, "both", function (level) local newState = gpio.read(sensor.gpioPin) if sensor.state ~= newState then sensor.state = newState print(sensor.name .. " pin is " .. sensor.state) queueRequest(sensor.deviceId, sensor.state) end end) end requestQueue = {} function queueRequest(sensorId, value) local requestData = { sensorId = sensorId, value = value } table.insert(requestQueue, requestData) end function sendRequest(sensorData) local payload = [[{"sensor_id":"]] .. sensorData.sensorId .. [[","state":]] .. sensorData.value .. "}" local headers = globalHeaders .. "Content-Length: " .. string.len(payload) .. "\r\n" http.post( apiHost .. apiEndpoint, headers, payload, function(code, data) if code > 201 then print("Error " .. code .. " posting " .. sensorData.sensorId .. ", retrying") table.insert(requestQueue, 1, sensorData) end end) end tmr.create():alarm(500, tmr.ALARM_AUTO, function() local data = table.remove(requestQueue) if data then if pcall(sendRequest, data) then print("Success: " .. data.sensorId .. " = " .. data.value) else table.insert(requestQueue, 1, data) print("Retrying: " .. data.sensorId .. " = " .. data.value) end end end)
require "variables" globalHeaders = "Host: " .. apiHost .. "\r\nAuthorization: Bearer " .. auth_token .. "\r\nContent-Type: application/json\r\n" -- Iterate through each configured sensor (from variables.lua) and set up trigger on its corresponding pin for i,sensor in pairs(sensors) do gpio.mode(sensor.gpioPin, gpio.INPUT, gpio.PULLUP) sensor.state = gpio.read(sensor.gpioPin) gpio.trig(sensor.gpioPin, "both", function (level) local newState = gpio.read(sensor.gpioPin) if sensor.state ~= newState then sensor.state = newState print(sensor.name .. " pin is " .. sensor.state) queueRequest(sensor.deviceId, sensor.state) end end) end requestQueue = {} function queueRequest(sensorId, value) local requestData = { sensorId = sensorId, value = value } table.insert(requestQueue, requestData) end function sendRequest(sensorData) local payload = [[{"sensor_id":"]] .. sensorData.sensorId .. [[","state":]] .. sensorData.value .. "}" local headers = globalHeaders .. "Content-Length: " .. string.len(payload) .. "\r\n" http.post( apiHost .. apiEndpoint, headers, payload, function(code, data) if code > 201 then print("Error " .. code .. " posting " .. sensorData.sensorId .. ", retrying") table.insert(requestQueue, 1, sensorData) end end) end tmr.create():alarm(500, tmr.ALARM_AUTO, function() local data = table.remove(requestQueue, 1) if data then if pcall(sendRequest, data) then print("Success: " .. data.sensorId .. " = " .. data.value) else table.insert(requestQueue, 1, data) print("Retrying: " .. data.sensorId .. " = " .. data.value) end end end)
fix queueing bug; add some explanitory comments
fix queueing bug; add some explanitory comments
Lua
mit
heythisisnate/nodemcu-smartthings
6f7b7fb6466541e3f9d5c40b96bce8257b89474e
lua/plugins/dap.lua
lua/plugins/dap.lua
local exepath = require'utils.files'.exepath local load_module = require'utils.helpers'.load_module local getcwd = require'utils.files'.getcwd local dap = load_module'dap' if not dap then return false end local set_autocmd = require'neovim.autocmds'.set_autocmd local set_command = require'neovim.commands'.set_command local set_mapping = require'neovim.mappings'.set_mapping local function pythonPath() -- debugpy supports launching an application with a different interpreter -- then the one used to launch debugpy itself. -- The code below looks for a `venv` or `.venv` folder in the current directly -- and uses the python within. -- You could adapt this - to for example use the `VIRTUAL_ENV` environment variable. local cwd = getcwd() if vim.env.VIRTUAL_ENV then return vim.env.VIRTUAL_ENV .. '/bin/python' elseif vim.fn.executable(cwd .. '/venv/bin/python') == 1 then return cwd .. '/venv/bin/python' elseif vim.fn.executable(cwd .. '/.venv/bin/python') == 1 then return cwd .. '/.venv/bin/python' end return exepath('python3') or exepath('python') end dap.adapters.python = { type = 'executable'; command = pythonPath(); args = { '-m', 'debugpy.adapter' }; } dap.configurations.python = { { -- The first three options are required by nvim-dap type = 'python'; -- the type here established the link to the adapter definition: `dap.adapters.python` request = 'launch'; name = "Launch file"; -- Options below are for debugpy, see -- https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings for supported options program = "${file}"; -- This configuration will launch the current file if used. pythonPath = pythonPath; }, } local lldb = exepath('lldb-vscode') or exepath('lldb-vscode-11') if lldb then dap.adapters.lldb = { type = 'executable', command = lldb, name = "lldb" } dap.configurations.cpp = { { name = "Launch", type = "lldb", request = "launch", program = function() return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/', 'file') end, cwd = '${workspaceFolder}', stopOnEntry = false, args = {}, -- if you change `runInTerminal` to true, you might need to change the yama/ptrace_scope setting: -- -- echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope -- -- Otherwise you might get the following error: -- -- Error on launch: Failed to attach to the target process -- -- But you should be aware of the implications: -- https://www.kernel.org/doc/html/latest/admin-guide/LSM/Yama.html runInTerminal = false, }, } -- If you want to use this for rust and c, add something like this: dap.configurations.c = dap.configurations.cpp dap.configurations.rust = dap.configurations.cpp end vim.fn.sign_define('DapBreakpoint', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapLogPoint', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapStopped', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapBreakpointRejected', {text='🛑', texthl='', linehl='', numhl=''}) set_autocmd{ event = 'Filetype', pattern = 'dap-repl', cmd = "lua require('dap.ext.autocompl').attach()", group = 'DapConfig', } -- DAP APIs -- -- dap.continue() -- dap.run() -- dap.run_last() -- dap.launch() -- dap.stop() -- dap.disconnect() -- dap.attach() -- dap.set_breakpoint() -- dap.toggle_breakpoint() -- dap.list_breakpoints() -- dap.set_exception_breakpoints() -- dap.step_over() -- dap.step_into() -- dap.step_out() -- dap.step_back() -- dap.pause() -- dap.reverse_continue() -- dap.up() -- dap.down() -- dap.goto_({line}) -- dap.run_to_cursor() -- dap.set_log_level() -- dap.session() -- dap.status() -- -- dap.repl.open() -- dap.repl.toggle() -- dap.repl.close() -- -- require('dap.ui.variables').hover() -- require('dap.ui.variables').scopes() -- require('dap.ui.variables').visual_hover() -- require('dap.ui.variables').toggle_multiline_display() local function list_breakpoints() dap.list_breakpoints() require'utils'.helpers.toggle_qf('qf') end local args = {noremap = true, silent = true} set_mapping{ mode = 'n', lhs = '<F5>', rhs = require'dap'.continue, args = args, } set_mapping{ mode = 'n', lhs = '<F4>', rhs = require'dap'.stop, args = args, } set_mapping{ mode = 'n', lhs = '<F10>', rhs = require'dap'.run_to_cursor, args = args, } set_mapping{ mode = 'n', lhs = ']s', rhs = require'dap'.step_over, args = args, } set_mapping{ mode = 'n', lhs = ']S', rhs = require'dap'.step_into, args = args, } set_mapping{ mode = 'n', lhs = '[s', rhs = require'dap'.step_out, args = args, } set_mapping{ mode = 'n', lhs = '=s', rhs = require'dap'.toggle_breakpoint, args = args, } set_mapping{ mode = 'n', lhs = '=r', rhs = require'dap'.repl.toggle, args = args, } set_mapping{ mode = 'n', lhs = '=b', rhs = list_breakpoints, args = args, } set_mapping{ mode = 'n', lhs = 'gK', rhs = require('dap.ui.widgets').hover, args = args, } set_command{ lhs = 'DapToggleBreakpoint', rhs = require'dap'.toggle_breakpoint, args = { force = true, } } set_command{ lhs = 'DapRun2Cursor', rhs = require'dap'.run_to_cursor, args = { force = true, } } set_command{ lhs = 'DapBreakpoint', rhs = require'dap'.set_breakpoint, args = { force = true, } } set_command{ lhs = 'DapListBreakpoint', rhs = list_breakpoints, args = { force = true, } } set_command{ lhs = 'DapStart', rhs = require'dap'.continue, args = { force = true, } } set_command{ lhs = 'DapStop', rhs = require'dap'.stop, args = { force = true, } } set_command{ lhs = 'DapContinue', rhs = require'dap'.continue, args = { force = true, } } set_command{ lhs = 'DapRepl', rhs = require'dap'.repl.toggle, args = { force = true, } } set_command{ lhs = 'DapInfo', rhs = require('dap.ui.widgets').hover, args = { force = true, } } return true
local exepath = require'utils.files'.exepath local load_module = require'utils.helpers'.load_module local getcwd = require'utils.files'.getcwd local dap = load_module'dap' if not dap then return false end local set_autocmd = require'neovim.autocmds'.set_autocmd local set_command = require'neovim.commands'.set_command local set_mapping = require'neovim.mappings'.set_mapping local function pythonPath() -- debugpy supports launching an application with a different interpreter -- then the one used to launch debugpy itself. -- The code below looks for a `venv` or `.venv` folder in the current directly -- and uses the python within. -- You could adapt this - to for example use the `VIRTUAL_ENV` environment variable. local cwd = getcwd() if vim.env.VIRTUAL_ENV then return vim.env.VIRTUAL_ENV .. '/bin/python' elseif vim.fn.executable(cwd .. '/venv/bin/python') == 1 then return cwd .. '/venv/bin/python' elseif vim.fn.executable(cwd .. '/.venv/bin/python') == 1 then return cwd .. '/.venv/bin/python' end return exepath('python3') or exepath('python') end dap.adapters.python = { type = 'executable'; command = pythonPath(); args = { '-m', 'debugpy.adapter' }; } dap.configurations.python = { { -- The first three options are required by nvim-dap type = 'python'; -- the type here established the link to the adapter definition: `dap.adapters.python` request = 'launch'; name = "Launch file"; -- Options below are for debugpy, see -- https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings for supported options program = "${file}"; -- This configuration will launch the current file if used. pythonPath = pythonPath; }, } local lldb = exepath('lldb-vscode') or exepath('lldb-vscode-11') if lldb then dap.adapters.lldb = { type = 'executable', command = lldb, name = "lldb" } dap.configurations.cpp = { { name = "Launch", type = "lldb", request = "launch", program = function() return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/', 'file') end, cwd = '${workspaceFolder}', stopOnEntry = false, args = {}, -- if you change `runInTerminal` to true, you might need to change the yama/ptrace_scope setting: -- -- echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope -- -- Otherwise you might get the following error: -- -- Error on launch: Failed to attach to the target process -- -- But you should be aware of the implications: -- https://www.kernel.org/doc/html/latest/admin-guide/LSM/Yama.html runInTerminal = false, }, } -- If you want to use this for rust and c, add something like this: dap.configurations.c = dap.configurations.cpp dap.configurations.rust = dap.configurations.cpp end vim.fn.sign_define('DapBreakpoint', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapLogPoint', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapStopped', {text='🛑', texthl='', linehl='', numhl=''}) -- vim.fn.sign_define('DapBreakpointRejected', {text='🛑', texthl='', linehl='', numhl=''}) set_autocmd{ event = 'Filetype', pattern = 'dap-repl', cmd = "lua require('dap.ext.autocompl').attach()", group = 'DapConfig', } -- DAP APIs -- -- dap.continue() -- dap.run() -- dap.run_last() -- dap.launch() -- dap.stop() -- dap.disconnect() -- dap.attach() -- dap.set_breakpoint() -- dap.toggle_breakpoint() -- dap.list_breakpoints() -- dap.set_exception_breakpoints() -- dap.step_over() -- dap.step_into() -- dap.step_out() -- dap.step_back() -- dap.pause() -- dap.reverse_continue() -- dap.up() -- dap.down() -- dap.goto_({line}) -- dap.run_to_cursor() -- dap.set_log_level() -- dap.session() -- dap.status() -- -- dap.repl.open() -- dap.repl.toggle() -- dap.repl.close() -- -- require('dap.ui.variables').hover() -- require('dap.ui.variables').scopes() -- require('dap.ui.variables').visual_hover() -- require('dap.ui.variables').toggle_multiline_display() local function list_breakpoints() dap.list_breakpoints() require'utils'.helpers.toggle_qf('qf') end local args = {noremap = true, silent = true} set_mapping{ mode = 'n', lhs = '<F5>', rhs = require'dap'.continue, args = args, } set_mapping{ mode = 'n', lhs = '<F4>', rhs = require'dap'.stop, args = args, } set_mapping{ mode = 'n', lhs = '<F10>', rhs = require'dap'.run_to_cursor, args = args, } set_mapping{ mode = 'n', lhs = ']s', rhs = require'dap'.step_over, args = args, } set_mapping{ mode = 'n', lhs = ']S', rhs = require'dap'.step_into, args = args, } set_mapping{ mode = 'n', lhs = '[s', rhs = require'dap'.step_out, args = args, } set_mapping{ mode = 'n', lhs = '=b', rhs = require'dap'.toggle_breakpoint, args = args, } set_mapping{ mode = 'n', lhs = '=r', rhs = require'dap'.repl.toggle, args = args, } set_mapping{ mode = 'n', lhs = '=L', rhs = list_breakpoints, args = args, } set_mapping{ mode = 'n', lhs = 'gK', rhs = require('dap.ui.widgets').hover, args = args, } set_command{ lhs = 'DapToggleBreakpoint', rhs = require'dap'.toggle_breakpoint, args = { force = true, } } set_command{ lhs = 'DapRun2Cursor', rhs = require'dap'.run_to_cursor, args = { force = true, } } set_command{ lhs = 'DapBreakpoint', rhs = require'dap'.set_breakpoint, args = { force = true, } } set_command{ lhs = 'DapListBreakpoint', rhs = list_breakpoints, args = { force = true, } } set_command{ lhs = 'DapStart', rhs = require'dap'.continue, args = { force = true, } } set_command{ lhs = 'DapStop', rhs = require'dap'.stop, args = { force = true, } } set_command{ lhs = 'DapContinue', rhs = require'dap'.continue, args = { force = true, } } set_command{ lhs = 'DapRepl', rhs = require'dap'.repl.toggle, args = { force = true, } } set_command{ lhs = 'DapInfo', rhs = require('dap.ui.widgets').hover, args = { force = true, } } set_command{ lhs = 'DapStepOver', rhs = function(args) require'dap'.step_over() end, args = {nargs = '?', force = true, } } set_command{ lhs = 'DapStepInto', rhs = function(args) require'dap'.step_into() end, args = {nargs = '?', force = true, } } set_command{ lhs = 'DapStepOut', rhs = function(args) require'dap'.step_out() end, args = {nargs = '?', force = true, } } return true
fix: Dap map conflict
fix: Dap map conflict
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
e2e016f251d281c9f83b8ad116c54a3b3815a7b6
hammerspoon/smart_modifier_keys.lua
hammerspoon/smart_modifier_keys.lua
-- Make the modifiers keys smarter: -- Tap ctrl -> esc. -- Tap shift -> switch input method. -- Whether ctrl and shift is being pressed alone. local ctrlPressed = 0 local shiftPressed = 0 hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(e) local modifiers = e:getFlags() local events_to_post = {} if modifiers['ctrl'] then ctrlPressed = true else if ctrlPressed then -- Ctrl was tapped, send an esc key. events_to_post = { hs.eventtap.event.newKeyEvent(nil, "escape", true), hs.eventtap.event.newKeyEvent(nil, "escape", false), } end ctrlPressed = false end if modifiers['shift'] then shiftPressed = true else if shiftPressed then -- Shift was tapped, switch input method (cmd + space). events_to_post = { hs.eventtap.event.newKeyEvent({"cmd"}, "space", true), hs.eventtap.event.newKeyEvent({"cmd"}, "space", false), } end shiftPressed = false end return false, events_to_post end):start() hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(e) -- If a non-modifier key is pressed, reset these two flags. ctrlPressed = false shiftPressed = false end):start()
-- Make the modifiers keys smarter: -- Tap ctrl -> esc. -- Tap shift -> switch input method. -- Whether ctrl and shift is being pressed alone. local ctrlPressed = false local shiftPressed = false local prevModifiers = {} local log = hs.logger.new('smart_modifier_keys','debug') hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(e) local events_to_post = nil local modifiers = e:getFlags() local count = 0 for _, __ in pairs(modifiers) do count = count + 1 end -- Check `ctrl` key. if modifiers['ctrl'] and not prevModifiers['ctrl'] and count == 1 then ctrlPressed = true else if count == 0 and ctrlPressed then -- Ctrl was tapped alone, send an esc key. events_to_post = { hs.eventtap.event.newKeyEvent(nil, "escape", true), hs.eventtap.event.newKeyEvent(nil, "escape", false), } end ctrlPressed = false end -- Check `shift` key. if modifiers['shift'] and not prevModifiers['shift'] and count == 1 then shiftPressed = true else if count == 0 and shiftPressed then -- Shift was tapped alone, switch input method (cmd + space). events_to_post = { hs.eventtap.event.newKeyEvent({"cmd"}, "space", true), hs.eventtap.event.newKeyEvent({"cmd"}, "space", false), } end shiftPressed = false end prevModifiers = modifiers return false, events_to_post end):start() hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(e) -- If a non-modifier key is pressed, reset these two flags. ctrlPressed = false shiftPressed = false end):start()
[hs] Fix smart_modifier_keys
[hs] Fix smart_modifier_keys
Lua
mit
raulchen/dotfiles,raulchen/dotfiles
3bf73017c5ff25dcef26e7be87b0872e79ba54ef
src/main.lua
src/main.lua
push = require('lib/push/push') lt = require('lib/lovetoys/lovetoys') lt.initialize({ globals = true, debug = true }) debug = false State = require('lib/State') Stack = require('lib/StackHelper') Vector = require('lib/vector') local Resources = require('lib/Resources') require('lib/tables') require("components/Drawable") require("components/Physical") require("components/SwarmMember") require("components/HasEnemy") require("components/Weapon") require("components/Bullet") require("components/Shield") require("components/Health") require("components/Particles") require("components/Mothership") require("components/LayeredDrawable") require("components/Transformable") require("components/Animation") require("components/LaserBeam") require("components/HitIndicator") require("components/Pulse") local MenuState = require('states/MenuState') function love.load() love.graphics.setDefaultFilter('nearest', 'nearest', 0) glyph_string = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=[]\\,./;')!@#$%^&*(+{}!<>?:\"" font = love.graphics.newImageFont('assets/img/font.png', glyph_string, 2) love.graphics.setFont(font) stack = Stack() stack:push(MenuState()) resources = Resources() resources:addImage('fighter', 'assets/img/fighterConfig/fighterTiny.png') resources:addImage('fighter_missile', 'assets/img/fighterConfig/missile.png') resources:addImage('mask_base', 'assets/img/player/colorBlackSmall.png') resources:addImage('block_particle', 'assets/img/block_particle.png') resources:addImage('round_particle', 'assets/img/round_particle.png') resources:addImage('stars_bg', 'assets/img/stars_bg.png') resources:addImage('stars_90', 'assets/img/stars_90.png') resources:addImage('stars_180', 'assets/img/stars_180.png') resources:addImage('core2', 'assets/img/maskConfig/core2Small.png') resources:addImage('eyes3', 'assets/img/maskConfig/eyes3Small.png') resources:addImage('eyes4', 'assets/img/maskConfig/eyes4Small.png') resources:addImage('explosion_1', 'assets/img/fighterConfig/explosion_1.png') resources:addImage('explosion_2', 'assets/img/fighterConfig/explosion_2.png') resources:addImage('explosion_3', 'assets/img/fighterConfig/explosion_3.png') resources:addImage('explosion_4', 'assets/img/fighterConfig/explosion_4.png') resources:addImage('explosion_5', 'assets/img/fighterConfig/explosion_5.png') resources:addMusic('bg', 'assets/music/glowing_geometry.mp3') resources:load() require('items') resources.music.bg:setLooping(true) -- love.audio.play(resources.music.bg) local game_width, game_height = 512, 448 local window_width, window_height = love.window.getDesktopDimensions() push:setupScreen(game_width, game_height, window_width * 0.8, window_height * 0.8, {fullscreen=false, resizable=true}) end function love.update(dt) stack:current():update(dt) end function love.keypressed(key) if key == "escape" then love.event.quit() end if key == "0" then debug = not debug end stack:current():keypressed(key) end function love.textinput(text) stack:current():textinput(text) end function love.draw() push:apply('start') stack:current():draw() push:apply('end') end function love.resize(w, h) push:resize(w, h) end
push = require('lib/push/push') lt = require('lib/lovetoys/lovetoys') lt.initialize({ globals = true, debug = true }) debug = false State = require('lib/State') Stack = require('lib/StackHelper') Vector = require('lib/vector') local Resources = require('lib/Resources') require('lib/tables') require("components/Drawable") require("components/Physical") require("components/SwarmMember") require("components/HasEnemy") require("components/Weapon") require("components/Bullet") require("components/Shield") require("components/Health") require("components/Particles") require("components/Mothership") require("components/LayeredDrawable") require("components/Transformable") require("components/Animation") require("components/LaserBeam") require("components/HitIndicator") require("components/Pulse") local MenuState = require('states/MenuState') function love.load() love.graphics.setDefaultFilter('nearest', 'nearest', 0) glyph_string = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=[]\\,./;')!@#$%^&*(+{}!<>?:\"" font = love.graphics.newImageFont('assets/img/font.png', glyph_string, 2) love.graphics.setFont(font) stack = Stack() stack:push(MenuState()) resources = Resources() resources:addImage('fighter', 'assets/img/fighterConfig/fighterTiny.png') resources:addImage('fighter_missile', 'assets/img/fighterConfig/missile.png') resources:addImage('mask_base', 'assets/img/player/colorBlackSmall.png') resources:addImage('block_particle', 'assets/img/block_particle.png') resources:addImage('round_particle', 'assets/img/round_particle.png') resources:addImage('stars_bg', 'assets/img/stars_bg.png') resources:addImage('stars_90', 'assets/img/stars_90.png') resources:addImage('stars_180', 'assets/img/stars_180.png') resources:addImage('core2', 'assets/img/player/core2Small.png') resources:addImage('eyes3', 'assets/img/player/eyes3Small.png') resources:addImage('eyes4', 'assets/img/player/eyes4Small.png') resources:addImage('explosion_1', 'assets/img/fighterConfig/explosion_1.png') resources:addImage('explosion_2', 'assets/img/fighterConfig/explosion_2.png') resources:addImage('explosion_3', 'assets/img/fighterConfig/explosion_3.png') resources:addImage('explosion_4', 'assets/img/fighterConfig/explosion_4.png') resources:addImage('explosion_5', 'assets/img/fighterConfig/explosion_5.png') resources:addMusic('bg', 'assets/music/glowing_geometry.mp3') resources:load() require('items') resources.music.bg:setLooping(true) -- love.audio.play(resources.music.bg) local game_width, game_height = 512, 448 local window_width, window_height = love.window.getDesktopDimensions() push:setupScreen(game_width, game_height, window_width * 0.8, window_height * 0.8, {fullscreen=false, resizable=true}) end function love.update(dt) stack:current():update(dt) end function love.keypressed(key) if key == "escape" then love.event.quit() end if key == "0" then debug = not debug end stack:current():keypressed(key) end function love.textinput(text) stack:current():textinput(text) end function love.draw() push:apply('start') stack:current():draw() push:apply('end') end function love.resize(w, h) push:resize(w, h) end
Fix image names
Fix image names
Lua
mit
alexd2580/igjam2016,alexd2580/igjam2016
702479c177411cf6fc7d5e3b10c69854615281c8
mod_register_json/mod_register_json.lua
mod_register_json/mod_register_json.lua
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local usermanager = require "core.usermanager"; local b64_decode = require "util.encodings".base64.decode; local json_decode = require "util.json".decode; module.host = "*" -- HTTP/BOSH Servlets need to be global. -- Pick up configuration. local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted"; local throttle_time = module:get_option("reg_servlet_ttime") or false; local whitelist = module:get_option("reg_servlet_wl") or {}; local blacklist = module:get_option("reg_servlet_bl") or {}; local recent_ips = {}; -- Begin for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end local function http_response(code, message, extra_headers) local response = { status = code .. " " .. message; body = message .. "\n"; } if extra_headers then response.headers = extra_headers; end return response end local function handle_req(method, body, request) if request.method ~= "POST" then return http_response(405, "Bad method...", {["Allow"] = "POST"}); end if not request.headers["authorization"] then return http_response(401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization :match("[^ ]*$") or ""):match("([^:]*):(.*)"); user = jid_prep(user); if not user or not password then return http_response(400, "What's this..?"); end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(401, "Negative."); end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(401, "Who the hell are you?! Guards!"); end local req_body; pcall(function() req_body = json.decode(body) end); -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]) return http_response(401, "I obey only to my masters... Have a nice day."); else -- Various sanity checks. if req_body == nil then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); end -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end if throttle_time and not whitelist[req_body["ip"]] then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = { time = os_time(), count = 1 }; else local ip = recent_ips[req_body["ip"]]; ip.count = ip.count + 1; if os_time() - ip.time < throttle_time then ip.time = os_time(); module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]); return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again."); end ip.time = os_time(); end end -- We first check if the supplied username for registration is already there. if not usermanager.user_exists(req_body["username"], req_body["host"]) then usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]); module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]); return http_response(200, "Done."); else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]); return http_response(409, "User already exists."); end end end -- Set it up! local function setup() local ports = module:get_option("reg_servlet_port") or { 9280 }; local base_name = module:get_option("reg_servlet_base") or "register_account"; local ssl_cert = module:get_option("reg_servlet_sslcert") or false; local ssl_key = module:get_option("reg_servlet_sslkey") or false; if not ssl_cert or not ssl_key then require "net.httpserver".new_from_config(ports, handle_req, { base = base_name }); else if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name }); end end if prosody.start_time then -- already started setup(); else prosody.events.add_handler("server-started", setup); end
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local jid_prep = require "util.jid".prep; local jid_split = require "util.jid".split; local usermanager = require "core.usermanager"; local b64_decode = require "util.encodings".base64.decode; local json_decode = require "util.json".decode; module.host = "*" -- HTTP/BOSH Servlets need to be global. -- Pick up configuration. local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted"; local throttle_time = module:get_option("reg_servlet_ttime") or false; local whitelist = module:get_option("reg_servlet_wl") or {}; local blacklist = module:get_option("reg_servlet_bl") or {}; local recent_ips = {}; -- Begin for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end local function http_response(code, message, extra_headers) local response = { status = code .. " " .. message; body = message .. "\n"; } if extra_headers then response.headers = extra_headers; end return response end local function handle_req(method, body, request) if request.method ~= "POST" then return http_response(405, "Bad method...", {["Allow"] = "POST"}); end if not request.headers["authorization"] then return http_response(401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization :match("[^ ]*$") or ""):match("([^:]*):(.*)"); user = jid_prep(user); if not user or not password then return http_response(400, "What's this..?"); end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(401, "Negative."); end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(401, "Who the hell are you?! Guards!"); end local req_body; -- We check that what we have is valid JSON wise else we throw an error... if not pcall(function() req_body = json_decode(body) end) then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); else -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]); return http_response(401, "I obey only to my masters... Have a nice day."); else -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist[req_body["ip"]] then then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end if throttle_time and not whitelist[req_body["ip"]] then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = { time = os_time(), count = 1 }; else local ip = recent_ips[req_body["ip"]]; ip.count = ip.count + 1; if os_time() - ip.time < throttle_time then ip.time = os_time(); module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]); return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again."); end ip.time = os_time(); end end -- We first check if the supplied username for registration is already there. if not usermanager.user_exists(req_body["username"], req_body["host"]) then usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]); module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]); return http_response(200, "Done."); else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]); return http_response(409, "User already exists."); end end end end -- Set it up! local function setup() local ports = module:get_option("reg_servlet_port") or { 9280 }; local base_name = module:get_option("reg_servlet_base") or "register_account"; local ssl_cert = module:get_option("reg_servlet_sslcert") or false; local ssl_key = module:get_option("reg_servlet_sslkey") or false; if not ssl_cert or not ssl_key then require "net.httpserver".new_from_config(ports, handle_req, { base = base_name }); else if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name }); end end if prosody.start_time then -- already started setup(); else prosody.events.add_handler("server-started", setup); end
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
Lua
mit
mardraze/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,Craige/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,prosody-modules/import,either1/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,prosody-modules/import,guilhem/prosody-modules
61d57b4b55c2a942b11b66047e05eba36f00c6c4
server/scene-src/db.lua
server/scene-src/db.lua
local core = require "silly.core" local env = require "silly.env" local zproto = require "zproto" local property = require "protocol.property" local redis = require "redis" local format = string.format local tunpack = table.unpack local M = {} local dbproto = zproto:parse [[ idcount { .id:integer 1 .count:integer 2 } role_basic { .uid:integer 1 .name:string 2 .exp:integer 3 .level:integer 4 .gold:integer 5 .hp:integer 6 .magic:integer 7 } role_bag { .list:idcount[id] 1 } role_prop { .atk:integer 1 .def:integer 2 .matk:integer 3 .mdef:integer 4 } role_skill { skill { .skillid:integer 1 .skilllv:integer 2 } .active:skill[skillid] 2 .passive:skill[skillid] 3 } ]] local dbinst local proto_role_basic = "role_basic" local proto_role_bag = "role_bag" local proto_role_prop = "role_prop" local proto_role_skill = "role_skill" local dbk_role = "role:%s" local dbk_role_basic = "basic" local dbk_role_bag = "bag" local dbk_role_prop = "prop" local dbk_role_skill = "skill" local DIRTY_BASIC = 0x01 local DIRTY_BAG = 0x02 local DIRTY_PROP = 0x04 local DIRTY_SKILL = 0x05 local DIRTY_LAND = 0x06 local DIRTY_ALL = DIRTY_BASIC | DIRTY_BAG | DIRTY_PROP | DIRTY_SKILL local rolecache = {} local roledirtycount = 0 local roledirty = {} local part_proto = { [dbk_role_basic] = proto_role_basic, [dbk_role_bag] = proto_role_bag, [dbk_role_prop] = proto_role_prop, [dbk_role_skill] = proto_role_skill, } local part_flag = { [dbk_role_basic] = DIRTY_BASIC, [dbk_role_bag] = DIRTY_BAG, [dbk_role_prop] = DIRTY_PROP, [dbk_role_skill] = DIRTY_SKILL, } function M.rolecreate(uid, name) local basic = { uid = uid, name = name, exp = 0, level = 0, gold = 100, hp = 90, magic = 100, coord_x = 10, coord_z = 10, } local bag = { list = { [10000] = { id = 10000, count = 100 }, [10001] = { id = 10001, count = 101, } } } local prop = { atk = 99, def = 98, matk = 89, mdef = 88, } local skill = { active = { [10000000] = { skillid = 10000000, skilllv = 1, }, [10001000] = { skillid = 10001000, skilllv = 1, }, } } role = { basic = basic, bag = bag, prop = prop, skill = skill, } rolecache[uid] = role roledirty[uid] = DIRTY_ALL return role end local cmdbuffer = {} function M.roleload(uid) local role = rolecache[uid] if role then local dirty = roledirty[uid] if dirty then roledirty[uid] = dirty & (~DIRTY_LAND) end return role end local k = format(dbk_role, uid) local ok, dat = dbinst:hgetall(k) if not ok or #dat == 0 then return end rolecache[uid] = dat for i = 1, #dat, 2 do local j = i + 1 local k = dat[i] local v = dat[j] dat[i] = nil dat[j] = nil local protok = part_proto[k] local info = dbproto:decode(protok, v) dat[k] = info end return dat end function M.roleget(uid) return rolecache[uid] end local function roleupdate(uid, role, dirty) local count = 0 local k = format(dbk_role, uid) for k, flag in pairs(part_flag) do if dirty & flag ~= 0 then count = count + 1 cmdbuffer[count] = k count = count + 1 cmdbuffer[count] = dbproto:encode(part_proto[k], role[k]) end end if count == 0 then return end local ok, err = dbinst:hmset(k, tunpack(cmdbuffer, 1, count)) for i = 1, count do cmdbuffer[i] = nil end if not ok then print("roleupdate", err) end end function M.roleland(uid) local role = rolecache[uid] if not role then return end local dirty = roledirty[uid] if not dirty then rolecache[uid] = nil return end if dirty == 0 then rolecache[uid] = nil roledirty[uid] = nil return end roledirty[uid] = dirty | DIRTY_LAND end local function writedb() roledirtycount = 0 for uid, dirty in pairs(roledirty) do local role = rolecache[uid] roledirty[uid] = nil roleupdate(uid, role, dirty) if dirty & DIRTY_LAND ~= 0 then roledirty[uid] = nil end end end local function try_get(dbk) return function(uid) local role = rolecache[uid] if not role then return nil end return role[dbk] end end local function role_dirty(flag) return function(uid) local origin = roledirty[uid] if not origin then roledirty[uid] = flag else roledirty[uid] = origin | flag end roledirtycount = roledirtycount + 1 if roledirtycount > 300 then roledirtycount = 0 core.fork(writedb) end end end M.rolebasic = try_get(dbk_role_basic) M.rolebag = try_get(dbk_role_bag) M.roleprop = try_get(dbk_role_prop) M.roleskill = try_get(dbk_role_skill) M.roledirtybasic = role_dirty(DIRTY_BASIC) M.roledirtybag = role_dirty(DIRTY_BAG) M.roledirtyprop = role_dirty(DIRTY_PROP) M.roledirtyskill = role_dirty(DIRTY_SKILL) local timer_sec = 10000 local function dbtimer() local ok, err = core.pcall(writedb) if not ok then print(err) end core.timeout(timer_sec, dbtimer) end function M.start() local err dbinst, err = redis:connect { addr = env.get("dbport") } dbinst:select(9) dbtimer() return dbinst and true or false end return M
local core = require "silly.core" local env = require "silly.env" local zproto = require "zproto" local property = require "protocol.property" local redis = require "redis" local format = string.format local tunpack = table.unpack local M = {} local dbproto = zproto:parse [[ idcount { .id:integer 1 .count:integer 2 } role_basic { .uid:integer 1 .name:string 2 .exp:integer 3 .level:integer 4 .gold:integer 5 .hp:integer 6 .magic:integer 7 } role_bag { .list:idcount[id] 1 } role_prop { .atk:integer 1 .def:integer 2 .matk:integer 3 .mdef:integer 4 } role_skill { skill { .skillid:integer 1 .skilllv:integer 2 } .active:skill[skillid] 2 .passive:skill[skillid] 3 } ]] local dbinst local proto_role_basic = "role_basic" local proto_role_bag = "role_bag" local proto_role_prop = "role_prop" local proto_role_skill = "role_skill" local dbk_role = "role:%s" local dbk_role_basic = "basic" local dbk_role_bag = "bag" local dbk_role_prop = "prop" local dbk_role_skill = "skill" local DIRTY_BASIC = 0x01 local DIRTY_BAG = 0x02 local DIRTY_PROP = 0x04 local DIRTY_SKILL = 0x08 local DIRTY_LAND = 0x10 local DIRTY_ALL = DIRTY_BASIC | DIRTY_BAG | DIRTY_PROP | DIRTY_SKILL local rolecache = {} local roledirtycount = 0 local roledirty = {} local part_proto = { [dbk_role_basic] = proto_role_basic, [dbk_role_bag] = proto_role_bag, [dbk_role_prop] = proto_role_prop, [dbk_role_skill] = proto_role_skill, } local part_flag = { [dbk_role_basic] = DIRTY_BASIC, [dbk_role_bag] = DIRTY_BAG, [dbk_role_prop] = DIRTY_PROP, [dbk_role_skill] = DIRTY_SKILL, } function M.rolecreate(uid, name) local basic = { uid = uid, name = name, exp = 0, level = 0, gold = 100, hp = 90, magic = 100, coord_x = 10, coord_z = 10, } local bag = { list = { [10000] = { id = 10000, count = 100 }, [10001] = { id = 10001, count = 101, } } } local prop = { atk = 99, def = 98, matk = 89, mdef = 88, } local skill = { active = { [10000000] = { skillid = 10000000, skilllv = 1, }, [10001000] = { skillid = 10001000, skilllv = 1, }, } } role = { basic = basic, bag = bag, prop = prop, skill = skill, } rolecache[uid] = role roledirty[uid] = DIRTY_ALL print("db.rolecreate") return role end local cmdbuffer = {} function M.roleload(uid) local role = rolecache[uid] if role then local dirty = roledirty[uid] if dirty then roledirty[uid] = dirty & (~DIRTY_LAND) end return role end local k = format(dbk_role, uid) local ok, dat = dbinst:hgetall(k) if not ok or #dat == 0 then return end rolecache[uid] = dat for i = 1, #dat, 2 do local j = i + 1 local k = dat[i] local v = dat[j] dat[i] = nil dat[j] = nil local protok = part_proto[k] local info = dbproto:decode(protok, v) dat[k] = info end return dat end function M.roleget(uid) return rolecache[uid] end local function roleupdate(uid, role, dirty) local count = 0 local k = format(dbk_role, uid) print("roleupdate", dirty) for k, flag in pairs(part_flag) do if (dirty & flag) ~= 0 then count = count + 1 cmdbuffer[count] = k count = count + 1 print("roleupdate", uid, k) cmdbuffer[count] = dbproto:encode(part_proto[k], role[k]) end end if count == 0 then return end local ok, err = dbinst:hmset(k, tunpack(cmdbuffer, 1, count)) for i = 1, count do cmdbuffer[i] = nil end if not ok then print("roleupdate", err) end end function M.roleland(uid) local role = rolecache[uid] if not role then return end local dirty = roledirty[uid] if not dirty then rolecache[uid] = nil return end if dirty == 0 then rolecache[uid] = nil roledirty[uid] = nil return end roledirty[uid] = dirty | DIRTY_LAND end local function writedb() roledirtycount = 0 for uid, dirty in pairs(roledirty) do local role = rolecache[uid] roledirty[uid] = nil print("roleupdate dirty", dirty) roleupdate(uid, role, dirty) if (dirty & DIRTY_LAND) ~= 0 then roledirty[uid] = nil end end end local function try_get(dbk) return function(uid) local role = rolecache[uid] if not role then return nil end return role[dbk] end end local function role_dirty(flag) return function(uid) local origin = roledirty[uid] if not origin then roledirty[uid] = flag else roledirty[uid] = origin | flag end roledirtycount = roledirtycount + 1 if roledirtycount > 300 then roledirtycount = 0 core.fork(writedb) end end end M.rolebasic = try_get(dbk_role_basic) M.rolebag = try_get(dbk_role_bag) M.roleprop = try_get(dbk_role_prop) M.roleskill = try_get(dbk_role_skill) M.roledirtybasic = role_dirty(DIRTY_BASIC) M.roledirtybag = role_dirty(DIRTY_BAG) M.roledirtyprop = role_dirty(DIRTY_PROP) M.roledirtyskill = role_dirty(DIRTY_SKILL) local timer_sec = 10000 local function dbtimer() local ok, err = core.pcall(writedb) if not ok then print(err) end core.timeout(timer_sec, dbtimer) end function M.start() local err dbinst, err = redis:connect { addr = env.get("dbport") } dbinst:select(9) dbtimer() return dbinst and true or false end return M
bugfix: scene-src/db.lua incorrect dirty_flag
bugfix: scene-src/db.lua incorrect dirty_flag
Lua
mit
findstr/mmorpg-demo,findstr/mmorpg-demo
c95f54dc56b7fac9143291bc816d99abb5f48859
lua/entities/gmod_wire_cameracontroller.lua
lua/entities/gmod_wire_cameracontroller.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Camera Controller" ENT.WireDebugName = "Camera Controller" if CLIENT then return end -- No more client function ENT:Initialize() self.BaseClass.Initialize(self) self.Outputs = WireLib.CreateOutputs( self, { "On", "X", "Y", "Z", "XYZ [VECTOR]" } ) self.CamPlayer = self:GetPlayer() -- The player being shown the camera view. self.Active = false -- Whether the player is currently being shown the camera view. self.ZoomAmount = 75 -- The FOV of the player's view. self.Static = false -- Whether the camera controller has a separate camera entity. self.FLIR = false -- Whether infrared view is turned on. end function ENT:MakeCamera(oldcam) local cam = ents.Create(self.Static and "prop_physics" or "base_point") if not IsValid(cam) then return false end if self.Static then cam:SetModel(Model("models/dav0r/camera.mdl")) else -- By default, base_point isn't sent to the client. cam.UpdateTransmitState = function() return TRANSMIT_PVS end end if IsValid(oldcam) then cam:SetPos(oldcam:GetPos()) cam:SetAngles(oldcam:GetAngles()) else local offset = self.Static and (self:GetAngles():Up() * 64) or Vector() cam:SetPos( self:GetPos() + offset ) cam:SetAngles( self:GetAngles() ) end cam:Spawn() cam:Activate() if self.Static then constraint.NoCollide(self, cam, 0, 0) end -- If the camera is ever deleted by the user, we immediately recreate it cam:CallOnRemove(self:GetClass() .. self:EntIndex(), function(ent) if IsValid(self) then self:MakeCamera(ent) self:EnableCam(false) end end) self:TriggerInput("Activated", 0) self.CamEnt = cam self:UpdateMarks() return cam end function ENT:Setup(Static) self.Static = tobool(Static) if not IsValid(self.CamEnt) then self:MakeCamera() end if not IsValid(self.CamEnt) then return false end if self.Static then self.Inputs = WireLib.CreateInputs( self, { "Activated", "Zoom (1-90)", "FLIR" } ) else self.Inputs = WireLib.CreateInputs( self, { "Activated", "Zoom (1-90)", "X", "Y", "Z", "Pitch", "Yaw", "Roll", "Angle [ANGLE]", "Position [VECTOR]", "Direction [VECTOR]", "Parent [ENTITY]", "FLIR" } ) end end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.CamEnt) then self:MakeCamera() end local trace = util.QuickTrace(self.CamEnt:GetPos(), self.CamEnt:GetForward(), self.CamEnt) local hitPos = trace.HitPos or Vector() WireLib.TriggerOutput(self, "XYZ", hitPos) WireLib.TriggerOutput(self, "X", hitPos.x) WireLib.TriggerOutput(self, "Y", hitPos.y) WireLib.TriggerOutput(self, "Z", hitPos.z) self:NextThink(CurTime()+0.1) return true end function ENT:OnRemove() self:EnableCam(false) if IsValid(self.CamEnt) then self.CamEnt:RemoveCallOnRemove(self:GetClass() .. self:EntIndex()) self.CamEnt:Remove() end self.BaseClass.OnRemove(self) end function ENT:EnableCam(enabled) if not IsValid(self.CamPlayer) then self.CamPlayer = self:GetPlayer() end if not IsValid(self.CamPlayer) then return end if not IsValid(self.CamEnt) then enabled = false end if not self.Active then self.CamPlayer.OriginalFOV = self.CamPlayer:GetFOV() end self.CamPlayer.CamController = enabled and self or nil self.CamPlayer:SetViewEntity(enabled and self.CamEnt or self.CamPlayer) self.CamPlayer:SetFOV(enabled and self.ZoomAmount or self.CamPlayer.OriginalFOV or 75, 0.01 ) FLIR.enable(self.CamPlayer, enabled and self.FLIR) WireLib.TriggerOutput(self, "On", enabled and 1 or 0) self.Active = enabled end function ENT:TriggerInput( name, value ) if name == "Activated" then value = tobool(value) if value and IsValid(self.CamPod) then self.CamPlayer = self.CamPod:GetDriver() or nil end self:EnableCam(value) elseif name == "Zoom" then self.ZoomAmount = math.Clamp( value, 1, 90 ) if self.Active then self.CamPlayer:SetFOV( self.ZoomAmount, 0.01 ) end elseif name == "FLIR" then self.FLIR = tobool(value) self:EnableCam(self.Active) elseif name == "Direction" then self:TriggerInput("Angle", value:Angle()) elseif IsValid(self.CamEnt) then local pos = self.CamEnt:GetPos() local ang = self.CamEnt:GetAngles() if name == "Parent" then self.CamEnt:SetParent(IsValid(value) and value or nil) elseif name == "Position" then pos = value elseif name == "Angle" then ang = value elseif name == "X" then pos.x = value elseif name == "Y" then pos.y = value elseif name == "Z" then pos.z = value elseif name == "Pitch" then ang.p = value elseif name == "Yaw" then ang.y = value elseif name == "Roll" then ang.r = value end -- We unparent before moving the child entity if IsValid(self.CamEnt:GetParent()) then local parent = self:GetParent() self:SetParent(nil) end self.CamEnt:SetPos(pos) self.CamEnt:SetAngles(ang) if IsValid(self.CamEnt:GetParent()) then self:SetParent(parent) end end end hook.Add("PlayerLeaveVehicle", "gmod_wire_cameracontroller", function(player, vehicle) if IsValid(player.CamController) and player.CamController.CamPod == vehicle then player.CamController:EnableCam(false) end end) concommand.Add( "wire_cameracontroller_leave", function(player) if IsValid(player.CamController) then player.CamController:EnableCam(false) end end) function ENT:UpdateMarks() self.Marks = {} if IsValid(self.CamPod) then table.insert(self.Marks, self.CamPod) end if self.Static and IsValid(self.CamEnt) then table.insert(self.Marks, self.CamEnt) end WireLib.SendMarks(self) end function ENT:LinkEnt(pod) if not IsValid(pod) or not pod:IsVehicle() then return "Must link to a vehicle" end self.CamPod = pod self:UpdateMarks() return true end function ENT:UnlinkEnt() self.CamPod = nil self:UpdateMarks() return true end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) if IsValid(self.CamPod) then info.pod = self.CamPod:EntIndex() end if IsValid(self.CamEnt) and self.Static then info.cam = self.CamEnt:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.CamPod = GetEntByID(info.pod) -- Setup is called before ApplyDupeInfo, so we will already have spawned -- a camera by the time we restore the duped camera. if IsValid(self.CamEnt) then self.CamEnt:RemoveCallOnRemove(self:GetClass() .. self:EntIndex()) self.CamEnt:Remove() end self.CamEnt = GetEntByID(info.cam) self:UpdateMarks() end duplicator.RegisterEntityClass("gmod_wire_cameracontroller", WireLib.MakeWireEnt, "Data", "Static")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Camera Controller" ENT.WireDebugName = "Camera Controller" if CLIENT then return end -- No more client function ENT:Initialize() self.BaseClass.Initialize(self) self.Outputs = WireLib.CreateOutputs( self, { "On", "X", "Y", "Z", "XYZ [VECTOR]" } ) self.CamPlayer = self:GetPlayer() -- The player being shown the camera view. self.Active = false -- Whether the player is currently being shown the camera view. self.ZoomAmount = nil -- The FOV of the player's view. self.Static = false -- Whether the camera controller has a separate camera entity. self.FLIR = false -- Whether infrared view is turned on. end function ENT:MakeCamera(oldcam) local cam = ents.Create(self.Static and "prop_physics" or "base_point") if not IsValid(cam) then return false end if self.Static then cam:SetModel(Model("models/dav0r/camera.mdl")) else -- By default, base_point isn't sent to the client. cam.UpdateTransmitState = function() return TRANSMIT_PVS end end if IsValid(oldcam) then cam:SetPos(oldcam:GetPos()) cam:SetAngles(oldcam:GetAngles()) else local offset = self.Static and (self:GetAngles():Up() * 64) or Vector() cam:SetPos( self:GetPos() + offset ) cam:SetAngles( self:GetAngles() ) end cam:Spawn() cam:Activate() if self.Static then constraint.NoCollide(self, cam, 0, 0) end -- If the camera is ever deleted by the user, we immediately recreate it cam:CallOnRemove(self:GetClass() .. self:EntIndex(), function(ent) if IsValid(self) then self:MakeCamera(ent) self:EnableCam(false) end end) self:TriggerInput("Activated", 0) self.CamEnt = cam self:UpdateMarks() return cam end function ENT:Setup(Static) self.Static = tobool(Static) if not IsValid(self.CamEnt) then self:MakeCamera() end if not IsValid(self.CamEnt) then return false end if self.Static then self.Inputs = WireLib.CreateInputs( self, { "Activated", "Zoom (1-90)", "FLIR" } ) else self.Inputs = WireLib.CreateInputs( self, { "Activated", "Zoom (1-90)", "X", "Y", "Z", "Pitch", "Yaw", "Roll", "Angle [ANGLE]", "Position [VECTOR]", "Direction [VECTOR]", "Parent [ENTITY]", "FLIR" } ) end end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.CamEnt) then self:MakeCamera() end local trace = util.QuickTrace(self.CamEnt:GetPos(), self.CamEnt:GetForward(), self.CamEnt) local hitPos = trace.HitPos or Vector() WireLib.TriggerOutput(self, "XYZ", hitPos) WireLib.TriggerOutput(self, "X", hitPos.x) WireLib.TriggerOutput(self, "Y", hitPos.y) WireLib.TriggerOutput(self, "Z", hitPos.z) self:NextThink(CurTime()+0.1) return true end function ENT:OnRemove() self:EnableCam(false) if IsValid(self.CamEnt) then self.CamEnt:RemoveCallOnRemove(self:GetClass() .. self:EntIndex()) self.CamEnt:Remove() end self.BaseClass.OnRemove(self) end function ENT:EnableCam(enabled) if not IsValid(self.CamPlayer) then self.CamPlayer = self:GetPlayer() end if not IsValid(self.CamPlayer) then return end if not IsValid(self.CamEnt) then enabled = false end if not self.Active then self.CamPlayer.OriginalFOV = self.CamPlayer:GetFOV() end self.CamPlayer.CamController = enabled and self or nil self.CamPlayer:SetViewEntity(enabled and self.CamEnt or self.CamPlayer) if self.ZoomAmount then self.CamPlayer:SetFOV(enabled and self.ZoomAmount or self.CamPlayer.OriginalFOV or 75, 0.01 ) end FLIR.enable(self.CamPlayer, enabled and self.FLIR) WireLib.TriggerOutput(self, "On", enabled and 1 or 0) self.Active = enabled end function ENT:TriggerInput( name, value ) if name == "Activated" then value = tobool(value) if value and IsValid(self.CamPod) then self.CamPlayer = self.CamPod:GetDriver() or nil end self:EnableCam(value) elseif name == "Zoom" then self.ZoomAmount = math.Clamp( value, 1, 90 ) if self.Active then self.CamPlayer:SetFOV( self.ZoomAmount, 0.01 ) end elseif name == "FLIR" then self.FLIR = tobool(value) self:EnableCam(self.Active) elseif name == "Direction" then self:TriggerInput("Angle", value:Angle()) elseif IsValid(self.CamEnt) then local pos = self.CamEnt:GetPos() local ang = self.CamEnt:GetAngles() if name == "Parent" then self.CamEnt:SetParent(IsValid(value) and value or nil) elseif name == "Position" then pos = value elseif name == "Angle" then ang = value elseif name == "X" then pos.x = value elseif name == "Y" then pos.y = value elseif name == "Z" then pos.z = value elseif name == "Pitch" then ang.p = value elseif name == "Yaw" then ang.y = value elseif name == "Roll" then ang.r = value end -- We unparent before moving the child entity if IsValid(self.CamEnt:GetParent()) then local parent = self:GetParent() self:SetParent(nil) end self.CamEnt:SetPos(pos) self.CamEnt:SetAngles(ang) if IsValid(self.CamEnt:GetParent()) then self:SetParent(parent) end end end hook.Add("PlayerLeaveVehicle", "gmod_wire_cameracontroller", function(player, vehicle) if IsValid(player.CamController) and player.CamController.CamPod == vehicle then player.CamController:EnableCam(false) end end) concommand.Add( "wire_cameracontroller_leave", function(player) if IsValid(player.CamController) then player.CamController:EnableCam(false) end end) function ENT:UpdateMarks() self.Marks = {} if IsValid(self.CamPod) then table.insert(self.Marks, self.CamPod) end if self.Static and IsValid(self.CamEnt) then table.insert(self.Marks, self.CamEnt) end WireLib.SendMarks(self) end function ENT:LinkEnt(pod) if not IsValid(pod) or not pod:IsVehicle() then return "Must link to a vehicle" end self.CamPod = pod self:UpdateMarks() return true end function ENT:UnlinkEnt() self.CamPod = nil self:UpdateMarks() return true end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) if IsValid(self.CamPod) then info.pod = self.CamPod:EntIndex() end if IsValid(self.CamEnt) and self.Static then info.cam = self.CamEnt:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.CamPod = GetEntByID(info.pod) -- Setup is called before ApplyDupeInfo, so we will already have spawned -- a camera by the time we restore the duped camera. if IsValid(self.CamEnt) then self.CamEnt:RemoveCallOnRemove(self:GetClass() .. self:EntIndex()) self.CamEnt:Remove() end self.CamEnt = GetEntByID(info.cam) self:UpdateMarks() end duplicator.RegisterEntityClass("gmod_wire_cameracontroller", WireLib.MakeWireEnt, "Data", "Static")
Cam Controller: Stopped changing FOV if Zoom hasn't been set Fixes #437
Cam Controller: Stopped changing FOV if Zoom hasn't been set Fixes #437
Lua
apache-2.0
CaptainPRICE/wire,wiremod/wire,NezzKryptic/Wire,mitterdoo/wire,plinkopenguin/wiremod,rafradek/wire,dvdvideo1234/wire,bigdogmat/wire,immibis/wiremod,Python1320/wire,thegrb93/wire,notcake/wire,sammyt291/wire,garrysmodlua/wire,mms92/wire,Grocel/wire
533b3872ff3deec820ee7f10da913b2adc46f080
scen_edit/view/fields/numeric_field.lua
scen_edit/view/fields/numeric_field.lua
SCEN_EDIT.Include(SCEN_EDIT_VIEW_FIELDS_DIR .. "string_field.lua") NumericField = StringField:extends{} function NumericField:Update(source) local v = string.format(self.format, self.value) if source ~= self.editBox and not self.editBox.state.focused then self.editBox:SetText(v) end if source ~= self.lblValue then self.lblValue:SetCaption(v) end end function NumericField:Validate(value) local valid, value = self:super("Validate", value) if value then value = tonumber(value) end if value then if self.maxValue then value = math.min(self.maxValue, value) end if self.minValue then value = math.max(self.minValue, value) end return true, value end return nil end function NumericField:init(field) self.decimals = 2 self.value = 0 StringField.init(self, field) self.format = "%." .. tostring(self.decimals) .. "f" if self.step == nil then self.step = 1 if self.minValue and self.maxValue then self.step = (self.maxValue - self.minValue) / 200 end end local v = string.format(self.format, self.value) self.lblValue:SetCaption(v) self.button.OnMouseUp = { function(...) SCEN_EDIT.SetMouseCursor() self.lblValue.font:SetColor(1, 1, 1, 1) self.lblTitle.font:SetColor(1, 1, 1, 1) self.lblTitle:Invalidate() if self.startX and self.startY then Spring.WarpMouse(self.startX, self.startY) end self.startX = nil self.notClick = false self.ev:_OnEndChange(self.name) end } self.button.OnMouseMove = { function(obj, x, y, dx, dy, btn, ...) if btn == 1 then local vsx, vsy = Spring.GetViewGeometry() x, y = Spring.GetMouseState() local _, _, _, shift = Spring.GetModKeyState() if not self.startX then self.startX = x self.startY = y self.currentX = x self.lblValue.font:SetColor(0.96,0.83,0.09, 1) self.lblTitle.font:SetColor(0.96,0.83,0.09, 1) self.lblTitle:Invalidate() end self.currentX = x if math.abs(x - self.startX) > 4 then self.notClick = true self.ev:_OnStartChange(self.name) end if self.notClick then if shift then dx = dx * 0.1 end local value = self.value + dx * self.step self:Set(value, obj) end -- FIXME: This -could- be Spring.WarpMouse(self.startX, self.startY) but it doesn't seem to work well Spring.WarpMouse(vsx/2, vsy/2) SCEN_EDIT.SetMouseCursor("empty") end end } end
SCEN_EDIT.Include(SCEN_EDIT_VIEW_FIELDS_DIR .. "string_field.lua") NumericField = StringField:extends{} function NumericField:Update(source) local v = string.format(self.format, self.value) if source ~= self.editBox and not self.editBox.state.focused then self.editBox:SetText(v) end if source ~= self.lblValue then self.lblValue:SetCaption(v) end end function NumericField:Validate(value) local valid, value = self:super("Validate", value) if value then value = tonumber(value) end if value then if self.maxValue then value = math.min(self.maxValue, value) end if self.minValue then value = math.max(self.minValue, value) end return true, value end return nil end function NumericField:init(field) self.decimals = 2 self.value = 0 StringField.init(self, field) self.format = "%." .. tostring(self.decimals) .. "f" if self.step == nil then self.step = 1 if self.minValue and self.maxValue then self.step = (self.maxValue - self.minValue) / 200 end end local v = string.format(self.format, self.value) self.lblValue:SetCaption(v) self.editBox:SetText(v) self.button.OnMouseUp = { function(...) SCEN_EDIT.SetMouseCursor() self.lblValue.font:SetColor(1, 1, 1, 1) self.lblTitle.font:SetColor(1, 1, 1, 1) self.lblTitle:Invalidate() if self.startX and self.startY then Spring.WarpMouse(self.startX, self.startY) end self.startX = nil self.notClick = false self.ev:_OnEndChange(self.name) end } self.button.OnMouseMove = { function(obj, x, y, dx, dy, btn, ...) if btn == 1 then local vsx, vsy = Spring.GetViewGeometry() x, y = Spring.GetMouseState() local _, _, _, shift = Spring.GetModKeyState() if not self.startX then self.startX = x self.startY = y self.currentX = x self.lblValue.font:SetColor(0.96,0.83,0.09, 1) self.lblTitle.font:SetColor(0.96,0.83,0.09, 1) self.lblTitle:Invalidate() end self.currentX = x if math.abs(x - self.startX) > 4 then self.notClick = true self.ev:_OnStartChange(self.name) end if self.notClick then if shift then dx = dx * 0.1 end local value = self.value + dx * self.step self:Set(value, obj) end -- FIXME: This -could- be Spring.WarpMouse(self.startX, self.startY) but it doesn't seem to work well Spring.WarpMouse(vsx/2, vsy/2) SCEN_EDIT.SetMouseCursor("empty") end end } end
fix numeric field editbox value not being converted to text on init (causing crash); fix https://github.com/Spring-SpringBoard/SpringBoard-Core/issues/111
fix numeric field editbox value not being converted to text on init (causing crash); fix https://github.com/Spring-SpringBoard/SpringBoard-Core/issues/111
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
ae4dc14c8133bdce302282ac649d4060adc1c413
game/scripts/vscripts/heroes/hero_saitama/limiter.lua
game/scripts/vscripts/heroes/hero_saitama/limiter.lua
LinkLuaModifier("modifier_saitama_limiter_autocast", "heroes/hero_saitama/limiter.lua", LUA_MODIFIER_MOTION_NONE) saitama_limiter = class({ GetIntrinsicModifierName = function() return "modifier_saitama_limiter_autocast" end, }) function saitama_limiter:GetManaCost() return self:GetCaster():GetMaxMana() * self:GetSpecialValueFor("manacost_pct") * 0.01 + self:GetSpecialValueFor("manacost") end function saitama_limiter:CastFilterResult() local parent = self:GetCaster() return parent:GetModifierStackCount("modifier_saitama_limiter", parent) == 0 and UF_FAIL_CUSTOM or UF_SUCCESS end function saitama_limiter:GetCustomCastError() local parent = self:GetCaster() return parent:GetModifierStackCount("modifier_saitama_limiter", parent) == 0 and "#dota_hud_error_no_charges" or "" end if IsServer() then function saitama_limiter:OnSpellStart() local caster = self:GetCaster() StartAnimation(caster, { duration = 1.2, -- 36 / 30 activity = ACT_DOTA_CAST_ABILITY_6 }) caster:EmitSound("Arena.Hero_Saitama.Limiter") caster:ModifyStrength(caster:GetStrength() * self:GetSpecialValueFor("bonus_strength_pct") * caster:GetModifierStackCount("modifier_saitama_limiter", caster) * 0.01) end end modifier_saitama_limiter_autocast = class({ IsHidden = function() return true end, }) if IsServer() then function modifier_saitama_limiter_autocast:OnCreated() self:StartIntervalThink(0.1) local parent = self:GetParent() if not parent:HasModifier("modifier_saitama_limiter") then parent:AddNewModifier(parent, self:GetAbility(), "modifier_saitama_limiter", nil) end end function modifier_saitama_limiter_autocast:OnIntervalThink() local ability = self:GetAbility() local parent = self:GetParent() if parent:IsAlive() then if ability:GetAutoCastState() and parent:GetMana() >= ability:GetManaCost() and not parent:IsChanneling() and not parent:IsInvisible() and parent:GetModifierStackCount("modifier_saitama_limiter", parent) > 0 then parent:CastAbilityNoTarget(ability, parent:GetPlayerID()) end end end end
LinkLuaModifier("modifier_saitama_limiter_autocast", "heroes/hero_saitama/limiter.lua", LUA_MODIFIER_MOTION_NONE) saitama_limiter = class({ GetIntrinsicModifierName = function() return "modifier_saitama_limiter_autocast" end, }) function saitama_limiter:GetManaCost() return self:GetCaster():GetMaxMana() * self:GetSpecialValueFor("manacost_pct") * 0.01 + self:GetSpecialValueFor("manacost") end function saitama_limiter:CastFilterResult() local parent = self:GetCaster() return parent:GetModifierStackCount("modifier_saitama_limiter", parent) == 0 and UF_FAIL_CUSTOM or UF_SUCCESS end function saitama_limiter:GetCustomCastError() local parent = self:GetCaster() return parent:GetModifierStackCount("modifier_saitama_limiter", parent) == 0 and "#dota_hud_error_no_charges" or "" end if IsServer() then function saitama_limiter:OnSpellStart() local caster = self:GetCaster() StartAnimation(caster, { duration = 1.2, -- 36 / 30 activity = ACT_DOTA_CAST_ABILITY_6 }) caster:EmitSound("Arena.Hero_Saitama.Limiter") caster:ModifyStrength(caster:GetStrength() * self:GetSpecialValueFor("bonus_strength_pct") * caster:GetModifierStackCount("modifier_saitama_limiter", caster) * 0.01) end end modifier_saitama_limiter_autocast = class({ IsHidden = function() return true end, }) if IsServer() then function modifier_saitama_limiter_autocast:OnCreated() self:StartIntervalThink(0.1) local parent = self:GetParent() if not parent:HasModifier("modifier_saitama_limiter") then parent:AddNewModifier(parent, self:GetAbility(), "modifier_saitama_limiter", nil) end end function modifier_saitama_limiter_autocast:OnIntervalThink() local ability = self:GetAbility() local parent = self:GetParent() if parent:IsAlive() then if ability:GetAutoCastState() and parent:GetMana() >= ability:GetManaCost() and not parent:IsChanneling() and not parent:IsInvisible() and not (parent:GetCurrentActiveAbility() and parent:GetCurrentActiveAbility():IsInAbilityPhase()) and parent:GetModifierStackCount("modifier_saitama_limiter", parent) > 0 then parent:CastAbilityNoTarget(ability, parent:GetPlayerID()) end end end end
fix(abilities): Saitama - Limiter autocast cancels abilities in cast phase (#169)
fix(abilities): Saitama - Limiter autocast cancels abilities in cast phase (#169)
Lua
mit
ark120202/aabs
ad0993e72f71f4241427f9a85335e1a9a2e0b4f5
modules/vim/installed-config/plugin/cmp.lua
modules/vim/installed-config/plugin/cmp.lua
local cmp = require'cmp' cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) vim.fn["vsnip#anonymous"](args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = false }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ['<C-n>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Down>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), ['<C-p>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Up>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'vsnip' }, -- For vsnip users. }, { { name = 'buffer' }, }), window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() } })
local cmp = require'cmp' local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) vim.fn["vsnip#anonymous"](args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = false }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ['<C-n>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Down>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), ['<C-p>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Up>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'vsnip' }, -- For vsnip users. }, { { name = 'buffer' }, }), window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() } })
Fix crash in cmp.lua
Fix crash in cmp.lua
Lua
mit
justinhoward/dotfiles,justinhoward/dotfiles
283e4c33f4b54f0553b8b5374df616c866738475
files/default/balancer.lua
files/default/balancer.lua
-- Note: This really shouldn't be delivered via a chef cookbook -- this is a basic example meant for learning purposes local _M = {} local json = require "cjson" local http = require "resty.http" local upstreams = {} local state = {} local refresh_interval = 30 -- private local function refresh(premature) if premature then return end local hc = http:new() local res, err = hc:request_uri "http://127.0.0.1:8500/v1/catalog/services", { method = "GET" } if res == nil then ngx.log(ngx.ERR, "consul: FAILED to refresh upstreams") elseif res.body then local services = json.decode(res.body) -- catch json errors local suc, services = pcall(function() return json.decode(res.body) end) if suc then for service, tags in pairs(services) do local sub, err = hc:request_uri("http://127.0.0.1:8500/v1/catalog/service/" .. service .. "?tag=service", { method = "GET" }) if sub.body then _M.set(service, json.decode(sub.body)) end end ngx.log(ngx.ERR, "consul: refreshed upstreams") else ngx.log(ngx.ERR, "consul: Failed to decode Consul response") end end local ok, err = ngx.timer.at(refresh_interval, refresh) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) end end -- public -- start consul refresh function _M.start(interval) refresh_interval = interval local ok, err = ngx.timer.at(0, refresh) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) end end -- set upstreams function _M.set(name, nodes) upstreams[name] = nodes end -- get service nodes function _M.service(name) local nodes = {} for index, node in ipairs(upstreams[name]) do nodes[index] = { address = node["Address"], port = node["ServicePort"] } end return nodes end -- get next node saving state per service function _M.next(service) if upstreams[service] == nil then return nil end if state[service] == nil or state[service] > #upstreams[service] then state[service] = 1 end local node = upstreams[service][state[service]] state[service] = state[service] + 1 return { address = node["Address"], port = node["ServicePort"] } end return _M
-- Note: This really shouldn't be delivered via a chef cookbook -- this is a basic example meant for learning purposes local _M = {} local json = require "cjson" local http = require "resty.http" local upstreams = {} local state = {} local refresh_interval = 30 -- private local function refresh(premature) if premature then return end local hc = http:new() local res, err = hc:request_uri "http://127.0.0.1:8500/v1/catalog/services", { method = "GET" } if res == nil then ngx.log(ngx.ERR, "consul: FAILED to refresh upstreams") elseif res.body then -- catch json errors local suc, services = pcall(function() return json.decode(res.body) end) if suc then for service, tags in pairs(services) do local sub, err = hc:request_uri("http://127.0.0.1:8500/v1/catalog/service/" .. service .. "?tag=service", { method = "GET" }) if sub.body then _M.set(service, json.decode(sub.body)) end end ngx.log(ngx.ERR, "consul: refreshed upstreams") else ngx.log(ngx.ERR, "consul: Failed to decode Consul response") end end local ok, err = ngx.timer.at(refresh_interval, refresh) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) end end -- public -- start consul refresh function _M.start(interval) refresh_interval = interval local ok, err = ngx.timer.at(0, refresh) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) end end -- set upstreams function _M.set(name, nodes) upstreams[name] = nodes end -- get service nodes function _M.service(name) local nodes = {} for index, node in ipairs(upstreams[name]) do nodes[index] = { address = node["Address"], port = node["ServicePort"] } end return nodes end -- get next node saving state per service function _M.next(service) if upstreams[service] == nil then return nil end if state[service] == nil or state[service] > #upstreams[service] then state[service] = 1 end local node = upstreams[service][state[service]] state[service] = state[service] + 1 return { address = node["Address"], port = node["ServicePort"] } end return _M
actually fix the issue
actually fix the issue
Lua
apache-2.0
sigil66/nginx-consul-cookbook,sigil66/nginx-consul-cookbook
f3663c636bc34653606ff2469b86b9254725962d
src/CppParser/premake5.lua
src/CppParser/premake5.lua
clang_msvc_flags = { "/wd4146", "/wd4244", "/wd4800", "/wd4345", "/wd4355", "/wd4996", "/wd4624", "/wd4291", "/wd4251", "/wd4141", -- 'inline' : used more than once } if not (string.starts(action, "vs") and not os.is("windows")) then project "CppSharp.CppParser" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" configuration "vs*" buildoptions { clang_msvc_flags } if os.getenv("APPVEYOR") then linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info end configuration "*" files { "*.h", "*.cpp", "*.lua" } SearchLLVM() SetupLLVMIncludes() SetupLLVMLibs() CopyClangIncludes() configuration "*" end
clang_msvc_flags = { "/wd4146", "/wd4244", "/wd4800", "/wd4345", "/wd4355", "/wd4996", "/wd4624", "/wd4291", "/wd4251", "/wd4141", -- 'inline' : used more than once } if not (string.starts(action, "vs") and not os.is("windows")) then project "CppSharp.CppParser" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" configuration "vs*" buildoptions { clang_msvc_flags } if os.getenv("APPVEYOR") then linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info end configuration "linux" defines { "_GLIBCXX_USE_CXX11_ABI=0" } configuration "*" files { "*.h", "*.cpp", "*.lua" } SearchLLVM() SetupLLVMIncludes() SetupLLVMLibs() CopyClangIncludes() configuration "*" end
Force the pre-C++11 ABI when compiling the parser library on Linux platforms.
Force the pre-C++11 ABI when compiling the parser library on Linux platforms. Hopefully fixes a long-standing compatibility issue caused by the C++11 ABI switch on GCC5. Fixes https://github.com/mono/CppSharp/issues/655.
Lua
mit
zillemarco/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mono/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,mono/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,u255436/CppSharp,u255436/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,u255436/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,ktopouzi/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp
01d04250c291b183b658b37b7557f662c9f61225
frontend/settings.lua
frontend/settings.lua
DocSettings = {} function DocSettings:getHistoryPath(fullpath) local i = #fullpath - 1 -- search for last slash while i > 0 do if fullpath:sub(i,i) == "/" then break end i = i - 1 end -- construct path to configuration file in history dir local filename = fullpath:sub(i+1, -1) local basename = fullpath:sub(1, i) return "./history/["..basename:gsub("/","#").."] "..filename..".lua" end function DocSettings:getPathFromHistory(hist_name) -- 1. select everything included in brackets local s = string.match(hist_name,"%b[]") -- 2. crop the bracket-sign from both sides -- 3. and finally replace decorative signs '#' to dir-char '/' return string.gsub(string.sub(s,2,-3),"#","/") end function DocSettings:getNameFromHistory(hist_name) -- at first, search for path length local s = string.len(string.match(hist_name,"%b[]")) -- and return the rest of string without 4 last characters (".lua") return string.sub(hist_name, s+2, -5) end function DocSettings:open(docfile) local conf_path = nil if docfile == ".reader" then -- we handle reader setting as special case conf_path = "settings.reader.lua" else conf_path = self:getHistoryPath(docfile) end -- construct settings obj local new = { file = conf_path, data = {} } local ok, stored = pcall(dofile, new.file) if not ok then -- try legacy conf path, for backward compatibility. this also -- takes care of reader legacy setting ok, stored = pcall(dofile, docfile..".kpdfview.lua") end if ok then new.data = stored end return setmetatable(new, { __index = DocSettings}) end function DocSettings:readSetting(key) return self.data[key] end function DocSettings:saveSetting(key, value) self.data[key] = value end function DocSettings:delSetting(key) self.data[key] = nil end function dump(data, max_lv) local out = {} DocSettings:_serialize(data, out, 0, max_lv) return table.concat(out) end -- simple serialization function, won't do uservalues, functions, loops function DocSettings:_serialize(what, outt, indent, max_lv) if not max_lv then max_lv = math.huge end if indent > max_lv then return end if type(what) == "table" then local didrun = false table.insert(outt, "{") for k, v in pairs(what) do if didrun then table.insert(outt, ",") end table.insert(outt, "\n") table.insert(outt, string.rep("\t", indent+1)) table.insert(outt, "[") self:_serialize(k, outt, indent+1, max_lv) table.insert(outt, "] = ") self:_serialize(v, outt, indent+1, max_lv) didrun = true end if didrun then table.insert(outt, "\n") table.insert(outt, string.rep("\t", indent)) end table.insert(outt, "}") elseif type(what) == "string" then table.insert(outt, string.format("%q", what)) elseif type(what) == "number" or type(what) == "boolean" then table.insert(outt, tostring(what)) end end function DocSettings:flush() -- write a serialized version of the data table if not self.file then return end local f_out = io.open(self.file, "w") if f_out ~= nil then os.setlocale('C', 'numeric') local out = {"-- we can read Lua syntax here!\nreturn "} self:_serialize(self.data, out, 0) table.insert(out, "\n") f_out:write(table.concat(out)) f_out:close() end end function DocSettings:close() self:flush() end
DocSettings = {} function DocSettings:getHistoryPath(fullpath) local i = #fullpath - 1 -- search for last slash while i > 0 do if fullpath:sub(i,i) == "/" then break end i = i - 1 end -- construct path to configuration file in history dir local filename = fullpath:sub(i+1, -1) local basename = fullpath:sub(1, i) return "./history/["..basename:gsub("/","#").."] "..filename..".lua" end function DocSettings:getPathFromHistory(hist_name) -- 1. select everything included in brackets local s = string.match(hist_name,"%b[]") -- 2. crop the bracket-sign from both sides -- 3. and finally replace decorative signs '#' to dir-char '/' return string.gsub(string.sub(s,2,-3),"#","/") end function DocSettings:getNameFromHistory(hist_name) -- at first, search for path length local s = string.len(string.match(hist_name,"%b[]")) -- and return the rest of string without 4 last characters (".lua") return string.sub(hist_name, s+2, -5) end function DocSettings:open(docfile) local conf_path = nil if docfile == ".reader" then -- we handle reader setting as special case conf_path = "settings.reader.lua" else if lfs.attributes("./history","mode") ~= "directory" then lfs.mkdir("history") end conf_path = self:getHistoryPath(docfile) end -- construct settings obj local new = { file = conf_path, data = {} } local ok, stored = pcall(dofile, new.file) if not ok then -- try legacy conf path, for backward compatibility. this also -- takes care of reader legacy setting ok, stored = pcall(dofile, docfile..".kpdfview.lua") end if ok then new.data = stored end return setmetatable(new, { __index = DocSettings}) end function DocSettings:readSetting(key) return self.data[key] end function DocSettings:saveSetting(key, value) self.data[key] = value end function DocSettings:delSetting(key) self.data[key] = nil end function dump(data, max_lv) local out = {} DocSettings:_serialize(data, out, 0, max_lv) return table.concat(out) end -- simple serialization function, won't do uservalues, functions, loops function DocSettings:_serialize(what, outt, indent, max_lv) if not max_lv then max_lv = math.huge end if indent > max_lv then return end if type(what) == "table" then local didrun = false table.insert(outt, "{") for k, v in pairs(what) do if didrun then table.insert(outt, ",") end table.insert(outt, "\n") table.insert(outt, string.rep("\t", indent+1)) table.insert(outt, "[") self:_serialize(k, outt, indent+1, max_lv) table.insert(outt, "] = ") self:_serialize(v, outt, indent+1, max_lv) didrun = true end if didrun then table.insert(outt, "\n") table.insert(outt, string.rep("\t", indent)) end table.insert(outt, "}") elseif type(what) == "string" then table.insert(outt, string.format("%q", what)) elseif type(what) == "number" or type(what) == "boolean" then table.insert(outt, tostring(what)) end end function DocSettings:flush() -- write a serialized version of the data table if not self.file then return end local f_out = io.open(self.file, "w") if f_out ~= nil then os.setlocale('C', 'numeric') local out = {"-- we can read Lua syntax here!\nreturn "} self:_serialize(self.data, out, 0) table.insert(out, "\n") f_out:write(table.concat(out)) f_out:close() end end function DocSettings:close() self:flush() end
Fix bug #119.
Fix bug #119.
Lua
agpl-3.0
NiLuJe/koreader,koreader/koreader,poire-z/koreader,apletnev/koreader,ashhher3/koreader,NickSavage/koreader,NiLuJe/koreader,poire-z/koreader,mwoz123/koreader,koreader/koreader,mihailim/koreader,chihyang/koreader,ashang/koreader,pazos/koreader,Hzj-jie/koreader,Frenzie/koreader,chrox/koreader,robert00s/koreader,noname007/koreader,lgeek/koreader,frankyifei/koreader,houqp/koreader,Frenzie/koreader,Markismus/koreader
91a6e8828f75dc9de22d195f56b9cd80122c88d1
hymn/inputhandler.lua
hymn/inputhandler.lua
local Class = require "shared.middleclass" local GameMath = require "shared.gamemath" local InputHandler = Class "InputHandler" local EntityStatics = require "hymn.staticdata.entitystatics" function InputHandler:initialize(logicCore) self.logicCore = logicCore self.translate = GameMath.Vector2:new(0, 0) end local borderWidth = 20 local scrollSpeed = 500 function InputHandler:update(dt) local width, height = love.graphics.getDimensions() local x, y = love.mouse.getPosition() -- border scrolling if x < borderWidth then self.translate.x = self.translate.x + scrollSpeed * dt elseif x > width - borderWidth then self.translate.x = self.translate.x - scrollSpeed * dt end if y < borderWidth then self.translate.y = self.translate.y + scrollSpeed * dt elseif y > height - borderWidth then self.translate.y = self.translate.y - scrollSpeed * dt end -- dragging if self.dragAnchor then -- dbgprint self.translate.x = x - self.dragAnchor.x self.translate.y = y - self.dragAnchor.y end local w, h = self.logicCore.map:size() self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0) self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0) end -- click-through prevention. sucky, sucky Quickie! ;) function InputHandler:isToolBar(x, y) local width, height = love.graphics.getDimensions() return y > height - 50 end function InputHandler:mousePressed(x, y, button) if self:isToolBar(x, y) then return end local position = GameMath.Vector2:new(x, y) - self.translate self.dragAnchor = position end function InputHandler:mouseReleased(x, y, button) if self:isToolBar(x, y) then return end local function isSelectable(entity) return entity.player == self.logicCore.players[1] and entity.selectable end local position = GameMath.Vector2:new(x, y) - self.translate local entityManager = self.logicCore.entityManager local logicCore = self.logicCore if button == "l" then if self.mode == "build" then local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1]) building:setPosition(position.x, position.y) self:selectEntity(building.id) self.mode = false elseif self.mode == "path" then local entity = entityManager:entity(self.selection) entity:addPathPoint(position) else local entity, distance = entityManager:findClosestEntity(position, isSelectable) self:selectEntity(entity and distance < 40 and entity.id) end elseif button == "r" then self:selectEntity(false) self.mode = false end end function InputHandler:setMode(mode) local entityManager = self.logicCore.entityManager if mode == "build" then self.mode = "build" elseif mode == "path" then local entity = entityManager:entity(self.selection) entity:clearPath() self.mode = "path" end end function InputHandler:keyPressed(key, unicode) end function InputHandler:selectEntity(entityId) self.selection = entityId end return InputHandler
local Class = require "shared.middleclass" local GameMath = require "shared.gamemath" local InputHandler = Class "InputHandler" local EntityStatics = require "hymn.staticdata.entitystatics" function InputHandler:initialize(logicCore) self.logicCore = logicCore self.translate = GameMath.Vector2:new(0, 0) end local borderWidth = 20 local scrollSpeed = 500 function InputHandler:update(dt) local width, height = love.graphics.getDimensions() local x, y = love.mouse.getPosition() -- border scrolling if x < borderWidth then self.translate.x = self.translate.x + scrollSpeed * dt elseif x > width - borderWidth then self.translate.x = self.translate.x - scrollSpeed * dt end if y < borderWidth then self.translate.y = self.translate.y + scrollSpeed * dt elseif y > height - borderWidth then self.translate.y = self.translate.y - scrollSpeed * dt end -- dragging if self.dragAnchor then -- dbgprint self.translate.x = x - self.dragAnchor.x self.translate.y = y - self.dragAnchor.y end local w, h = self.logicCore.map:size() self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0) self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0) end -- click-through prevention. sucky, sucky Quickie! ;) function InputHandler:isToolBar(x, y) local width, height = love.graphics.getDimensions() return y > height - 50 end function InputHandler:mousePressed(x, y, button) if self:isToolBar(x, y) then return end local position = GameMath.Vector2:new(x, y) - self.translate self.dragAnchor = position end function InputHandler:mouseReleased(x, y, button) self.dragAnchor = false if self:isToolBar(x, y) then return end local function isSelectable(entity) return entity.player == self.logicCore.players[1] and entity.selectable end local position = GameMath.Vector2:new(x, y) - self.translate local entityManager = self.logicCore.entityManager local logicCore = self.logicCore if button == "l" then if self.mode == "build" then local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1]) building:setPosition(position.x, position.y) self:selectEntity(building.id) self.mode = false elseif self.mode == "path" then local entity = entityManager:entity(self.selection) entity:addPathPoint(position) else local entity, distance = entityManager:findClosestEntity(position, isSelectable) self:selectEntity(entity and distance < 40 and entity.id) end elseif button == "r" then self:selectEntity(false) self.mode = false end end function InputHandler:setMode(mode) local entityManager = self.logicCore.entityManager if mode == "build" then self.mode = "build" elseif mode == "path" then local entity = entityManager:entity(self.selection) entity:clearPath() self.mode = "path" end end function InputHandler:keyPressed(key, unicode) end function InputHandler:selectEntity(entityId) self.selection = entityId end return InputHandler
Fix: mouse dragging
Fix: mouse dragging
Lua
mit
ExcelF/project-navel
75b2552c23daf90982414c658d0eace5a9d5081a
quest/valandil_elensar_69_wilderness.lua
quest/valandil_elensar_69_wilderness.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (69, 'quest.valandil_elensar_69_wilderness'); local common = require("base.common") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Elsbaumwald" Title[ENGLISH] = "Elstree Forest" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Sammel zehn Scheite Naldorholz und bringe diese Valandil Elensar. Um Holz zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einem Naldorbaum stehst." Description[ENGLISH][1] = "Collect ten logs of naldor wood and take them back to Valandil Elensar. To collect the wood use the hatchet in your hand, whilst standing in front of a naldor tree." Description[GERMAN][2] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][2] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][3] = "Sammel zwanzig Scheite Kirschholz und bringe diese Valandil Elensar. Um Holz zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einem Kirschbaum stehst." Description[ENGLISH][3] = "Collect twenty logs of cherry wood and take them back to Valandil Elensar. To collect the wood use the hatchet in your hand, whilst standing in front of a cherry tree." Description[GERMAN][4] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][4] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][5] = "Sammel fnf Zweige und bringe diese Valandil Elensar. Um Zweige zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einem Kirschbaum stehst." Description[ENGLISH][5] = "Collect five branches and take them back to Valandil Elensar. To collect branches use the hatchet in your hand, whilst standing in front of a cherry tree." Description[GERMAN][6] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][6] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][7] = "Besorge zehn Bndel Getreide und bringe sie Valandil Elensar. Du kannst Getreide auf einem Feld anbauen und mit einer Sense ernten oder die Getreidebndel bei einem Hndler kaufen." Description[ENGLISH][7] = "Obtain ten bundles of grain and take them to Valandil Elensar. You can grow grain on a field and harvest it with a scythe or buy the bundles of grain from a merchant." Description[GERMAN][8] = "Du hast alle Aufgaben von Valandil Elensar erfllt." Description[ENGLISH][8] = "You have fulfilled all the tasks for Valandil Elensar." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {840, 470, 0} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} QuestTarget[1] = {position(840, 470, 0), position(826, 464, 0)} -- Naldorbaum QuestTarget[2] = {position(840, 470, 0)} QuestTarget[3] = {position(840, 470, 0), position(855, 463, 0)} -- Kirschbaum QuestTarget[4] = {position(840, 470, 0)} QuestTarget[5] = {position(840, 470, 0), position(855, 463, 0)} -- Kirschbaum QuestTarget[6] = {position(840, 470, 0)} QuestTarget[7] = {position(840, 470, 0), position(791, 798, 0), position(847, 828, 0), position(959, 842, 0), position(430, 261, 0), position(361, 266,0)} QuestTarget[8] = {position(840, 470, 0)} -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 8 function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (69, 'quest.valandil_elensar_69_wilderness'); local common = require("base.common") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Elsbaumwald" Title[ENGLISH] = "Elstree Forest" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Sammel zehn Scheite Naldorholz und bringe diese Valandil Elensar. Um Holz zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einem Naldorbaum stehst." Description[ENGLISH][1] = "Collect ten logs of naldor wood and take them back to Valandil Elensar. To collect the wood use the hatchet in your hand, whilst standing in front of a naldor tree." Description[GERMAN][2] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][2] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][3] = "Sammel zwanzig Scheite Kirschholz und bringe diese Valandil Elensar. Um Holz zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einem Kirschbaum stehst." Description[ENGLISH][3] = "Collect twenty logs of cherry wood and take them back to Valandil Elensar. To collect the wood use the hatchet in your hand, whilst standing in front of a cherry tree." Description[GERMAN][4] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][4] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][5] = "Sammel fnf Zweige und bringe diese Valandil Elensar. Um Zweige zu sammeln, nimmst du das Beil in die Hand und benutzt es, whrend du vor einer Tanne oder ScandrelKiefer stehst." Description[ENGLISH][5] = "Collect five branches and take them back to Valandil Elensar. To collect branches use the hatchet in your hand, whilst standing in front of a fir tree or scandrel pine." Description[GERMAN][6] = "Geh zu Valandil Elensar im Elsbaumwald. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][6] = "Go back to Valandil Elensar in the Elstree Forest, he will certainly have another task for you." Description[GERMAN][7] = "Besorge zehn Bndel Getreide und bringe sie Valandil Elensar. Du kannst Getreide auf einem Feld anbauen und mit einer Sense ernten oder die Getreidebndel bei einem Hndler kaufen." Description[ENGLISH][7] = "Obtain ten bundles of grain and take them to Valandil Elensar. You can grow grain on a field and harvest it with a scythe or buy the bundles of grain from a merchant." Description[GERMAN][8] = "Du hast alle Aufgaben von Valandil Elensar erfllt." Description[ENGLISH][8] = "You have fulfilled all the tasks for Valandil Elensar." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {840, 470, 0} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} QuestTarget[1] = {position(840, 470, 0), position(826, 464, 0)} -- Naldorbaum QuestTarget[2] = {position(840, 470, 0)} QuestTarget[3] = {position(840, 470, 0), position(855, 463, 0)} -- Kirschbaum QuestTarget[4] = {position(840, 470, 0)} QuestTarget[5] = {position(840, 470, 0), position(855, 463, 0)} -- Kirschbaum QuestTarget[6] = {position(840, 470, 0)} QuestTarget[7] = {position(840, 470, 0), position(791, 798, 0), position(847, 828, 0), position(959, 842, 0), position(430, 261, 0), position(361, 266,0)} QuestTarget[8] = {position(840, 470, 0)} -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 8 function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end return M
#102 Fix Elstree Forest III
#102 Fix Elstree Forest III
Lua
agpl-3.0
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
f5de20271a00714f8ab700767ec622dffdbcb4ae
src/pf/lang.lua
src/pf/lang.lua
module("pf.lang",package.seeall) local function skip_whitespace(str, pos) while pos <= #str and str:match('^%s', pos) do pos = pos + 1 end return pos end local punctuation = { '(', ')', '[', ']', '!', '!=', '<', '<=', '>', '>=', '=', '+', '-', '*', '/', '%', '&', '|', '^', '&&', '||' } for k, v in ipairs(punctuation) do table.remove(punctuation, k) punctuation[v] = true end local function lex_host_or_keyword(str, pos) local name, next_pos = str:match("^([%w_.-]+)()", pos) assert(name, "failed to parse hostname or keyword at "..pos) return name, next_pos end local function lex_ipv4_or_host(str, pos) local function lex_byte(str) local byte = tonumber(str, 10) if byte >= 256 then return nil end return byte end local digits, dot = str:match("^(%d%d?%d?)()%.", pos) if not digits then return lex_host_or_keyword(str, start_pos) end local addr = { type='ipv4' } local byte = lex_byte(digits) if not byte then return lex_host_or_keyword(str, pos) end addr:insert(byte) pos = dot for i=1,3 do local digits, dot = str:match("^%.(%d%d?%d?)()", pos) if not digits then break end addr:insert(assert(lex_byte(digits), "failed to parse ipv4 addr")) pos = dot end local terminators = " \t\r\n)/" assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true), "unexpected terminator for ipv4 address") return addr, pos end local function lex_ipv6(str, pos) local addr = { type='ipv6' } -- FIXME: Currently only supporting fully-specified IPV6 names. local digits, dot = str:match("^(%x%x?)()%:", pos) assert(digits, "failed to parse ipv6 address at "..pos) addr:insert(tonumber(digits, 16)) pos = dot for i=1,15 do local digits, dot = str:match("^%:(%x%x?)()", pos) assert(digits, "failed to parse ipv6 address at "..pos) addr:insert(tonumber(digits, 16)) pos = dot end local terminators = " \t\r\n)/" assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true), "unexpected terminator for ipv6 address") return addr, pos end local function lex_addr(str, pos) local start_pos = pos if str:match("^%d%d?%d?%.", pos) then return lex_ipv4_or_host(str, pos) elseif str:match("^%x?%x?%:", pos) then return lex_ipv6(str, pos) else return lex_host_or_keyword(str, pos) end end local number_terminators = " \t\r\n)]!<>=+-*/%&|^" local function lex_number(str, pos, base) local res = 0 local i = pos while i <= #str do local chr = str:sub(i,i) local n = tonumber(chr, base) if n then res = res * base + n i = i + 1 elseif number_terminators:find(chr, 1, true) then return res, i else return nil, i end end return res, i -- EOS end local function lex_hex(str, pos) local ret, next_pos = lex_number(str, pos, 16) assert(ret, "unexpected end of hex literal at "..pos) return ret, next_pos end local function lex_octal_or_addr(str, pos) local ret, next_pos = lex_number(str, pos, 8) if not ret then return lex_addr(str, pos) end return ret, next_pos end local function lex_decimal_or_addr(str, pos) local ret, next_pos = lex_number(str, pos, 10) if not ret then return lex_addr(str, pos) end return ret, next_pos end local function lex(str, pos, len_is_keyword) -- EOF. if pos > #str then return nil, pos end -- Non-alphanumeric tokens. local two = str:sub(pos,pos+1) if punctuation[two] then return two, pos+2 end local one = str:sub(pos,pos) if punctuation[one] then return one, pos+1 end -- Numeric literals or net addresses. if one:match('^%d') then if two == ('0x') then return lex_hex(str, pos+2) end if two:match('^0%d') then return lex_octal_or_addr(str, pos) end return lex_decimal_or_addr(str, pos) end -- IPV6 net address beginning with [a-fA-F]. if str:match('^%x?%x?%:', pos) then return lex_ipv6(str, pos) end -- Unhappily, a special case for "len", which is the only bare name -- that can appear in an arithmetic expression. "len-1" lexes as { -- 'len', '-', 1 } in arithmetic contexts, but "len-1" otherwise. -- Clownshoes grammar! if str:match("^len", pos) and len_is_keyword then local ch = str:sub(pos+3, pos+3) if ch == '' or number_terminators:find(ch, 1, true) then return 'len', pos+3 end end -- Keywords or hostnames. return lex_host_or_keyword(str, pos) end function tokens(str) local pos, next_pos = 1, nil local peeked = nil local function peek(len_is_keyword) if not next_pos then pos = skip_whitespace(str, pos) peeked, next_pos = lex(str, pos, len_is_keyword) assert(next_pos, "next pos is nil") end return peeked end local function next(len_is_keyword) local tok = assert(peek(len_is_keyword), "unexpected end of filter string") pos, next_pos = next_pos, nil return tok end return { peek = peek, next = next } end function compile(str) local ast = parse(str) end function selftest () print("selftest: pf.lang") local function lex_test(str, elts, len_is_keyword) local lexer = tokens(str) for i, val in pairs(elts) do local tok = lexer.next(len_is_keyword) assert(tok == val, "expected "..val.." but got "..tok) end assert(not lexer.peek(len_is_keyword), "more tokens, yo") end lex_test("ip", {"ip"}, true) lex_test("len", {"len"}, true) lex_test("len", {"len"}, false) lex_test("len-1", {"len-1"}, false) lex_test("len-1", {"len", "-", 1}, true) print("OK") end
module("pf.lang",package.seeall) local function skip_whitespace(str, pos) while pos <= #str and str:match('^%s', pos) do pos = pos + 1 end return pos end local punctuation = { '(', ')', '[', ']', '!', '!=', '<', '<=', '>', '>=', '=', '+', '-', '*', '/', '%', '&', '|', '^', '&&', '||', '<<', '>>' } for k, v in ipairs(punctuation) do punctuation[v] = true end local function lex_host_or_keyword(str, pos) local name, next_pos = str:match("^([%w.-]+)()", pos) assert(name, "failed to parse hostname or keyword at "..pos) assert(name:match("^%w", 1, 1), "bad hostname or keyword "..name) assert(name:match("^%w", #name, #name), "bad hostname or keyword "..name) return tonumber(name, 10) or name, next_pos end local function lex_ipv4_or_host(str, pos) local function lex_byte(str) local byte = tonumber(str, 10) if byte >= 256 then return nil end return byte end local digits, dot = str:match("^(%d%d?%d?)()%.", pos) if not digits then return lex_host_or_keyword(str, start_pos) end local addr = { type='ipv4' } local byte = lex_byte(digits) if not byte then return lex_host_or_keyword(str, pos) end table.insert(addr, byte) pos = dot for i=1,3 do local digits, dot = str:match("^%.(%d%d?%d?)()", pos) if not digits then break end table.insert(addr, assert(lex_byte(digits), "failed to parse ipv4 addr")) pos = dot end local terminators = " \t\r\n)/" assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true), "unexpected terminator for ipv4 address") return addr, pos end local function lex_ipv6(str, pos) local addr = { type='ipv6' } -- FIXME: Currently only supporting fully-specified IPV6 names. local digits, dot = str:match("^(%x%x?)()%:", pos) assert(digits, "failed to parse ipv6 address at "..pos) table.insert(addr, tonumber(digits, 16)) pos = dot for i=1,15 do local digits, dot = str:match("^%:(%x%x?)()", pos) assert(digits, "failed to parse ipv6 address at "..pos) table.insert(addr, tonumber(digits, 16)) pos = dot end local terminators = " \t\r\n)/" assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true), "unexpected terminator for ipv6 address") return addr, pos end local function lex_addr(str, pos) local start_pos = pos if str:match("^%d%d?%d?%.", pos) then return lex_ipv4_or_host(str, pos) elseif str:match("^%x?%x?%:", pos) then return lex_ipv6(str, pos) else return lex_host_or_keyword(str, pos) end end local number_terminators = " \t\r\n)]!<>=+-*/%&|^" local function lex_number(str, pos, base) local res = 0 local i = pos while i <= #str do local chr = str:sub(i,i) local n = tonumber(chr, base) if n then res = res * base + n i = i + 1 elseif str:match("^[%a_.]", i) then return nil, i else return res, i end end return res, i -- EOS end local function lex_hex(str, pos) local ret, next_pos = lex_number(str, pos, 16) assert(ret, "unexpected end of hex literal at "..pos) return ret, next_pos end local function lex_octal_or_addr(str, pos, in_brackets) local ret, next_pos = lex_number(str, pos, 8) if not ret then if in_brackets then return lex_host_or_keyword(str, pos) end return lex_addr(str, pos) end return ret, next_pos end local function lex_decimal_or_addr(str, pos, in_brackets) local ret, next_pos = lex_number(str, pos, 10) if not ret then if in_brackets then return lex_host_or_keyword(str, pos) end return lex_addr(str, pos) end return ret, next_pos end local function lex(str, pos, opts, in_brackets) -- EOF. if pos > #str then return nil, pos end -- Non-alphanumeric tokens. local two = str:sub(pos,pos+1) if punctuation[two] then return two, pos+2 end local one = str:sub(pos,pos) if punctuation[one] then return one, pos+1 end if in_brackets and one == ':' then return one, pos+1 end -- Numeric literals or net addresses. if opts.maybe_arithmetic and one:match('^%d') then if two == ('0x') then return lex_hex(str, pos+2) elseif two:match('^0%d') then return lex_octal_or_addr(str, pos, in_brackets) else return lex_decimal_or_addr(str, pos, in_brackets) end end -- IPV6 net address beginning with [a-fA-F]. if not in_brackets and str:match('^%x?%x?%:', pos) then return lex_ipv6(str, pos) end -- "len" is the only bare name that can appear in an arithmetic -- expression. "len-1" lexes as { 'len', '-', 1 } in arithmetic -- contexts, but { "len-1" } otherwise. if opts.maybe_arithmetic and str:match("^len", pos) then if pos + 3 > #str or not str:match("^[%w.]", pos+3) then return 'len', pos+3 end end -- Keywords or hostnames. return lex_host_or_keyword(str, pos) end function tokens(str) local pos, next_pos = 1, nil local peeked = nil local brackets = 0 local function peek(opts) if not next_pos then pos = skip_whitespace(str, pos) peeked, next_pos = lex(str, pos, opts or {}, brackets > 0) if peeked == '[' then brackets = brackets + 1 end if peeked == ']' then brackets = brackets - 1 end assert(next_pos, "next pos is nil") end return peeked end local function next(opts) local tok = assert(peek(opts), "unexpected end of filter string") pos, next_pos = next_pos, nil return tok end return { peek = peek, next = next } end function compile(str) local ast = parse(str) end function selftest () print("selftest: pf.lang") local function lex_test(str, elts, opts) local lexer = tokens(str) for i, val in pairs(elts) do local tok = lexer.next(opts) assert(tok == val, "expected "..val.." but got "..tok) end assert(not lexer.peek(opts), "more tokens, yo") end lex_test("ip", {"ip"}, {maybe_arithmetic=true}) lex_test("len", {"len"}, {maybe_arithmetic=true}) lex_test("len", {"len"}, {}) lex_test("len-1", {"len-1"}, {}) lex_test("len-1", {"len", "-", 1}, {maybe_arithmetic=true}) lex_test("tcp port 80", {"tcp", "port", 80}, {}) lex_test("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)", { 'tcp', 'port', 80, 'and', '(', '(', '(', 'ip', '[', 2, ':', 2, ']', '-', '(', '(', 'ip', '[', 0, ']', '&', 15, ')', '<<', 2, ')', ')', '-', '(', '(', 'tcp', '[', 12, ']', '&', 240, ')', '>>', 2, ')', ')', '!=', 0, ')' }, {maybe_arithmetic=true}) print("OK") end
Working lexer
Working lexer * src/pf/lang.lua: Add larger lexer tests, and fix bugs.
Lua
apache-2.0
mpeterv/pflua,SnabbCo/pflua
b18962929b6f54d342c84e0ea9be38c29b60a513
lualib/http/httpd.lua
lualib/http/httpd.lua
local table = table local httpd = {} local http_status_msg = { [100] = "Continue", [101] = "Switching Protocols", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-Authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Time-out", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Request Entity Too Large", [414] = "Request-URI Too Large", [415] = "Unsupported Media Type", [416] = "Requested range not satisfiable", [417] = "Expectation Failed", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Time-out", [505] = "HTTP Version not supported", } local function recvheader(readbytes, limit, lines, header) 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 if #header > limit then return end e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end local function 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 header[name] = header[name] .. ", " .. value else header[name] = value end end end return header end local function chunksize(readbytes, body) while true do if #body > 128 then return end body = body .. readbytes() 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 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 local function 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 body = readcrln(readbytes, body) if not body then return end local tmpline = {} body = recvheader(readbytes, 8192, tmpline, body) if not body then return end header = parseheader(tmpline,1,header) return result, header end local function readall(readbytes, bodylimit) local tmpline = {} local body = recvheader(readbytes, 8192, tmpline, "") if not body then return 413 -- Request Entity Too Large end local request = assert(tmpline[1]) local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$" assert(method and url and httpver) httpver = assert(tonumber(httpver)) if httpver < 1.0 or httpver > 1.1 then return 505 -- HTTP Version not supported end local header = parseheader(tmpline,2,{}) if not header then return 400 -- Bad request end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" or mode ~= "chunked" then return 501 -- Not Implemented end end if mode == "chunked" then body, header = recvchunkedbody(readbytes, bodylimit, header, body) if not body then return 413 end else -- identity mode if length then if length > bodylimit then return 413 end if #body >= length then body = body:sub(1,length) else local padding = readbytes(length - #body) body = body .. padding end end end return 200, url, method, header, body end function httpd.read_request(...) local ok, code, url, method, header, body = pcall(readall, ...) if ok then return code, url, method, header, body else return nil, code end end local function writeall(writefunc, statuscode, bodyfunc, header) local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "") writefunc(statusline) if header then for k,v in pairs(header) do writefunc(string.format("%s: %s\r\n", k,v)) end end local t = type(bodyfunc) if t == "string" then writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) writefunc(bodyfunc) elseif t == "function" then writefunc("transfer-encoding: chunked\r\n") while true do local s = bodyfunc() if s then if s ~= "" then writefunc(string.format("\r\n%x\r\n", #s)) writefunc(s) end else writefunc("\r\n0\r\n\r\n") end end else assert(t == "nil") writefunc("\r\n") end end function httpd.write_response(...) return pcall(writeall, ...) end return httpd
local table = table local httpd = {} local http_status_msg = { [100] = "Continue", [101] = "Switching Protocols", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-Authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Time-out", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Request Entity Too Large", [414] = "Request-URI Too Large", [415] = "Unsupported Media Type", [416] = "Requested range not satisfiable", [417] = "Expectation Failed", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Time-out", [505] = "HTTP Version not supported", } local function recvheader(readbytes, limit, 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 if #header > limit then return end 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 end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end local function 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 header[name] = header[name] .. ", " .. value else header[name] = value end end end return header end local function chunksize(readbytes, body) while true do if #body > 128 then return end body = body .. readbytes() 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 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 local function 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 = recvheader(readbytes, 8192, tmpline, body) if not body then return end header = parseheader(tmpline,1,header) return result, header end local function readall(readbytes, bodylimit) local tmpline = {} local body = recvheader(readbytes, 8192, tmpline, "") if not body then return 413 -- Request Entity Too Large end local request = assert(tmpline[1]) local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$" assert(method and url and httpver) httpver = assert(tonumber(httpver)) if httpver < 1.0 or httpver > 1.1 then return 505 -- HTTP Version not supported end local header = parseheader(tmpline,2,{}) if not header then return 400 -- Bad request 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 return 501 -- Not Implemented end end if mode == "chunked" then body, header = recvchunkedbody(readbytes, bodylimit, header, body) if not body then return 413 end else -- identity mode if length then if length > bodylimit then return 413 end if #body >= length then body = body:sub(1,length) else local padding = readbytes(length - #body) body = body .. padding end end end return 200, url, method, header, body end function httpd.read_request(...) local ok, code, url, method, header, body = pcall(readall, ...) if ok then return code, url, method, header, body else return nil, code end end local function writeall(writefunc, statuscode, bodyfunc, header) local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "") writefunc(statusline) if header then for k,v in pairs(header) do writefunc(string.format("%s: %s\r\n", k,v)) end end local t = type(bodyfunc) if t == "string" then writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) writefunc(bodyfunc) elseif t == "function" then writefunc("transfer-encoding: chunked\r\n") while true do local s = bodyfunc() if s then if s ~= "" then writefunc(string.format("\r\n%x\r\n", #s)) writefunc(s) end else writefunc("\r\n0\r\n\r\n") end end else assert(t == "nil") writefunc("\r\n") end end function httpd.write_response(...) return pcall(writeall, ...) end return httpd
bugfix: chunked mode
bugfix: chunked mode
Lua
mit
Zirpon/skynet,jiuaiwo1314/skynet,felixdae/skynet,kebo/skynet,ypengju/skynet_comment,kyle-wang/skynet,korialuo/skynet,lynx-seu/skynet,cpascal/skynet,zhoukk/skynet,lawnight/skynet,pigparadise/skynet,your-gatsby/skynet,longmian/skynet,Markal128/skynet,yinjun322/skynet,felixdae/skynet,nightcj/mmo,MetSystem/skynet,leezhongshan/skynet,liuxuezhan/skynet,chfg007/skynet,zzh442856860/skynet-Note,ypengju/skynet_comment,letmefly/skynet,jxlczjp77/skynet,samael65535/skynet,catinred2/skynet,ruleless/skynet,zzh442856860/skynet-Note,ruleless/skynet,cdd990/skynet,winglsh/skynet,LiangMa/skynet,catinred2/skynet,icetoggle/skynet,dymx101/skynet,xinmingyao/skynet,MoZhonghua/skynet,harryzeng/skynet,MRunFoss/skynet,LuffyPan/skynet,fhaoquan/skynet,chuenlungwang/skynet,bttscut/skynet,LuffyPan/skynet,fhaoquan/skynet,zhangshiqian1214/skynet,ludi1991/skynet,togolwb/skynet,zzh442856860/skynet,zhangshiqian1214/skynet,czlc/skynet,zzh442856860/skynet,enulex/skynet,wangyi0226/skynet,javachengwc/skynet,asanosoyokaze/skynet,puXiaoyi/skynet,czlc/skynet,lc412/skynet,letmefly/skynet,LuffyPan/skynet,wangjunwei01/skynet,ruleless/skynet,ag6ag/skynet,asanosoyokaze/skynet,sanikoyes/skynet,zhaijialong/skynet,cuit-zhaxin/skynet,microcai/skynet,sundream/skynet,u20024804/skynet,helling34/skynet,chuenlungwang/skynet,matinJ/skynet,wangyi0226/skynet,letmefly/skynet,wangjunwei01/skynet,pigparadise/skynet,ilylia/skynet,lynx-seu/skynet,icetoggle/skynet,iskygame/skynet,winglsh/skynet,matinJ/skynet,zzh442856860/skynet,xinjuncoding/skynet,lynx-seu/skynet,wangyi0226/skynet,bigrpg/skynet,KittyCookie/skynet,ilylia/skynet,kyle-wang/skynet,samael65535/skynet,korialuo/skynet,xcjmine/skynet,zhangshiqian1214/skynet,sundream/skynet,zhouxiaoxiaoxujian/skynet,pigparadise/skynet,your-gatsby/skynet,JiessieDawn/skynet,leezhongshan/skynet,Ding8222/skynet,kebo/skynet,harryzeng/skynet,korialuo/skynet,sanikoyes/skynet,cloudwu/skynet,MoZhonghua/skynet,bigrpg/skynet,helling34/skynet,rainfiel/skynet,QuiQiJingFeng/skynet,iskygame/skynet,lawnight/skynet,microcai/skynet,hongling0/skynet,zhangshiqian1214/skynet,chenjiansnail/skynet,pichina/skynet,u20024804/skynet,bttscut/skynet,liuxuezhan/skynet,lc412/skynet,vizewang/skynet,qyli/test,fztcjjl/skynet,bingo235/skynet,MetSystem/skynet,Markal128/skynet,winglsh/skynet,Zirpon/skynet,boyuegame/skynet,boyuegame/skynet,xubigshu/skynet,jiuaiwo1314/skynet,fztcjjl/skynet,hongling0/skynet,xinjuncoding/skynet,great90/skynet,sundream/skynet,harryzeng/skynet,Zirpon/skynet,firedtoad/skynet,sdgdsffdsfff/skynet,liuxuezhan/skynet,puXiaoyi/skynet,liuxuezhan/skynet,gitfancode/skynet,matinJ/skynet,yinjun322/skynet,puXiaoyi/skynet,zzh442856860/skynet-Note,firedtoad/skynet,yunGit/skynet,yinjun322/skynet,czlc/skynet,rainfiel/skynet,nightcj/mmo,chuenlungwang/skynet,nightcj/mmo,codingabc/skynet,KAndQ/skynet,sdgdsffdsfff/skynet,firedtoad/skynet,longmian/skynet,KittyCookie/skynet,dymx101/skynet,cmingjian/skynet,qyli/test,KAndQ/skynet,ag6ag/skynet,xinjuncoding/skynet,your-gatsby/skynet,catinred2/skynet,zhaijialong/skynet,zhoukk/skynet,longmian/skynet,togolwb/skynet,hongling0/skynet,cloudwu/skynet,bingo235/skynet,vizewang/skynet,cmingjian/skynet,lawnight/skynet,qyli/test,xubigshu/skynet,jiuaiwo1314/skynet,LiangMa/skynet,xjdrew/skynet,codingabc/skynet,bingo235/skynet,pichina/skynet,microcai/skynet,bigrpg/skynet,yunGit/skynet,samael65535/skynet,ilylia/skynet,plsytj/skynet,gitfancode/skynet,boyuegame/skynet,icetoggle/skynet,cloudwu/skynet,sanikoyes/skynet,sdgdsffdsfff/skynet,QuiQiJingFeng/skynet,ag6ag/skynet,zhouxiaoxiaoxujian/skynet,dymx101/skynet,lawnight/skynet,cdd990/skynet,QuiQiJingFeng/skynet,ypengju/skynet_comment,fhaoquan/skynet,cdd990/skynet,JiessieDawn/skynet,great90/skynet,xinmingyao/skynet,Ding8222/skynet,zhangshiqian1214/skynet,MetSystem/skynet,cpascal/skynet,Ding8222/skynet,felixdae/skynet,ludi1991/skynet,gitfancode/skynet,MRunFoss/skynet,MRunFoss/skynet,zhouxiaoxiaoxujian/skynet,helling34/skynet,ludi1991/skynet,chfg007/skynet,plsytj/skynet,enulex/skynet,jxlczjp77/skynet,togolwb/skynet,LiangMa/skynet,zhaijialong/skynet,KittyCookie/skynet,letmefly/skynet,xjdrew/skynet,wangjunwei01/skynet,rainfiel/skynet,great90/skynet,cpascal/skynet,ludi1991/skynet,xjdrew/skynet,u20024804/skynet,lc412/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,zhoukk/skynet,cuit-zhaxin/skynet,KAndQ/skynet,leezhongshan/skynet,cmingjian/skynet,yunGit/skynet,bttscut/skynet,cuit-zhaxin/skynet,codingabc/skynet,chenjiansnail/skynet,JiessieDawn/skynet,javachengwc/skynet,MoZhonghua/skynet,asanosoyokaze/skynet,Markal128/skynet,vizewang/skynet,chenjiansnail/skynet,kebo/skynet,fztcjjl/skynet,plsytj/skynet,qyli/test,pichina/skynet,xcjmine/skynet,zzh442856860/skynet-Note,xcjmine/skynet,kyle-wang/skynet,enulex/skynet,chfg007/skynet,iskygame/skynet,javachengwc/skynet
6fe833c9dc45914a693c2f381e33ed0a78cd241a
src/lluv/qless/utils.lua
src/lluv/qless/utils.lua
local function prequire(...) local ok, mod = pcall(require, ...) if not ok then return nil, mod end return mod, ... end local uuid = require "uuid" local sha1 = require "bgcrypto.sha1" local socket = require "socket" local json = require "cjson" local uv = require "lluv" local Utils do local getpid do local _pid local psapi = prequire("pdh.psapi") if psapi then getpid = function () if not _pid then local proc = psapi.process() _pid = proc:pid() proc:destroy() end return _pid end end if not getpid then local posix = prequire ("posix") if not (posix and posix.getpid) then posix = prequire ("posix.unistd") end if posix and posix.getpid then getpid = function () if not _pid then _pid = posix.getpid() end return _pid end end end assert(getpid, 'can not find getpid implementation. Try install lua-posix library for *nix or lua-pdh for Windwos') end local _hostname local function gethostname() if not _hostname then _hostname = socket.dns.gethostname() end return _hostname end local function now() return os.time() end local function generate_jid() return string.gsub(uuid.new(), '%-', '') end local function dummy() end local function pass_self(self, cb) return function(_, ...) return cb(self, ...) end end local function is_callable(f) return (type(f) == 'function') and f end local pack_args = function(...) local n = select("#", ...) local args = {...} local cb = args[n] if is_callable(cb) then args[n] = nil n = n - 1 else cb = dummy end return args, cb, n end local function read_sha1_file(fname) local f, e = io.open(fname, "rb") if not f then return nil, e end local data = f:read("*all") f:close() data = data:gsub("\r\n", "\n"):gsub("%f[^\n]%-%-[^\n]-\n", ""):gsub("^%-%-[^\n]-\n", "") return data, sha1.digest(data, true) end -- create monitoring timer to be able to reconnect redis connection local function reconnect_redis(cnn, interval, on_connect, on_disconnect) local error_handler, timer, connected timer = uv.timer():start(0, interval, function(self) self:stop() cnn:open(error_handler) end):stop() error_handler = function(_, err) if err and connected then on_disconnect(cnn, err) end connected = not err if connected then return on_connect(cnn) end if not timer:closed() then timer:again() end end -- so we can pass first connect error connected = true cnn:open(error_handler) cnn:on_error(error_handler) return timer end local DummyLogger = {} do local lvl = {'emerg','alert','fatal','error','warning','notice','info','debug','trace'} for _, l in ipairs(lvl) do DummyLogger[l] = dummy; DummyLogger[l..'_dump'] = dummy; end local api = {'writer', 'formatter', 'format', 'lvl', 'set_lvl', 'set_writer', 'set_formatter', 'set_format'} for _, meth in ipairs(api) do DummyLogger[meth] = dummy end end local function super(self, m, ...) return self.__base[m](self, ...) end Utils = { super = super; now = now; getpid = getpid; gethostname = gethostname; generate_jid = generate_jid; pass_self = pass_self; pack_args = pack_args; dummy = dummy; read_sha1_file = read_sha1_file; is_callable = is_callable; json = json; reconnect_redis = reconnect_redis; dummy_logger = DummyLogger; } end return Utils
local function prequire(...) local ok, mod = pcall(require, ...) if not ok then return nil, mod end return mod, ... end local uuid = require "uuid" local sha1 = require "bgcrypto.sha1" local socket = require "socket" local json = require "cjson" local uv = require "lluv" local Utils do local getpid do local _pid local psapi = prequire("pdh.psapi") if psapi then getpid = function () if not _pid then local proc = psapi.process() _pid = proc:pid() proc:destroy() end return _pid end end if not getpid then local posix = prequire ("posix") if not (posix and posix.getpid) then posix = prequire ("posix.unistd") end if posix and posix.getpid then getpid = function () if not _pid then _pid = posix.getpid() if type(_pid) == 'table' then _pid = _pid.pid end end return _pid end end end assert(getpid, 'can not find getpid implementation. Try install lua-posix library for *nix or lua-pdh for Windwos') end local _hostname local function gethostname() if not _hostname then _hostname = socket.dns.gethostname() end return _hostname end local function now() return os.time() end local function generate_jid() return string.gsub(uuid.new(), '%-', '') end local function dummy() end local function pass_self(self, cb) return function(_, ...) return cb(self, ...) end end local function is_callable(f) return (type(f) == 'function') and f end local pack_args = function(...) local n = select("#", ...) local args = {...} local cb = args[n] if is_callable(cb) then args[n] = nil n = n - 1 else cb = dummy end return args, cb, n end local function read_sha1_file(fname) local f, e = io.open(fname, "rb") if not f then return nil, e end local data = f:read("*all") f:close() data = data:gsub("\r\n", "\n"):gsub("%f[^\n]%-%-[^\n]-\n", ""):gsub("^%-%-[^\n]-\n", "") return data, sha1.digest(data, true) end -- create monitoring timer to be able to reconnect redis connection local function reconnect_redis(cnn, interval, on_connect, on_disconnect) local error_handler, timer, connected timer = uv.timer():start(0, interval, function(self) self:stop() cnn:open(error_handler) end):stop() error_handler = function(_, err) if err and connected then on_disconnect(cnn, err) end connected = not err if connected then return on_connect(cnn) end if not timer:closed() then timer:again() end end -- so we can pass first connect error connected = true cnn:open(error_handler) cnn:on_error(error_handler) return timer end local DummyLogger = {} do local lvl = {'emerg','alert','fatal','error','warning','notice','info','debug','trace'} for _, l in ipairs(lvl) do DummyLogger[l] = dummy; DummyLogger[l..'_dump'] = dummy; end local api = {'writer', 'formatter', 'format', 'lvl', 'set_lvl', 'set_writer', 'set_formatter', 'set_format'} for _, meth in ipairs(api) do DummyLogger[meth] = dummy end end local function super(self, m, ...) return self.__base[m](self, ...) end Utils = { super = super; now = now; getpid = getpid; gethostname = gethostname; generate_jid = generate_jid; pass_self = pass_self; pack_args = pack_args; dummy = dummy; read_sha1_file = read_sha1_file; is_callable = is_callable; json = json; reconnect_redis = reconnect_redis; dummy_logger = DummyLogger; } end return Utils
Fix. posix.getpid returns table instead of integer.
Fix. posix.getpid returns table instead of integer.
Lua
mit
moteus/lua-lluv-qless
e08dd1a31907dd52c861c2ecd2ef265257d01ea1
mods/a_addons/mobs_mc/heads.lua
mods/a_addons/mobs_mc/heads.lua
--MC Heads for minetest --maikerumine minetest.register_node( "mobs_mc:creeper_head", { description = "Creeper Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_creeper.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", --visual_scale = 0.5, is_ground_content = false, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:enderman_head", { description = "Enderman Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_endermen.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:ghast_head", { description = "Ghast Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "ghast_front.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:skeleton_head", { description = "Skeleton Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_skeleton.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = false, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:skeleton2_head", { description = "Skeleton2 Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_skeleton2.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:spider_head", { description = "Spider Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_spider.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:zombie_head", { description = "Zombie Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_zombie.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:zombiepig_head", { description = "Zombie Pigmen Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "Original_Zombiepig_Man_by_Fedora_P.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, })
--MC Heads for minetest --maikerumine minetest.register_node( "mobs_mc:creeper_head", { description = "Creeper Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_creeper.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", --visual_scale = 0.5, is_ground_content = false, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:enderman_head", { description = "Enderman Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_endermen.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:ghast_head", { description = "Ghast Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "ghast_front.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:skeleton_head", { description = "Skeleton Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_skeleton.png" }, paramtype2 = "facedir", visual_scale = 0.5, is_ground_content = false, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:skeleton2_head", { description = "Skeleton2 Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_skeleton2.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:spider_head", { description = "Spider Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_spider.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:zombie_head", { description = "Zombie Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "mobs_zombie.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, }) minetest.register_node( "mobs_mc:zombiepig_head", { description = "Zombie Pigmen Head-W.I.P.", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "Original_Zombiepig_Man_by_Fedora_P.png" }, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.25, -0.49, -0.25, 0.25, 0.01, 0.25}, }, drawtype = "nodebox", paramtype = "light", is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 1, })
Heads fix size
Heads fix size
Lua
lgpl-2.1
maikerumine/grieftest
87cffe16106952e20be67ed105e5c1a7cc9f0675
lib/px/pxnginx.lua
lib/px/pxnginx.lua
-- Copyright © 2016 PerimeterX, Inc. -- 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 _M = {} function _M.application(file_name) -- Support for multiple apps - each app file should be named "pxconfig-<appname>.lua" local config_file = ((file_name == nil or file_name == '') and "px.pxconfig" or "px.pxconfig-" .. file_name) local px_config = require (config_file) local px_filters = require ("px.utils.pxfilters").load(config_file) local px_client = require ("px.utils.pxclient").load(config_file) local px_cookie = require ("px.utils.pxcookie").load(config_file) local px_captcha = require ("px.utils.pxcaptcha").load(config_file) local px_block = require ("px.block.pxblock").load(config_file) local px_api = require ("px.utils.pxapi").load(config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local px_headers = require ("px.utils.pxheaders").load(config_file) local auth_token = px_config.auth_token local enable_server_calls = px_config.enable_server_calls local risk_api_path = px_config.risk_api_path local enabled_routes = px_config.enabled_routes local remote_addr = ngx.var.remote_addr or "" local user_agent = ngx.var.http_user_agent or "" local string_sub = string.sub local string_len = string.len local pcall = pcall if not px_config.px_enabled then return true end local valid_route = false -- Enable module only on configured routes for i = 1, #enabled_routes do if string_sub(ngx.var.uri, 1, string_len(enabled_routes[i])) == enabled_routes[i] then px_logger.debug("Checking for enabled routes. " .. enabled_routes[i]) valid_route = true end end if not valid_route and #enabled_routes > 0 then px_headers.set_score_header(0) return true end -- Validate if request is from internal redirect to avoid duplicate processing if px_headers.validate_internal_request() then return true end -- Clean any protected headers from the request. -- Prevents header spoofing to upstream application px_headers.clear_protected_headers() -- run filter and whitelisting logic if (px_filters.process()) then px_headers.set_score_header(0) return true end px_logger.debug("New request process. IP: " .. remote_addr .. ". UA: " .. user_agent) -- process _px cookie if present local _px = ngx.var.cookie__px local _pxCaptcha = ngx.var.cookie__pxCaptcha if px_config.captcha_enabled and _pxCaptcha then local success, result = pcall(px_captcha.process, _pxCaptcha) -- validating captcha value and if reset was successful then pass the request if success and result == 0 then ngx.header['Set-Cookie'] = '_pxCaptcha=; Expires=Thu, 01 Jan 1970 00:00:00 GMT;' return true end end local success, result = pcall(px_cookie.process, _px) -- cookie verification passed - checking result. if success then -- score crossed threshold if result == false then return px_block.block('cookie_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested") return true end -- cookie verification failed/cookie does not exist. performing s2s query elseif enable_server_calls == true then local request_data = px_api.new_request_object(result.message) local success, response = pcall(px_api.call_s2s, request_data, risk_api_path, auth_token) local result if success then result = px_api.process(response) -- score crossed threshold if result == false then px_logger.error("blocking s2s") return px_block.block('s2s_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested") return true end else -- server2server call failed, passing traffic px_client.send_to_perimeterx("page_requested") return true end else px_client.send_to_perimeterx("page_requested") return true end end return _M
-- Copyright © 2016 PerimeterX, Inc. -- 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 _M = {} function _M.application(file_name) -- Support for multiple apps - each app file should be named "pxconfig-<appname>.lua" local config_file = ((file_name == nil or file_name == '') and "px.pxconfig" or "px.pxconfig-" .. file_name) local px_config = require (config_file) local px_filters = require ("px.utils.pxfilters").load(config_file) local px_client = require ("px.utils.pxclient").load(config_file) local px_cookie = require ("px.utils.pxcookie").load(config_file) local px_captcha = require ("px.utils.pxcaptcha").load(config_file) local px_block = require ("px.block.pxblock").load(config_file) local px_api = require ("px.utils.pxapi").load(config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local px_headers = require ("px.utils.pxheaders").load(config_file) local auth_token = px_config.auth_token local enable_server_calls = px_config.enable_server_calls local risk_api_path = px_config.risk_api_path local enabled_routes = px_config.enabled_routes local remote_addr = ngx.var.remote_addr or "" local user_agent = ngx.var.http_user_agent or "" local string_sub = string.sub local string_len = string.len local pcall = pcall if not px_config.px_enabled then return true end local valid_route = false -- Enable module only on configured routes for i = 1, #enabled_routes do if string_sub(ngx.var.uri, 1, string_len(enabled_routes[i])) == enabled_routes[i] then px_logger.debug("Checking for enabled routes. " .. enabled_routes[i]) valid_route = true end end if not valid_route and #enabled_routes > 0 then px_headers.set_score_header(0) return true end -- Validate if request is from internal redirect to avoid duplicate processing if px_headers.validate_internal_request() then return true end -- Clean any protected headers from the request. -- Prevents header spoofing to upstream application px_headers.clear_protected_headers() -- run filter and whitelisting logic if (px_filters.process()) then px_headers.set_score_header(0) return true end px_logger.debug("New request process. IP: " .. remote_addr .. ". UA: " .. user_agent) -- process _px cookie if present local _px = ngx.var.cookie__px local _pxCaptcha = ngx.var.cookie__pxCaptcha if px_config.captcha_enabled and _pxCaptcha then local success, result = pcall(px_captcha.process, _pxCaptcha) -- validating captcha value and if reset was successful then pass the request if success and result == 0 then ngx.header["Content-Type"] = nil ngx.header["Set-Cookie"] = "_pxCaptcha=; Expires=Thu, 01 Jan 1970 00:00:00 GMT;" return true end end local success, result = pcall(px_cookie.process, _px) -- cookie verification passed - checking result. if success then -- score crossed threshold if result == false then return px_block.block('cookie_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested") return true end -- cookie verification failed/cookie does not exist. performing s2s query elseif enable_server_calls == true then local request_data = px_api.new_request_object(result.message) local success, response = pcall(px_api.call_s2s, request_data, risk_api_path, auth_token) local result if success then result = px_api.process(response) -- score crossed threshold if result == false then px_logger.error("blocking s2s") return px_block.block('s2s_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested") return true end else -- server2server call failed, passing traffic px_client.send_to_perimeterx("page_requested") return true end else px_client.send_to_perimeterx("page_requested") return true end end return _M
Fixed content-type bug
Fixed content-type bug
Lua
mit
PerimeterX/perimeterx-nginx-plugin
3d05fbd55b9755c428aa72e834bf9a556baad571
heka/sandbox/decoders/http_edge_decoder.lua
heka/sandbox/decoders/http_edge_decoder.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- See https://wiki.mozilla.org/CloudServices/DataPipeline/HTTPEdgeServerSpecification require "cjson" require "lpeg" require "string" require "table" require 'geoip.city' -- Split a path into components. Multiple consecutive separators do not -- result in empty path components. -- Examples: -- /foo/bar -> {"foo", "bar"} -- ///foo//bar/ -> {"foo", "bar"} -- foo/bar/ -> {"foo", "bar"} -- / -> {} local sep = lpeg.P("/") local elem = lpeg.C((1 - sep)^1) local path_grammar = lpeg.Ct(elem^0 * (sep^0 * elem)^0) local function split_path(s) if not s then return {} end return lpeg.match(path_grammar, s) end local city_db = assert(geoip.city.open(read_config("geoip_city_db"))) local UNK_GEO = "??" function get_geo_country(xff, remote_addr) local country if xff then local first_addr = string.match(xff, "([^, ]+)") if first_addr then country = city_db:query_by_addr(first_addr, "country_code") end end if country then return country end if remote_addr then country = city_db:query_by_addr(remote_addr, "country_code") end return country or UNK_GEO end -- Load the namespace configuration externally. -- Note that if the config contains invalid JSON, we will discard any messages -- we receive with the following error: -- FATAL: process_message() function was not found local ok, ns_config = pcall(cjson.decode, read_config("namespace_config")) if not ok then return -1, ns_config end -- This is a copy of the raw message that will be passed through as-is. local landfill_msg = { Timestamp = nil, Type = nil, Hostname = nil, Pid = nil, Logger = nil, Payload = nil, EnvVersion = nil, Severity = nil, Fields = nil } -- This is the modified message that knows about namespaces and so forth. local main_msg = { Timestamp = nil, Type = "http_edge_incoming", Payload = nil, EnvVersion = nil, Hostname = nil, Fields = nil } function process_message() -- First, copy the current message as-is. landfill_msg.Timestamp = read_message("Timestamp") landfill_msg.Type = read_message("Type") landfill_msg.Hostname = read_message("Hostname") landfill_msg.Pid = read_message("Pid") -- UUID is auto-generated and meaningless anyways landfill_msg.Logger = read_message("Logger") landfill_msg.Payload = read_message("Payload") landfill_msg.EnvVersion = read_message("EnvVersion") landfill_msg.Severity = read_message("Severity") -- Now copy the fields: landfill_msg.Fields = {} while true do local value_type, name, value, representation, count = read_next_field() if not name then break end -- Keep the first occurence only (we want the value supplied by the -- HttpListenInput, not the user-supplied one if we have to choose). if not landfill_msg.Fields[name] then landfill_msg.Fields[name] = value end end local landfill_status, landfill_err = pcall(inject_message, landfill_msg) if not landfill_status then return -1, landfill_err end -- Reset Fields, since different namespaces may use different fields. main_msg.Fields = {} -- Carry forward payload some incoming fields. main_msg.Payload = landfill_msg.Payload main_msg.Timestamp = landfill_msg.Timestamp main_msg.EnvVersion = landfill_msg.EnvVersion -- Note: 'Hostname' is the host name of the server that received the -- message, while 'Host' is the name of the HTTP endpoint the client -- used (such as "incoming.telemetry.mozilla.org"). main_msg.Hostname = landfill_msg.Hostname main_msg.Fields.Host = landfill_msg.Fields.Host -- Path should be of the form: -- ^/submit/namespace/id[/extra/path/components]$ local path = landfill_msg.Fields.Path local components = split_path(path) -- Skip this message: Not enough path components. if not components or #components < 3 then return -1, "Not enough path components" end local submit = table.remove(components, 1) -- Skip this message: Invalid path prefix. if submit ~= "submit" then return -1, string.format("Invalid path prefix: '%s' in %s", submit, path) end local namespace = table.remove(components, 1) -- Get namespace configuration, look up params, override Logger if needed. local cfg = ns_config[namespace] -- Skip this message: Invalid namespace. if not cfg then return -1, string.format("Invalid namespace: '%s' in %s", namespace, path) end main_msg.Logger = namespace local dataLength = string.len(main_msg.Payload) -- Skip this message: Payload too large. if dataLength > cfg.max_data_length then return -1, string.format("Payload too large: %d > %d", dataLength, cfg.max_data_length) end local pathLength = string.len(path) -- Skip this message: Path too long. if pathLength > cfg.max_path_length then return -1, string.format("Path too long: %d > %d", pathLength, cfg.max_path_length) end -- Override Logger if specified. if cfg["logger"] then main_msg.Logger = cfg["logger"] end -- This documentId is what we should use to de-duplicate submissions. main_msg.Fields.documentId = table.remove(components, 1) local num_components = #components if num_components > 0 then local dims = cfg["dimensions"] if dims ~= nil and #dims >= num_components then for i=1,num_components do main_msg.Fields[dims[i]] = components[i] end else -- Didn't have dimension spec, or had too many components. main_msg.Fields.PathComponents = components end end -- Insert geo info. local xff = landfill_msg.Fields["X-Forwarded-For"] local remote_addr = landfill_msg.Fields["RemoteAddr"] main_msg.Fields.geoCountry = get_geo_country(xff, remote_addr) -- Send new message along. local main_status, main_err = pcall(inject_message, main_msg) if not main_status then return -1, main_err end return 0 end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- See https://wiki.mozilla.org/CloudServices/DataPipeline/HTTPEdgeServerSpecification require "cjson" require "lpeg" require "string" require "table" require 'geoip.city' -- Split a path into components. Multiple consecutive separators do not -- result in empty path components. -- Examples: -- /foo/bar -> {"foo", "bar"} -- ///foo//bar/ -> {"foo", "bar"} -- foo/bar/ -> {"foo", "bar"} -- / -> {} local sep = lpeg.P("/") local elem = lpeg.C((1 - sep)^1) local path_grammar = lpeg.Ct(elem^0 * (sep^0 * elem)^0) local function split_path(s) if not s then return {} end return lpeg.match(path_grammar, s) end local city_db = assert(geoip.city.open(read_config("geoip_city_db"))) local UNK_GEO = "??" function get_geo_country(xff, remote_addr) local country if xff then local first_addr = string.match(xff, "([^, ]+)") if first_addr then country = city_db:query_by_addr(first_addr, "country_code") end end if country then return country end if remote_addr then country = city_db:query_by_addr(remote_addr, "country_code") end return country or UNK_GEO end -- Load the namespace configuration externally. -- Note that if the config contains invalid JSON, we will discard any messages -- we receive with the following error: -- FATAL: process_message() function was not found local ok, ns_config = pcall(cjson.decode, read_config("namespace_config")) if not ok then return -1, ns_config end -- This is a copy of the raw message that will be passed through as-is. local landfill_msg = { Timestamp = nil, Type = nil, Hostname = nil, Pid = nil, Logger = nil, Payload = nil, EnvVersion = nil, Severity = nil, Fields = nil } -- This is the modified message that knows about namespaces and so forth. local main_msg = { Timestamp = nil, Type = "http_edge_incoming", Payload = nil, EnvVersion = nil, Hostname = nil, Fields = nil } function process_message() -- First, copy the current message as-is. landfill_msg.Timestamp = read_message("Timestamp") landfill_msg.Type = read_message("Type") landfill_msg.Hostname = read_message("Hostname") landfill_msg.Pid = read_message("Pid") -- UUID is auto-generated and meaningless anyways landfill_msg.Logger = read_message("Logger") landfill_msg.Payload = read_message("Payload") landfill_msg.EnvVersion = read_message("EnvVersion") landfill_msg.Severity = read_message("Severity") -- Now copy the fields: landfill_msg.Fields = {} while true do local value_type, name, value, representation, count = read_next_field() if not name then break end -- Keep the first occurence only (we want the value supplied by the -- HttpListenInput, not the user-supplied one if we have to choose). if not landfill_msg.Fields[name] then landfill_msg.Fields[name] = value end end local landfill_status, landfill_err = pcall(inject_message, landfill_msg) if not landfill_status then return -1, landfill_err end -- Reset Fields, since different namespaces may use different fields. main_msg.Fields = {} -- Carry forward payload some incoming fields. main_msg.Payload = landfill_msg.Payload main_msg.Timestamp = landfill_msg.Timestamp main_msg.EnvVersion = landfill_msg.EnvVersion -- Note: 'Hostname' is the host name of the server that received the -- message, while 'Host' is the name of the HTTP endpoint the client -- used (such as "incoming.telemetry.mozilla.org"). main_msg.Hostname = landfill_msg.Hostname main_msg.Fields.Host = landfill_msg.Fields.Host -- Path should be of the form: -- ^/submit/namespace/id[/extra/path/components]$ local path = landfill_msg.Fields.Path local components = split_path(path) -- Skip this message: Not enough path components. if not components or #components < 3 then return -1, "Not enough path components" end local submit = table.remove(components, 1) -- Skip this message: Invalid path prefix. if submit ~= "submit" then return -1, string.format("Invalid path prefix: '%s' in %s", submit, path) end local namespace = table.remove(components, 1) -- Get namespace configuration, look up params, override Logger if needed. local cfg = ns_config[namespace] -- Skip this message: Invalid namespace. if not cfg then return -1, string.format("Invalid namespace: '%s' in %s", namespace, path) end main_msg.Logger = namespace local dataLength = string.len(main_msg.Payload) -- Skip this message: Payload too large. if dataLength > cfg.max_data_length then return -1, string.format("Payload too large: %d > %d", dataLength, cfg.max_data_length) end local pathLength = string.len(path) -- Skip this message: Path too long. if pathLength > cfg.max_path_length then return -1, string.format("Path too long: %d > %d", pathLength, cfg.max_path_length) end -- Override Logger if specified. if cfg["logger"] then main_msg.Logger = cfg["logger"] end -- This documentId is what we should use to de-duplicate submissions. main_msg.Fields.documentId = table.remove(components, 1) local num_components = #components if num_components > 0 then local dims = cfg["dimensions"] if dims ~= nil and #dims >= num_components then for i=1,num_components do main_msg.Fields[dims[i]] = components[i] end else -- Didn't have dimension spec, or had too many components. main_msg.Fields.PathComponents = components end end -- Insert geo info. local xff = landfill_msg.Fields["X-Forwarded-For"] local remote_addr = landfill_msg.Fields["RemoteAddr"] main_msg.Fields.geoCountry = get_geo_country(xff, remote_addr) -- Remove the PII Bugzilla 1143818 landfill_msg.Fields["X-Forwarded-For"] = nil landfill_msg.Fields["RemoteAddr"] = nil -- Send new message along. local main_status, main_err = pcall(inject_message, main_msg) if not main_status then return -1, main_err end return 0 end
Remove the IP address PII
Remove the IP address PII https://bugzilla.mozilla.org/show_bug.cgi?id=1143818
Lua
mpl-2.0
mreid-moz/data-pipeline,mozilla-services/data-pipeline,nathwill/data-pipeline,mozilla-services/data-pipeline,mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,mreid-moz/data-pipeline,nathwill/data-pipeline,acmiyaguchi/data-pipeline,sapohl/data-pipeline,kparlante/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,whd/data-pipeline,whd/data-pipeline,acmiyaguchi/data-pipeline,kparlante/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,mreid-moz/data-pipeline,kparlante/data-pipeline,nathwill/data-pipeline,nathwill/data-pipeline
38d2d6cc96de74d8d6112e599226b16cce523409
modules/farming_module.lua
modules/farming_module.lua
------------------------------------------------------------ -- Copyright (c) 2016 tacigar -- https://github.com/tacigar/maidroid ------------------------------------------------------------ local _aux = maidroid.modules._aux local state = { walk = 0, punch = 1, plant = 2, walk_to_plant = 3, walk_to_soil = 4, } local max_punch_time = 20 local max_plant_time = 15 local search_lenvec = {x = 3, y = 0, z = 3} -- find max size of each plants local target_plants_list = {} minetest.after(0, function() local max = {} for name, node in pairs(minetest.registered_nodes) do if minetest.get_item_group(name, "plant") > 0 then local s, i = string.match(name, "(.+)_(%d+)") if max[s] == nil or max[s] < i then max[s] = i end end end for s, i in pairs(max) do table.insert(target_plants_list, s.."_"..i) end end) -- check the maidroid has seed items local function has_seed_item(self) local inv = maidroid._aux.get_maidroid_inventory(self) local stacks = inv:get_list("main") for _, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then return true end end return false end -- check can plant plants. local function can_plant(self, pos) local node = minetest.get_node(pos) local upos = _aux.get_under_pos(pos) local unode = minetest.get_node(upos) return node.name == "air" and minetest.get_item_group(unode.name, "wet") > 0 and has_seed_item(self) end -- check can punch plant local function can_punch(self, pos) local node = minetest.get_node(pos) return maidroid.util.table_find_value(target_plants_list, node.name) end -- change state to walk local function to_walk(self) self.state = state.walk self.destination = nil self.object:set_animation(maidroid.animations.walk, 15, 0) self.time_count = 0 _aux.change_dir(self) end maidroid.register_module("maidroid:farming_module", { description = "Maidroid Module : Farming", inventory_image = "maidroid_farming_module.png", initialize = function(self) self.object:set_animation(maidroid.animations.walk, 15, 0) self.object:setacceleration{x = 0, y = -10, z = 0} self.state = state.walk self.preposition = self.object:getpos() self.time_count = 0 self.destination = nil -- for walk_to_* _aux.change_dir(self) end, finalize = function(self) self.state = nil self.preposition = nil self.time_count = nil self.destination = nil self.object:setvelocity{x = 0, y = 0, z = 0} end, on_step = function(self, dtime) local pos = self.object:getpos() local rpos = vector.round(pos) local upos = _aux.get_under_pos(pos) local yaw = self.object:getyaw() local forward_vec = _aux.get_forward(yaw) local forward_vec2 = _aux.get_round_forward(forward_vec) local forward_pos = vector.add(rpos, forward_vec2) local forward_node = minetest.get_node(forward_pos) local forward_under_pos = vector.subtract(forward_pos, {x = 0, y = 1, z = 0}) _aux.pickup_item(self, 1.5, function(itemstring) -- pickup droped seed items return minetest.get_item_group(itemstring, "seed") > 0 end) if self.state == state.walk then -- searching plants or spaces local b1, dest1 = _aux.search_surrounding(self, search_lenvec, can_plant) local b2, dest2 = _aux.search_surrounding(self, search_lenvec, can_punch) -- search soil node near if b1 then -- to soil self.state = state.walk_to_soil self.destination = dest1 _aux.change_dir_to(self, dest1) elseif b2 then self.state = state.walk_to_plant self.destination = dest2 _aux.change_dir_to(self, dest2) elseif pos.x == self.preposition.x or pos.z == self.preposition.z then _aux.change_dir(self) end elseif self.state == state.punch then if self.time_count >= max_punch_time then if can_punch(self, self.destination) then local destnode = minetest.get_node(self.destination) minetest.remove_node(self.destination) local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = minetest.get_node_drops(destnode.name) for _, stack in ipairs(stacks) do local leftover = inv:add_item("main", stack) minetest.add_item(self.destination, leftover) end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.plant then if self.time_count >= max_plant_time then if can_plant(self, self.destination) then local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = inv:get_list("main") for idx, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then minetest.add_node(self.destination, {name = item_name, param2 = 1}) stack:take_item(1) inv:set_stack("main", idx, stack) break end end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.walk_to_soil then if vector.distance(pos, self.destination) < 1.5 then -- to plant state local destnode = minetest.get_node(self.destination) if (can_plant(self, self.destination)) then self.state = state.plant self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end elseif self.state == state.walk_to_plant then if vector.distance(pos, self.destination) < 1.5 then local destnode = minetest.get_node(self.destination) if maidroid.util.table_find_value(target_plants_list, destnode.name) then self.state = state.punch self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end end self.preposition = pos return end })
------------------------------------------------------------ -- Copyright (c) 2016 tacigar -- https://github.com/tacigar/maidroid ------------------------------------------------------------ local _aux = maidroid.modules._aux local state = { walk = 0, punch = 1, plant = 2, walk_to_plant = 3, walk_to_soil = 4, } local max_punch_time = 20 local max_plant_time = 15 local search_lenvec = {x = 3, y = 0, z = 3} -- find max size of each plants local target_plants_list = {} minetest.after(0, function() local max = {} for name, node in pairs(minetest.registered_nodes) do if minetest.get_item_group(name, "plant") > 0 then local s, i = string.match(name, "(.+)_(%d+)") if max[s] == nil or max[s] < i then max[s] = i end end end for s, i in pairs(max) do table.insert(target_plants_list, s.."_"..i) end end) -- check the maidroid has seed items local function has_seed_item(self) local inv = maidroid._aux.get_maidroid_inventory(self) local stacks = inv:get_list("main") for _, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then return true end end return false end -- check can plant plants. local function can_plant(self, pos) local node = minetest.get_node(pos) local upos = _aux.get_under_pos(pos) local unode = minetest.get_node(upos) return node.name == "air" and minetest.get_item_group(unode.name, "wet") > 0 and has_seed_item(self) end -- check can punch plant local function can_punch(self, pos) local node = minetest.get_node(pos) return maidroid.util.table_find_value(target_plants_list, node.name) end -- change state to walk local function to_walk(self) self.state = state.walk self.destination = nil self.object:set_animation(maidroid.animations.walk, 15, 0) self.time_count = 0 _aux.change_dir(self) end maidroid.register_module("maidroid:farming_module", { description = "Maidroid Module : Farming", inventory_image = "maidroid_farming_module.png", initialize = function(self) self.object:set_animation(maidroid.animations.walk, 15, 0) self.object:setacceleration{x = 0, y = -10, z = 0} self.state = state.walk self.preposition = self.object:getpos() self.time_count = 0 self.destination = nil -- for walk_to_* _aux.change_dir(self) end, finalize = function(self) self.state = nil self.preposition = nil self.time_count = nil self.destination = nil self.object:setvelocity{x = 0, y = 0, z = 0} end, on_step = function(self, dtime) local pos = self.object:getpos() local rpos = vector.round(pos) local upos = _aux.get_under_pos(pos) local yaw = self.object:getyaw() _aux.pickup_item(self, 1.5, function(itemstring) -- pickup droped seed items return minetest.get_item_group(itemstring, "seed") > 0 end) if self.state == state.walk then -- searching plants or spaces local b1, dest1 = _aux.search_surrounding(self, search_lenvec, can_plant) local b2, dest2 = _aux.search_surrounding(self, search_lenvec, can_punch) -- search soil node near if b1 then -- to soil self.state = state.walk_to_soil self.destination = dest1 _aux.change_dir_to(self, dest1) elseif b2 then self.state = state.walk_to_plant self.destination = dest2 _aux.change_dir_to(self, dest2) elseif pos.x == self.preposition.x or pos.z == self.preposition.z then _aux.change_dir(self) end elseif self.state == state.punch then if self.time_count >= max_punch_time then if can_punch(self, self.destination) then local destnode = minetest.get_node(self.destination) minetest.remove_node(self.destination) local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = minetest.get_node_drops(destnode.name) for _, stack in ipairs(stacks) do local leftover = inv:add_item("main", stack) minetest.add_item(self.destination, leftover) end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.plant then if self.time_count >= max_plant_time then if can_plant(self, self.destination) then local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = inv:get_list("main") for idx, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then minetest.add_node(self.destination, {name = item_name, param2 = 1}) stack:take_item(1) inv:set_stack("main", idx, stack) break end end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.walk_to_soil then if vector.distance(pos, self.destination) < 1.5 then -- to plant state local destnode = minetest.get_node(self.destination) if (can_plant(self, self.destination)) then self.state = state.plant self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end elseif self.state == state.walk_to_plant then if vector.distance(pos, self.destination) < 1.5 then local destnode = minetest.get_node(self.destination) if maidroid.util.table_find_value(target_plants_list, destnode.name) then self.state = state.punch self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end end self.preposition = pos return end })
Fix farming module
Fix farming module
Lua
lgpl-2.1
tacigar/maidroid
0641936cd7800e0ec27f953566e9ad7d2f743529
xmake/plugins/show/lists/toolchains.lua
xmake/plugins/show/lists/toolchains.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 toolchains.lua -- -- imports import("core.tool.toolchain") import("core.base.text") -- show all toolchains function main() local tbl = {align = 'l', sep = " "} for _, name in ipairs(toolchain.list()) do local t = toolchain.load(name) table.insert(tbl, {name, t:get("description")}) end print(text.table(tbl)) 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 toolchains.lua -- -- imports import("core.tool.toolchain") import("core.base.text") import("core.project.config") import("core.project.project") -- show all toolchains function main() config.load() local tbl = {align = 'l', sep = " "} for _, name in ipairs(toolchain.list()) do local t = os.isfile(os.projectfile()) and project.toolchain(name) or toolchain.load(name) table.insert(tbl, {name, t:get("description")}) end print(text.table(tbl)) end
fix show toolchains
fix show toolchains
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
02fd4231619211af0c66913036e3e85f1463e7e7
test_scripts/RC/GetInteriorVehicleDataCapabilities/008.lua
test_scripts/RC/GetInteriorVehicleDataCapabilities/008.lua
--------------------------------------------------------------------------------------------------- -- RPC: GetInteriorVehicleDataCapabilities -- Script: 008 --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local commonRC = require('test_scripts/RC/commonRC') local runner = require('user_modules/script_runner') --[[ Local Functions ]] local function step(module_types, self) local cid = self.mobileSession:SendRPC("GetInteriorVehicleDataCapabilities", { moduleTypes = module_types }) EXPECT_HMICALL("RC.GetInteriorVehicleDataCapabilities", { appID = self.applications["Test Application"], moduleTypes = module_types }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { interiorVehicleDataCapabilities = commonRC.getInteriorVehicleDataCapabilities(module_types) }) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", interiorVehicleDataCapabilities = commonRC.getInteriorVehicleDataCapabilities(module_types) }) end local function ptu_update_func(tbl) tbl.policy_table.app_policies[config.application1.registerAppInterfaceParams.appID].moduleType = { } end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu, { ptu_update_func }) runner.Title("Test") runner.Step("GetInteriorVehicleDataCapabilities_CLIMATE", step, { { "CLIMATE" } }) runner.Step("GetInteriorVehicleDataCapabilities_RADIO", step, { { "RADIO" } }) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--------------------------------------------------------------------------------------------------- -- RPC: GetInteriorVehicleDataCapabilities -- Script: 008 --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local commonRC = require('test_scripts/RC/commonRC') local runner = require('user_modules/script_runner') local json = require('modules/json') --[[ Local Functions ]] local function step(module_types, self) local cid = self.mobileSession:SendRPC("GetInteriorVehicleDataCapabilities", { moduleTypes = module_types }) EXPECT_HMICALL("RC.GetInteriorVehicleDataCapabilities", { appID = self.applications["Test Application"], moduleTypes = module_types }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { interiorVehicleDataCapabilities = commonRC.getInteriorVehicleDataCapabilities(module_types) }) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", interiorVehicleDataCapabilities = commonRC.getInteriorVehicleDataCapabilities(module_types) }) end local function ptu_update_func(tbl) tbl.policy_table.app_policies[config.application1.registerAppInterfaceParams.appID].moduleType = json.EMPTY_ARRAY end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu, { ptu_update_func }) runner.Title("Test") runner.Step("GetInteriorVehicleDataCapabilities_CLIMATE", step, { { "CLIMATE" } }) runner.Step("GetInteriorVehicleDataCapabilities_RADIO", step, { { "RADIO" } }) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
Fix empty array sending
Fix empty array sending The problem is that PTU generated by current script have moduleType value {} which is not correct and this is a reason of PTU failure. The correct one is []. This commit solves this issue.
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
6ca51f40ee7343698d7c79b4e8e222d4250490f8
lexers/dmd.lua
lexers/dmd.lua
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- D LPeg lexer. -- Heavily modified by Brian Schott (SirAlaran). local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '//' * l.nonnewline_esc^0 local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1 local nested_comment = l.nested_pair('/+', '+/', true) local comment = token(l.COMMENT, line_comment + block_comment + nested_comment) -- Strings. local sq_str = l.delimited_range("'", '\\', true, false, '\n') * S('cwd')^-1 local dq_str = l.delimited_range('"', '\\', true, false, '\n') * S('cwd')^-1 local lit_str = 'r' * l.delimited_range('"', nil, true, false, '\n') * S('cwd')^-1 local bt_str = l.delimited_range('`', '\\', nil, false, '\n') * S('cwd')^-1 local hex_str = 'x' * l.delimited_range('"', '\\', nil, false, '\n') * S('cwd')^-1 local del_str = 'q"' * (l.any - '"')^0 * P('"')^-1 local tok_str = 'q' * l.nested_pair('{', '}', true) local other_hex_str = '\\x' * (l.xdigit * l.xdigit)^1 local string = token(l.STRING, sq_str + dq_str + lit_str + bt_str + hex_str + del_str + tok_str + other_hex_str) -- Numbers. local dec = l.digit^1 * ('_' * l.digit^1)^0 local bin_num = '0' * S('bB') * S('01_')^1 local oct_num = '0' * S('01234567_')^1 local integer = S('+-')^-1 * (l.hex_num + oct_num + bin_num + dec) local number = token(l.NUMBER, (l.float + integer) * S('uUlLdDfFi')^-1) -- Keywords. local keyword = token(l.KEYWORD, word_match { 'abstract', 'align', 'asm', 'assert', 'auto', 'body', 'break', 'case', 'cast', 'catch', 'const', 'continue', 'debug', 'default', 'delete', 'deprecated', 'do', 'else', 'extern', 'export', 'false', 'final', 'finally', 'for', 'foreach', 'foreach_reverse', 'goto', 'if', 'import', 'immutable', 'in', 'inout', 'invariant', 'is', 'lazy', 'macro', 'mixin', 'new', 'nothrow', 'null', 'out', 'override', 'pragma', 'private', 'protected', 'public', 'pure', 'ref', 'return', 'scope', 'shared', 'static', 'super', 'switch', 'synchronized', 'this', 'throw','true', 'try', 'typeid', 'typeof', 'unittest', 'version', 'volatile', 'while', 'with', '__gshared', '__thread', '__traits' }) -- Types. local type = token(l.TYPE, word_match { 'alias', 'bool', 'byte', 'cdouble', 'cent', 'cfloat', 'char', 'class', 'creal', 'dchar', 'delegate', 'double', 'enum', 'float', 'function', 'idouble', 'ifloat', 'int', 'interface', 'ireal', 'long', 'module', 'package', 'ptrdiff_t', 'real', 'short', 'size_t', 'struct', 'template', 'typedef', 'ubyte', 'ucent', 'uint', 'ulong', 'union', 'ushort', 'void', 'wchar', 'string', 'wstring', 'dstring', 'hash_t', 'equals_t' }) -- Constants. local constant = token(l.CONSTANT, word_match { '__FILE__', '__LINE__', '__DATE__', '__EOF__', '__TIME__', '__TIMESTAMP__', '__VENDOR__', '__VERSION__', 'DigitalMars', 'X86', 'X86_64', 'Windows', 'Win32', 'Win64', 'linux', 'Posix', 'LittleEndian', 'BigEndian', 'D_Coverage', 'D_InlineAsm_X86', 'D_InlineAsm_X86_64', 'D_LP64', 'D_PIC', 'D_Version2', 'all', }) local class_sequence = token(l.TYPE, P('class') + P('struct')) * ws^1 * token(l.CLASS, l.word) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Operators. local operator = token(l.OPERATOR, S('?=!<>+-*$/%&|^~.,;()[]{}')) -- Properties. local properties = (type + identifier + operator) * token(l.OPERATOR, '.') * token(l.VARIABLE, word_match { 'alignof', 'dig', 'dup', 'epsilon', 'idup', 'im', 'init', 'infinity', 'keys', 'length', 'mangleof', 'mant_dig', 'max', 'max_10_exp', 'max_exp', 'min', 'min_normal', 'min_10_exp', 'min_exp', 'nan', 'offsetof', 'ptr', 're', 'rehash', 'reverse', 'sizeof', 'sort', 'stringof', 'tupleof', 'values' }) -- Preprocs. local annotation = token('annotation', '@' * l.word^1) local preproc = token(l.PREPROCESSOR, '#' * l.nonnewline^0) -- Traits. local traits_list = token('traits', word_match { "isAbstractClass", "isArithmetic", "isAssociativeArray", "isFinalClass", "isFloating", "isIntegral", "isScalar", "isStaticArray", "isUnsigned", "isVirtualFunction", "isAbstractFunction", "isFinalFunction", "isStaticFunction", "isRef", "isOut", "isLazy", "hasMember", "identifier", "getMember", "getOverloads", "getVirtualFunctions", "classInstanceSize", "allMembers", "derivedMembers", "isSame", "compiles" }) local traits = token(l.KEYWORD, '__traits') * l.space^0 * token(l.OPERATOR, '(') * l.space^0 * traits_list local func = token(l.FUNCTION, l.word) * #(l.space^0 * (P('!') * l.word^-1 * l.space^-1)^-1 * P('(')) _rules = { { 'whitespace', ws }, { 'class', class_sequence }, { 'traits', traits }, { 'keyword', keyword }, { 'variable', properties }, { 'type', type }, { 'function', func}, { 'constant', constant }, { 'identifier', identifier }, { 'string', string }, { 'comment', comment }, { 'number', number }, { 'preproc', preproc }, { 'operator', operator }, { 'annotation', annotation }, { 'any_char', l.any_char }, } _tokenstyles = { { 'annotation', l.style_preproc }, { 'traits', l.style_definition }, } _foldsymbols = { _patterns = { '[{}]', '/[*+]', '[*+]/', '//' }, [l.OPERATOR] = { ['{'] = 1, ['}'] = -1 }, [l.COMMENT] = { ['/*'] = 1, ['*/'] = -1, ['/+'] = 1, ['+/'] = -1, ['//'] = l.fold_line_comments('//') } }
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- D LPeg lexer. -- Heavily modified by Brian Schott (SirAlaran). local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '//' * l.nonnewline_esc^0 local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1 local nested_comment = l.nested_pair('/+', '+/', true) local comment = token(l.COMMENT, line_comment + block_comment + nested_comment) -- Strings. local sq_str = l.delimited_range("'", '\\', true, false, '\n') * S('cwd')^-1 local dq_str = l.delimited_range('"', '\\', true, false, '\n') * S('cwd')^-1 local lit_str = 'r' * l.delimited_range('"', nil, true, false, '\n') * S('cwd')^-1 local bt_str = l.delimited_range('`', '\\', nil, false, '\n') * S('cwd')^-1 local hex_str = 'x' * l.delimited_range('"', '\\', nil, false, '\n') * S('cwd')^-1 local other_hex_str = '\\x' * (l.xdigit * l.xdigit)^1 local del_str = l.nested_pair('q"[', ']"', true) + l.nested_pair('q"(', ')"', true) + l.nested_pair('q"{', '}"', true) + l.nested_pair('q"<', '>"', true) + P('q') * l.nested_pair('{', '}', true) local string = token(l.STRING, del_str + sq_str + dq_str + lit_str + bt_str + hex_str + other_hex_str) -- Numbers. local dec = l.digit^1 * ('_' * l.digit^1)^0 local bin_num = '0' * S('bB') * S('01_')^1 local oct_num = '0' * S('01234567_')^1 local integer = S('+-')^-1 * (l.hex_num + oct_num + bin_num + dec) local number = token(l.NUMBER, (l.float + integer) * S('uUlLdDfFi')^-1) -- Keywords. local keyword = token(l.KEYWORD, word_match { 'abstract', 'align', 'asm', 'assert', 'auto', 'body', 'break', 'case', 'cast', 'catch', 'const', 'continue', 'debug', 'default', 'delete', 'deprecated', 'do', 'else', 'extern', 'export', 'false', 'final', 'finally', 'for', 'foreach', 'foreach_reverse', 'goto', 'if', 'import', 'immutable', 'in', 'inout', 'invariant', 'is', 'lazy', 'macro', 'mixin', 'new', 'nothrow', 'null', 'out', 'override', 'pragma', 'private', 'protected', 'public', 'pure', 'ref', 'return', 'scope', 'shared', 'static', 'super', 'switch', 'synchronized', 'this', 'throw','true', 'try', 'typeid', 'typeof', 'unittest', 'version', 'volatile', 'while', 'with', '__gshared', '__thread', '__traits' }) -- Types. local type = token(l.TYPE, word_match { 'alias', 'bool', 'byte', 'cdouble', 'cent', 'cfloat', 'char', 'class', 'creal', 'dchar', 'delegate', 'double', 'enum', 'float', 'function', 'idouble', 'ifloat', 'int', 'interface', 'ireal', 'long', 'module', 'package', 'ptrdiff_t', 'real', 'short', 'size_t', 'struct', 'template', 'typedef', 'ubyte', 'ucent', 'uint', 'ulong', 'union', 'ushort', 'void', 'wchar', 'string', 'wstring', 'dstring', 'hash_t', 'equals_t' }) -- Constants. local constant = token(l.CONSTANT, word_match { '__FILE__', '__LINE__', '__DATE__', '__EOF__', '__TIME__', '__TIMESTAMP__', '__VENDOR__', '__VERSION__', 'DigitalMars', 'X86', 'X86_64', 'Windows', 'Win32', 'Win64', 'linux', 'Posix', 'LittleEndian', 'BigEndian', 'D_Coverage', 'D_InlineAsm_X86', 'D_InlineAsm_X86_64', 'D_LP64', 'D_PIC', 'D_Version2', 'all', }) local class_sequence = token(l.TYPE, P('class') + P('struct')) * ws^1 * token(l.CLASS, l.word) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Operators. local operator = token(l.OPERATOR, S('?=!<>+-*$/%&|^~.,;()[]{}')) -- Properties. local properties = (type + identifier + operator) * token(l.OPERATOR, '.') * token(l.VARIABLE, word_match { 'alignof', 'dig', 'dup', 'epsilon', 'idup', 'im', 'init', 'infinity', 'keys', 'length', 'mangleof', 'mant_dig', 'max', 'max_10_exp', 'max_exp', 'min', 'min_normal', 'min_10_exp', 'min_exp', 'nan', 'offsetof', 'ptr', 're', 'rehash', 'reverse', 'sizeof', 'sort', 'stringof', 'tupleof', 'values' }) -- Preprocs. local annotation = token('annotation', '@' * l.word^1) local preproc = token(l.PREPROCESSOR, '#' * l.nonnewline^0) -- Traits. local traits_list = token('traits', word_match { "isAbstractClass", "isArithmetic", "isAssociativeArray", "isFinalClass", "isFloating", "isIntegral", "isScalar", "isStaticArray", "isUnsigned", "isVirtualFunction", "isAbstractFunction", "isFinalFunction", "isStaticFunction", "isRef", "isOut", "isLazy", "hasMember", "identifier", "getMember", "getOverloads", "getVirtualFunctions", "classInstanceSize", "allMembers", "derivedMembers", "isSame", "compiles" }) local traits = token(l.KEYWORD, '__traits') * l.space^0 * token(l.OPERATOR, '(') * l.space^0 * traits_list local func = token(l.FUNCTION, l.word) * #(l.space^0 * (P('!') * l.word^-1 * l.space^-1)^-1 * P('(')) _rules = { { 'whitespace', ws }, { 'class', class_sequence }, { 'traits', traits }, { 'keyword', keyword }, { 'variable', properties }, { 'type', type }, { 'function', func}, { 'constant', constant }, { 'string', string }, { 'identifier', identifier }, { 'comment', comment }, { 'number', number }, { 'preproc', preproc }, { 'operator', operator }, { 'annotation', annotation }, { 'any_char', l.any_char }, } _tokenstyles = { { 'annotation', l.style_preproc }, { 'traits', l.style_definition }, } _foldsymbols = { _patterns = { '[{}]', '/[*+]', '[*+]/', '//' }, [l.OPERATOR] = { ['{'] = 1, ['}'] = -1 }, [l.COMMENT] = { ['/*'] = 1, ['*/'] = -1, ['/+'] = 1, ['+/'] = -1, ['//'] = l.fold_line_comments('//') } }
Fixed multi-line delimited strings and token strings; lexers/dmd.lua Thanks to Brian Schott.
Fixed multi-line delimited strings and token strings; lexers/dmd.lua Thanks to Brian Schott.
Lua
mit
rgieseke/scintillua
cd930a21562c6309bb884cd0f4d6cdbd3763e02b
OS/DiskOS/Programs/help.lua
OS/DiskOS/Programs/help.lua
--Liko12 Help System ! if select(1,...) == "-?" then printUsage( "help","Displays the help info", "help Topics","Displays help topics list", "help <topic>", "Displays a help topic" ) return end local lume = require("Libraries.lume") local helpPATH = "C:/Help/" local function nextPath() if helpPATH:sub(-1)~=";" then helpPATH=helpPATH..";" end return helpPATH:gmatch("(.-);") end local topic = select(1,...) topic = topic or "Welcome" local giveApi = select(1,...) if type(giveApi) == "boolean" then --Requesting HELP api local api = {} function api.setHelpPATH(p) helpPATH = p end function api.getHelpPATH() return helpPATH end return api end helpPATH = require("Programs.help",true).getHelpPATH() --A smart way to keep the helpPath palt(0,false) --Make black opaque local doc --The help document to print for path in nextPath() do if fs.exists(path..topic) then doc = path..topic break elseif fs.exists(path..topic..".lua") then doc = path..topic..".lua" break end end if not doc then return 1, "Help file not found '"..topic.."' !" end -- Waits for any input (keyboard or mouse) to continue -- Returns true if "q" was pressed, to quit local function waitkey() while true do local name, a = pullEvent() if name == "keypressed" then return false elseif name == "textinput" then if string.lower(a) == "q" then return true else return end elseif name == "touchpressed" then textinput(true) end end end printCursor(0) --Set the x pos to 0 (the start of the screen) local tw, th = termSize() local msg = "[press any key to continue, q to quit]" local msglen = msg:len() local skipY = select(2,printCursor()) -- Smart print with the "press any key to continue" message -- Returns true if "q" was pressed, which should abort the process local function sprint(text) if text == "" then text = " " end local iter = text:gmatch(".") local curX, curY = printCursor() skipY = skipY - 1 local codeBlockFlag = false for char in iter do if char == "\\" then local nchar = iter() if nchar == "\\" then print(nchar,false) else color(tonumber(nchar,16)) curX = curX - 1 end elseif char == "`" then color(codeBlockFlag and 7 or 6) codeBlockFlag = not codeBlockFlag curX = curX - 1 elseif char == "\n" then print(char,false) curX = tw-1 --A new line :o else print(char,false) end curX = curX + 1 if curX == tw then --End of line curX, curY = 0, curY+1 if curY == th then curY = th-1 sleep(0.02) clearEStack() if skipY > 0 then skipY = skipY - 1 else pushColor() color(9) print(msg,false) flip() local quit = waitkey() for i=1,msglen do printBackspace() end popColor() if quit then return true end end end end end end local lua = (doc:sub(-4,-1) == ".lua") if lua then doc = fs.load(doc)() if not doc then print("") return 0 end else doc = fs.read(doc) end doc = doc:gsub("\r\n","\n") doc = doc:gsub("\\LIKO%-12","\\CL\\8I\\BK\\9O\\7-\\F12") color(7) sprint(doc) print("")
--Liko12 Help System ! if select(1,...) == "-?" then printUsage( "help","Displays the help info", "help Topics","Displays help topics list", "help <topic>", "Displays a help topic" ) return end local lume = require("Libraries.lume") local helpPATH = "C:/Help/" local function nextPath() if helpPATH:sub(-1)~=";" then helpPATH=helpPATH..";" end return helpPATH:gmatch("(.-);") end local topic = select(1,...) topic = topic or "Welcome" local giveApi = select(1,...) if type(giveApi) == "boolean" then --Requesting HELP api local api = {} function api.setHelpPATH(p) helpPATH = p end function api.getHelpPATH() return helpPATH end return api end helpPATH = require("Programs.help",true).getHelpPATH() --A smart way to keep the helpPath palt(0,false) --Make black opaque local doc --The help document to print for path in nextPath() do if fs.exists(path..topic) then doc = path..topic break elseif fs.exists(path..topic..".lua") then doc = path..topic..".lua" break end end if not doc then return 1, "Help file not found '"..topic.."' !" end -- Waits for any input (keyboard or mouse) to continue -- Returns true if "q" was pressed, to quit local function waitkey() clearEStack() while true do local name, a = pullEvent() if name == "keypressed" then return false elseif name == "textinput" then if string.lower(a) == "q" then return true else return end elseif name == "touchpressed" then textinput(true) end end end printCursor(0) --Set the x pos to 0 (the start of the screen) local tw, th = termSize() local msg = "[press any key to continue, q to quit]" local msglen = msg:len() local skipY = select(2,printCursor()) -- Smart print with the "press any key to continue" message -- Returns true if "q" was pressed, which should abort the process local function sprint(text) if text == "" then text = " " end local iter = text:gmatch(".") local curX, curY = printCursor() skipY = skipY - 1 local codeBlockFlag = false for char in iter do if char == "\\" then local nchar = iter() if nchar == "\\" then print(nchar,false) else color(tonumber(nchar,16)) curX = curX - 1 end elseif char == "`" then color(codeBlockFlag and 7 or 6) codeBlockFlag = not codeBlockFlag curX = curX - 1 elseif char == "\n" then print(char,false) curX = tw-1 --A new line :o else print(char,false) end curX = curX + 1 if curX == tw then --End of line curX, curY = 0, curY+1 if curY == th then curY = th-1 sleep(0.02) if skipY > 0 then skipY = skipY - 1 else pushColor() color(9) print(msg,false) flip() local quit = waitkey() for i=1,msglen do printBackspace() end popColor() if quit then return true end end end end end end local lua = (doc:sub(-4,-1) == ".lua") if lua then doc = fs.load(doc)() if not doc then print("") return 0 end else doc = fs.read(doc) end doc = doc:gsub("\r\n","\n") doc = doc:gsub("\\LIKO%-12","\\CL\\8I\\BK\\9O\\7-\\F12") color(7) sprint(doc) print("")
my fault, fix a new made bug in `help`
my fault, fix a new made bug in `help` Former-commit-id: 2c49c8b06fa18c6a036a982ad6f38c7622785692
Lua
mit
RamiLego4Game/LIKO-12
8b808db61e712f62817e0a25590db4bb320f6e8b
packages/pullquote.lua
packages/pullquote.lua
SILE.require("packages/color") SILE.require("packages/raiselower") SILE.require("packages/rebox") SILE.registerCommand("pullquote:font", function (_, _) end, "The font chosen for the pullquote environment") SILE.registerCommand("pullquote:author-font", function (_, _) SILE.settings.set("font.style", "italic") end, "The font style with which to typeset the author attribution.") SILE.registerCommand("pullquote:mark-font", function (_, _) SILE.settings.set("font.family", "Libertinus Serif") end, "The font from which to pull the quotation marks.") local typesetMark = function (open, setback, scale, color, mark) SILE.settings.temporarily(function () SILE.call("pullquote:mark-font") local setwidth = SU.cast("length", setback) SILE.typesetter:pushGlue({ width = open and -setwidth or setwidth }) SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function () SILE.settings.set("font.size", SILE.settings.get("font.size")*scale) SILE.call("color", { color = color }, function () SILE.call("rebox", { width = 0, height = 0 }, { mark }) end) end) SILE.typesetter:pushGlue({width = open and setwidth or -setwidth }) end) end SILE.registerCommand("pullquote", function (options, content) local author = options.author or nil local setback = options.setback or "2em" local scale = options.scale or 3 local color = options.color or "#999999" SILE.settings.temporarily(function () SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback)) SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback)) SILE.settings.set("current.parindent", SILE.nodefactory.glue()) SILE.call("pullquote:font") typesetMark(true, setback, scale, color, "“") SILE.process(content) SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue()) typesetMark(false, setback, scale, color, "”") if author then SILE.settings.temporarily(function () SILE.typesetter:leaveHmode() SILE.call("pullquote:author-font") SILE.call("raggedleft", {}, function () SILE.typesetter:typeset("— " .. author) end) end) else SILE.call("par") end end) end, "Typesets its contents in a formatted blockquote with decorative quotation\ marks in the margins.") return { documentation = [[\begin{document} The \code{pullquote} command formats longer quotations in an indented blockquote block with decorative quotation marks in the margins. Here is some text set in a pullquote environment: \begin[author=Anatole France]{pullquote} An education is not how much you have committed to memory, or even how much you know. It is being able to differentiate between what you do know and what you do not know. \end{pullquote} Optional values are available for: • \code{author} to add an attribution line\par • \code{setback} to set the bilateral margins around the block\par • \code{color} to change the color of the quote marks\par • \code{scale} to change the relative size of the quote marks\par If you want to specify what font the pullquote environment should use, you can redefine the \code{pullquote:font} command. By default it will be the same as the surrounding document. The font style used for the attribution line can likewise be set using \code{pullquote:author-font} and the font used for the quote marks can be set using \code{pullquote:mark-font}. \end{document}]] }
SILE.require("packages/color") SILE.require("packages/raiselower") SILE.require("packages/rebox") SILE.registerCommand("pullquote:font", function (_, _) end, "The font chosen for the pullquote environment") SILE.registerCommand("pullquote:author-font", function (_, _) SILE.settings.set("font.style", "italic") end, "The font style with which to typeset the author attribution.") SILE.registerCommand("pullquote:mark-font", function (_, _) SILE.settings.set("font.family", "Libertinus Serif") end, "The font from which to pull the quotation marks.") local typesetMark = function (open, setback, scale, color, mark) SILE.settings.temporarily(function () SILE.call("pullquote:mark-font") SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function () SILE.settings.set("font.size", SILE.settings.get("font.size")*scale) SILE.call("color", { color = color }, function () if open then SILE.typesetter:pushGlue({ width = -setback }) SILE.call("rebox", { width = setback, height = 0 }, { mark }) else SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue()) local hbox = SILE.call("hbox", {}, { mark }) table.remove(SILE.typesetter.state.nodes) -- steal it back SILE.typesetter:pushGlue({ width = setback - hbox.width }) SILE.call("rebox", { width = hbox.width, height = 0 }, { mark }) SILE.typesetter:pushGlue({ width = -setback }) end end) end) end) end SILE.registerCommand("pullquote", function (options, content) local author = options.author or nil local scale = options.scale or 3 local color = options.color or "#999999" SILE.settings.temporarily(function () SILE.call("pullquote:font") local setback = SU.cast("length", options.setback or "2em"):absolute() SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback)) SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback)) SILE.settings.set("current.parindent", SILE.nodefactory.glue()) typesetMark(true, setback, scale, color, "“") SILE.process(content) typesetMark(false, setback, scale, color, "”") if author then SILE.settings.temporarily(function () SILE.typesetter:leaveHmode() SILE.call("pullquote:author-font") SILE.call("raggedleft", {}, function () SILE.typesetter:typeset("— " .. author) end) end) else SILE.call("par") end end) end, "Typesets its contents in a formatted blockquote with decorative quotation\ marks in the margins.") return { documentation = [[\begin{document} The \code{pullquote} command formats longer quotations in an indented blockquote block with decorative quotation marks in the margins. Here is some text set in a pullquote environment: \begin[author=Anatole France]{pullquote} An education is not how much you have committed to memory, or even how much you know. It is being able to differentiate between what you do know and what you do not know. \end{pullquote} Optional values are available for: • \code{author} to add an attribution line\par • \code{setback} to set the bilateral margins around the block\par • \code{color} to change the color of the quote marks\par • \code{scale} to change the relative size of the quote marks\par If you want to specify what font the pullquote environment should use, you can redefine the \code{pullquote:font} command. By default it will be the same as the surrounding document. The font style used for the attribution line can likewise be set using \code{pullquote:author-font} and the font used for the quote marks can be set using \code{pullquote:mark-font}. \end{document}]] }
fix(packages): Align pullquote ending mark with outside margin
fix(packages): Align pullquote ending mark with outside margin This will be a change in rendering but seems to have been the intention all along, the way glues and reboxing were implemented was just bogus. With this the opening and closing marks are both aligned to the surrounding r/lmargin instead of the opening being outside and closing inside.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
3e087518594c6104fd19c133062de1f202780d4d
UCDdetective/client.lua
UCDdetective/client.lua
local skins = {1, 2, 7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 66, 67, 68, 70, 71, 72, 73, 78, 79, 80, 81, 82, 83, 84, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128, 132, 133, 134, 135, 136, 137, 142, 143, 144, 146, 147, 153, 154, 155, 156, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 170, 171, 173, 174, 175, 176, 177, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 200, 202, 203, 204, 206, 209, 210, 212, 213, 217, 220, 221, 222, 223, 227, 228, 229, 230, 234, 235, 236, 239, 240, 241, 242, 247, 248, 249, 250, 252, 253, 254, 255, 258, 259, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 290, 291, 292, 293, 294, 295, 296, 297, 299, 300, 301, 302, 303, 305, 306, 307, 308, 309, 310, 311, 312, 9, 10, 11, 12, 13, 31, 38, 39, 40, 41, 53, 54, 55, 56, 63, 64, 69, 75, 76, 77, 85, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 139, 140, 141, 145, 148, 150, 151, 152, 157, 169, 172, 178, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 201, 205, 207, 211, 214, 215, 216, 218, 219, 224, 225, 226, 231, 232, 233, 237, 238, 243, 244, 245, 246, 251, 256, 257, 263, 298, 304} local objects = {1210, 367} local destinations = { {x = 1968.6837, y = -1482.7329, z = 10.8281, rot = 90, objs = {{1996.3604, -1478.6409, 11.644}, {1955.5939, -1474.5669, 13.5469}, {1972.6407, -1473.288, 13.5564}, {1960.7535, -1494.8043, 3.3559}, {1968.764, -1507.5338, 3.5346}}}, {x = 1886.2681, y = -1964.8997, z = 13.5469, rot = 90, objs = {{1866.1803, -1967.1952, 13.5469}, {1869.8966, -1966.8141, 18.6563}, {1886.8195, -1987.1522, 13.5469}, {1913.4451, -1954.0959, 13.5547}, {1904.9744, -1939.4832, 13.5469}}}, {x = 536.8918, y = -1697.5397, z = 16.119, rot = 90, objs = {{511.1562, -1691.8781, 17.5124}, {495.9906, -1705.627, 12.0492}, {508.1011, -1721.1276, 12.042}, {574.5625, -1714.1274, 13.6436}}}, } local curr local prev local ped local blip local col2id = {} local id2obj = {} local hitCount = 0 local objCount addEventHandler("onClientResourceStart", resourceRoot, function () if (localPlayer:getData("Occupation") == "Detective") then newCase() end end ) addEvent("onClientPlayerGetJob", true) addEventHandler("onClientPlayerGetJob", root, function (jobName) if (jobName == "Detective") then newCase() end end ) function newCase() exports.UCDdx:del("detective") if (curr) then prev = curr curr = nil end repeat curr = math.random(1, #destinations) until curr ~= prev local dest = destinations[curr] exports.UCDdx:new("There has been a homicide in "..getZoneName(dest.x, dest.y, dest.z)..". Go there to investigate.", 30, 144, 255) ped = Ped(skins[math.random(1, #skins)], dest.x, dest.y, dest.z) blip = Blip.createAttachedTo(ped, 23) ped.rotation = Vector3(0, 0, dest.rot) ped.health = 0 ped.frozen = true objCount = #dest.objs hitCount = 0 exports.UCDdx:add("detective", "Clues: "..tostring(hitCount).."/"..tostring(objCount), 30, 144, 255) for k, v in ipairs(dest.objs) do local sphere = ColShape.Sphere(v[1], v[2], v[3], 1) addEventHandler("onClientColShapeHit", sphere, onEvidenceHit) local obj = Object(objects[math.random(1, #objects)], v[1], v[2], v[3] - 0.8, 90, 90, 0) obj:setCollisionsEnabled(false) col2id[sphere] = k id2obj[k] = obj end end addEvent("UCDdetective.newCase", true) addEventHandler("UCDdetective.newCase", root, newCase) function onEvidenceHit(plr, matchingDimension) if (plr and plr.type == "player" and plr == localPlayer and col2id[source] and matchingDimension) then id2obj[col2id[source]]:destroy() id2obj[col2id[source]] = nil source:destroy() col2id[source] = nil hitCount = hitCount + 1 exports.UCDdx:add("detective", "Clues: "..tostring(hitCount).."/"..tostring(objCount), 30, 144, 255) if (#id2obj == 0 and hitCount == objCount) then ped:destroy() blip:destroy() exports.UCDdx:new("You have gathered enough evidence to solve the case and determine the killer", 30, 144, 255) triggerServerEvent("UCDdetective.onEvidenceCollected", resourceRoot) Timer(function () exports.UCDdx:del("detective") end, 2000, 1) end end end
local skins = {1, 2, 7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 66, 67, 68, 70, 71, 72, 73, 78, 79, 80, 81, 82, 83, 84, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128, 132, 133, 134, 135, 136, 137, 142, 143, 144, 146, 147, 153, 154, 155, 156, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 170, 171, 173, 174, 175, 176, 177, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 200, 202, 203, 204, 206, 209, 210, 212, 213, 217, 220, 221, 222, 223, 227, 228, 229, 230, 234, 235, 236, 239, 240, 241, 242, 247, 248, 249, 250, 252, 253, 254, 255, 258, 259, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 290, 291, 292, 293, 294, 295, 296, 297, 299, 300, 301, 302, 303, 305, 306, 307, 308, 309, 310, 311, 312, 9, 10, 11, 12, 13, 31, 38, 39, 40, 41, 53, 54, 55, 56, 63, 64, 69, 75, 76, 77, 85, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 139, 140, 141, 145, 148, 150, 151, 152, 157, 169, 172, 178, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 201, 205, 207, 211, 214, 215, 216, 218, 219, 224, 225, 226, 231, 232, 233, 237, 238, 243, 244, 245, 246, 251, 256, 257, 263, 298, 304} local objects = {1210, 367} local destinations = { {x = 1968.6837, y = -1482.7329, z = 10.8281, rot = 90, objs = {{1996.3604, -1478.6409, 11.644}, {1955.5939, -1474.5669, 13.5469}, {1972.6407, -1473.288, 13.5564}, {1960.7535, -1494.8043, 3.3559}, {1968.764, -1507.5338, 3.5346}}}, {x = 1886.2681, y = -1964.8997, z = 13.5469, rot = 90, objs = {{1866.1803, -1967.1952, 13.5469}, {1869.8966, -1966.8141, 18.6563}, {1886.8195, -1987.1522, 13.5469}, {1913.4451, -1954.0959, 13.5547}, {1904.9744, -1939.4832, 13.5469}}}, {x = 536.8918, y = -1697.5397, z = 16.119, rot = 90, objs = {{511.1562, -1691.8781, 17.5124}, {495.9906, -1705.627, 12.0492}, {508.1011, -1721.1276, 12.042}, {574.5625, -1714.1274, 13.6436}}}, } local curr local prev local ped local blip local col2id = {} local id2obj = {} local hitCount = 0 local objCount addEventHandler("onClientResourceStart", resourceRoot, function () if (localPlayer:getData("Occupation") == "Detective") then newCase() end end ) addEvent("onClientPlayerGetJob", true) addEventHandler("onClientPlayerGetJob", root, function (jobName) if (jobName == "Detective") then newCase() return end if (isElement(blip)) then blip:destroy() end curr = nil prev = nil ped = nil blip = nil col2id = {} id2obj = {} hitCount = 0 objCount = nil exports.UCDdx:del("detective") end ) function newCase() exports.UCDdx:del("detective") if (curr) then prev = curr curr = nil end repeat curr = math.random(1, #destinations) until curr ~= prev local dest = destinations[curr] exports.UCDdx:new("There has been a homicide in "..getZoneName(dest.x, dest.y, dest.z)..". Go there to investigate.", 30, 144, 255) ped = Ped(skins[math.random(1, #skins)], dest.x, dest.y, dest.z) blip = Blip.createAttachedTo(ped, 23) ped.rotation = Vector3(0, 0, dest.rot) ped.health = 0 ped.frozen = true objCount = #dest.objs hitCount = 0 exports.UCDdx:add("detective", "Clues: "..tostring(hitCount).."/"..tostring(objCount), 30, 144, 255) for k, v in ipairs(dest.objs) do local sphere = ColShape.Sphere(v[1], v[2], v[3], 1) addEventHandler("onClientColShapeHit", sphere, onEvidenceHit) local obj = Object(objects[math.random(1, #objects)], v[1], v[2], v[3] - 0.8, 90, 90, 0) obj:setCollisionsEnabled(false) col2id[sphere] = k id2obj[k] = obj end end addEvent("UCDdetective.newCase", true) addEventHandler("UCDdetective.newCase", root, newCase) function onEvidenceHit(plr, matchingDimension) if (plr and plr.type == "player" and plr == localPlayer and col2id[source] and matchingDimension) then id2obj[col2id[source]]:destroy() id2obj[col2id[source]] = nil source:destroy() col2id[source] = nil hitCount = hitCount + 1 exports.UCDdx:add("detective", "Clues: "..tostring(hitCount).."/"..tostring(objCount), 30, 144, 255) Sound.playFrontEnd(12) if (#id2obj == 0 and hitCount == objCount) then ped:destroy() blip:destroy() exports.UCDdx:new("You have gathered enough evidence to solve the case and determine the killer", 30, 144, 255) triggerServerEvent("UCDdetective.onEvidenceCollected", resourceRoot) Timer(function () exports.UCDdx:del("detective") end, 2000, 1) end end end
UCDdetective
UCDdetective - Fixed shit still being here when you got another job
Lua
mit
nokizorque/ucd,nokizorque/ucd
da9ddd0c17ded24eb2b3ee3fab74af5913a557ea
lua/entities/starfall_screen/cl_init.lua
lua/entities/starfall_screen/cl_init.lua
include('shared.lua') ENT.RenderGroup = RENDERGROUP_OPAQUE include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") local context = SF.CreateContext(nil, nil, nil, nil, SF.Libraries.CreateLocalTbl{"render"}) surface.CreateFont("Starfall_ErrorFont", { font = "arial", size = 26, weight = 200 }) local dlScreen = nil local dlOwner = nil local dlMain = nil local dlFiles = nil local hashes = {} net.Receive("starfall_screen_download", function(len) if not dlScreen then dlScreen = net.ReadEntity() dlOwner = net.ReadEntity() dlMain = net.ReadString() dlFiles = {} --print("Begin recieving, mainfile:", updata.mainfile) else if net.ReadBit() ~= 0 then --print("End recieving data") dlScreen:CodeSent(dlFiles, dlMain, dlOwner) dlScreen.files = dlFiles dlScreen.mainfile = dlMain dlScreen, dlFiles, dlMain, dlOwner = nil, nil, nil, nil return end local filename = net.ReadString() local filedata = net.ReadString() --print("\tRecieved data for:", filename, "len:", #filedata) dlFiles[filename] = dlFiles[filename] and dlFiles[filename]..filedata or filedata end end) net.Receive("starfall_screen_update", function(len) local screen = net.ReadEntity() if not IsValid(screen) then return end local dirty = false local finish = net.ReadBit() while finish == 0 do local file = net.ReadString() local hash = net.ReadString() if hash ~= hashes[file] then dirty = true hashes[file] = hash end finish = net.ReadBit() end if dirty then net.Start("starfall_screen_download") net.WriteEntity(screen) net.SendToServer() else screen:CodeSent(screen.files, screen.mainfile, screen.owner) end end) usermessage.Hook( "starfall_screen_used", function ( data ) local screen = Entity( data:ReadShort() ) local activator = Entity( data:ReadShort() ) screen:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) ) -- Error message copying if screen.error then SetClipboardText(string.format("%q", screen.error.orig)) end end) function ENT:Initialize() self.GPU = GPULib.WireGPU(self) net.Start("starfall_screen_download") net.WriteEntity(self) net.SendToServer() end function ENT:Think() self.BaseClass.Think(self) self:NextThink(CurTime()) if self.instance and not self.instance.error then self.instance:resetOps() self:runScriptHook("think") end end function ENT:OnRemove() self.GPU:Finalize() if self.instance then self.instance:deinitialize() end end function ENT:Error(msg) -- Notice owner WireLib.AddNotify(self.owner, msg, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1) -- Process error message self.error = {} self.error.orig = msg self.error.source, self.error.line, self.error.msg = string.match(msg, "%[@?SF:(%a+):(%d+)](.+)$") if not self.error.source or not self.error.line or not self.error.msg then self.error.source, self.error.line, self.error.msg = nil, nil, msg else self.error.msg = string.TrimLeft(self.error.msg) end if self.instance then self.instance:deinitialize() self.instance = nil end self:SetOverlayText("Starfall Screen\nInactive (Error)") end function ENT:CodeSent(files, main, owner) if not files or not main or not owner then return end if self.instance then self.instance:deinitialize() end self.owner = owner local ok, instance = SF.Compiler.Compile(files,context,main,owner,{ent=self,render={}}) if not ok then self:Error(instance) return end instance.runOnError = function(inst,...) self:Error(...) end self.instance = instance instance.data.entity = self instance.data.render.gpu = self.GPU instance.data.render.matricies = 0 local ok, msg = instance:initialize() if not ok then self:Error(msg) end if not self.instance then return end local data = instance.data function self.renderfunc() if self.instance then data.render.isRendering = true draw.NoTexture() self:runScriptHook("render") data.render.isRendering = nil elseif self.error then surface.SetTexture(0) surface.SetDrawColor(0, 0, 0, 120) surface.DrawRect(0, 0, 512, 512) draw.DrawText("Error occurred in Starfall Screen:", "Starfall_ErrorFont", 32, 16, Color(0, 255, 255, 255)) -- Cyan draw.DrawText(tostring(self.error.msg), "Starfall_ErrorFont", 16, 80, Color(255, 0, 0, 255)) if self.error.source and self.error.line then draw.DrawText("Line: "..tostring(self.error.line), "Starfall_ErrorFont", 16, 512-16*7, Color(255, 255, 255, 255)) draw.DrawText("Source: "..self.error.source, "Starfall_ErrorFont", 16, 512-16*5, Color(255, 255, 255, 255)) end draw.DrawText("Press USE to copy to your clipboard", "Starfall_ErrorFont", 512 - 16*25, 512-16*2, Color(255, 255, 255, 255)) self.renderfunc = nil end end end function ENT:Draw() self:DrawModel() Wire_Render(self) if self.renderfunc then self.GPU:RenderToGPU(self.renderfunc) end self.GPU:Render() end
include('shared.lua') ENT.RenderGroup = RENDERGROUP_OPAQUE include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") local context = SF.CreateContext(nil, nil, nil, nil, SF.Libraries.CreateLocalTbl{"render"}) surface.CreateFont("Starfall_ErrorFont", { font = "arial", size = 26, weight = 200 }) local dlScreen = nil local dlOwner = nil local dlMain = nil local dlFiles = nil local hashes = {} net.Receive("starfall_screen_download", function(len) if not dlScreen then dlScreen = net.ReadEntity() dlOwner = net.ReadEntity() dlMain = net.ReadString() dlFiles = {} --print("Begin recieving, mainfile:", updata.mainfile) else if net.ReadBit() ~= 0 then --print("End recieving data") if dlScreen:IsValid() then dlScreen:CodeSent( dlFiles, dlMain, dlOwner ) dlScreen.files = dlFiles dlScreen.mainfile = dlMain end dlScreen, dlFiles, dlMain, dlOwner = nil, nil, nil, nil return end local filename = net.ReadString() local filedata = net.ReadString() --print("\tRecieved data for:", filename, "len:", #filedata) dlFiles[filename] = dlFiles[filename] and dlFiles[filename]..filedata or filedata end end) net.Receive("starfall_screen_update", function(len) local screen = net.ReadEntity() if not IsValid(screen) then return end local dirty = false local finish = net.ReadBit() while finish == 0 do local file = net.ReadString() local hash = net.ReadString() if hash ~= hashes[file] then dirty = true hashes[file] = hash end finish = net.ReadBit() end if dirty then net.Start("starfall_screen_download") net.WriteEntity(screen) net.SendToServer() else screen:CodeSent(screen.files, screen.mainfile, screen.owner) end end) usermessage.Hook( "starfall_screen_used", function ( data ) local screen = Entity( data:ReadShort() ) local activator = Entity( data:ReadShort() ) screen:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) ) -- Error message copying if screen.error then SetClipboardText(string.format("%q", screen.error.orig)) end end) function ENT:Initialize() self.GPU = GPULib.WireGPU(self) net.Start("starfall_screen_download") net.WriteEntity(self) net.SendToServer() end function ENT:Think() self.BaseClass.Think(self) self:NextThink(CurTime()) if self.instance and not self.instance.error then self.instance:resetOps() self:runScriptHook("think") end end function ENT:OnRemove() self.GPU:Finalize() if self.instance then self.instance:deinitialize() end end function ENT:Error(msg) -- Notice owner WireLib.AddNotify(self.owner, msg, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1) -- Process error message self.error = {} self.error.orig = msg self.error.source, self.error.line, self.error.msg = string.match(msg, "%[@?SF:(%a+):(%d+)](.+)$") if not self.error.source or not self.error.line or not self.error.msg then self.error.source, self.error.line, self.error.msg = nil, nil, msg else self.error.msg = string.TrimLeft(self.error.msg) end if self.instance then self.instance:deinitialize() self.instance = nil end self:SetOverlayText("Starfall Screen\nInactive (Error)") end function ENT:CodeSent(files, main, owner) if not files or not main or not owner then return end if self.instance then self.instance:deinitialize() end self.owner = owner local ok, instance = SF.Compiler.Compile(files,context,main,owner,{ent=self,render={}}) if not ok then self:Error(instance) return end instance.runOnError = function(inst,...) self:Error(...) end self.instance = instance instance.data.entity = self instance.data.render.gpu = self.GPU instance.data.render.matricies = 0 local ok, msg = instance:initialize() if not ok then self:Error(msg) end if not self.instance then return end local data = instance.data function self.renderfunc() if self.instance then data.render.isRendering = true draw.NoTexture() self:runScriptHook("render") data.render.isRendering = nil elseif self.error then surface.SetTexture(0) surface.SetDrawColor(0, 0, 0, 120) surface.DrawRect(0, 0, 512, 512) draw.DrawText("Error occurred in Starfall Screen:", "Starfall_ErrorFont", 32, 16, Color(0, 255, 255, 255)) -- Cyan draw.DrawText(tostring(self.error.msg), "Starfall_ErrorFont", 16, 80, Color(255, 0, 0, 255)) if self.error.source and self.error.line then draw.DrawText("Line: "..tostring(self.error.line), "Starfall_ErrorFont", 16, 512-16*7, Color(255, 255, 255, 255)) draw.DrawText("Source: "..self.error.source, "Starfall_ErrorFont", 16, 512-16*5, Color(255, 255, 255, 255)) end draw.DrawText("Press USE to copy to your clipboard", "Starfall_ErrorFont", 512 - 16*25, 512-16*2, Color(255, 255, 255, 255)) self.renderfunc = nil end end end function ENT:Draw() self:DrawModel() Wire_Render(self) if self.renderfunc then self.GPU:RenderToGPU(self.renderfunc) end self.GPU:Render() end
Fix CodeSent error
Fix CodeSent error Fixes #45
Lua
bsd-3-clause
Jazzelhawk/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall
a330b77ef9b015bec1826e5866bd16f1f4d99b0f
scen_edit/view/main_window/general_panel.lua
scen_edit/view/main_window/general_panel.lua
GeneralPanel = AbstractMainWindowPanel:extends{} function GeneralPanel:init() self:super("init") self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Save scenario", OnClick = { function() local dir = FilePanel.lastDir or SCEN_EDIT_EXAMPLE_DIR_RAW_FS sfd = SaveFileDialog(dir) sfd:setConfirmDialogCallback( function(path) local saveCommand = SaveCommand(path) success, errMsg = pcall(function() SCEN_EDIT.commandManager:execute(saveCommand, true) end) if not success then Spring.Echo(errMsg) end end ) end }, children = { Image:New { file=SCEN_EDIT_IMG_DIR .. "document-save.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Save", y = 40, x = 14, }, }, } ) self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Load scenario", OnClick = { function() local dir = FilePanel.lastDir or SCEN_EDIT_EXAMPLE_DIR_RAW_FS ofd = OpenFileDialog(dir) ofd:setConfirmDialogCallback( function(path) Spring.Echo("Loading archive: " .. path .. " ...") if not VFS.FileExists(path, VFS.RAW) then Spring.Echo("Archive doesn't exist: " .. path) return end VFS.MapArchive(path) Spring.Echo("Loaded archive.") local data = VFS.LoadFile("model.lua", VFS.ZIP) cmd = LoadCommand(data) SCEN_EDIT.commandManager:execute(cmd) local data = VFS.LoadFile("heightmap.data", VFS.ZIP) loadMap = LoadMap(data) SCEN_EDIT.commandManager:execute(loadMap) end ) end }, children = { Image:New { file = SCEN_EDIT_IMG_DIR .. "document-open.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Load", y = 40, x = 14, }, }, } ) self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Scenario info settings", OnClick = { function() local scenarioInfoView = ScenarioInfoView() end }, children = { Image:New { file = SCEN_EDIT_IMG_DIR .. "info.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Info", y = 40, x = 14, }, }, } ) end
GeneralPanel = AbstractMainWindowPanel:extends{} function GeneralPanel:init() self:super("init") self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Save scenario", OnClick = { function() local dir = FilePanel.lastDir or SCEN_EDIT_EXAMPLE_DIR_RAW_FS sfd = SaveFileDialog(dir) sfd:setConfirmDialogCallback( function(path) local saveCommand = SaveCommand(path) success, errMsg = pcall(function() SCEN_EDIT.commandManager:execute(saveCommand, true) end) if not success then Spring.Echo(errMsg) end end ) end }, children = { Image:New { file=SCEN_EDIT_IMG_DIR .. "document-save.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Save", y = 40, x = 14, }, }, } ) self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Load scenario", OnClick = { function() local dir = FilePanel.lastDir or SCEN_EDIT_EXAMPLE_DIR_RAW_FS ofd = OpenFileDialog(dir) ofd:setConfirmDialogCallback( function(path) Spring.Echo("Loading archive: " .. path .. " ...") if not VFS.FileExists(path, VFS.RAW) then Spring.Echo("Archive doesn't exist: " .. path) return end if SCEN_EDIT.loadedArchive ~= nil then VFS.UnmapArchive(SCEN_EDIT.loadedArchive) end VFS.MapArchive(path) SCEN_EDIT.loadedArchive = path Spring.Echo("Loaded archive.") local data = VFS.LoadFile("model.lua", VFS.ZIP) cmd = LoadCommand(data) SCEN_EDIT.commandManager:execute(cmd) local data = VFS.LoadFile("heightmap.data", VFS.ZIP) loadMap = LoadMap(data) SCEN_EDIT.commandManager:execute(loadMap) end ) end }, children = { Image:New { file = SCEN_EDIT_IMG_DIR .. "document-open.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Load", y = 40, x = 14, }, }, } ) self.control:AddChild(Button:New { height = 80, width = 80, caption = '', tooltip = "Scenario info settings", OnClick = { function() local scenarioInfoView = ScenarioInfoView() end }, children = { Image:New { file = SCEN_EDIT_IMG_DIR .. "info.png", height = 40, width = 40, margin = {0, 0, 0, 0}, x = 10, }, Label:New { caption = "Info", y = 40, x = 14, }, }, } ) end
fixed archive reloading (97.0+)
fixed archive reloading (97.0+)
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
eb0f68c31367e676889cb529a679fdeefbd40540
bhop/gamemode/shared.lua
bhop/gamemode/shared.lua
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- GM.Name = "Bunny Hop" GM.Author = "xAaron113x" GM.Email = "[email protected]" GM.Website = "aaron113.pw" GM.TeamBased = false DeriveGamemode("ssbase") DEFINE_BASECLASS("gamemode_ssbase") --for self.BaseClass GM.VIPBonusHP = false GM.HUDShowVel = true GM.HUDShowTimer = true SS.Alldoors = { "bhop_archives", "bhop_monster_jam" } TEAM_BHOP = 1 team.SetUp(TEAM_BHOP, "Hoppers", Color(87, 198, 255), false) function GM:EntityKeyValue(ent, key, value) if(ent:GetClass() == "func_door") then if(table.HasValue(SS.Alldoors,game.GetMap())) then ent.IsP = true end if(string.find(string.lower(key),"movedir")) then if(value == "90 0 0") then ent.IsP = true end end if(string.find(string.lower(key),"noise1")) then ent.BHS = value end if(string.find(string.lower(key),"speed")) then if(tonumber(value) > 100) then ent.IsP = true end ent.BHSp = tonumber(value) end end if(ent:GetClass() == "func_button") then if(table.HasValue(SS.Alldoors,game.GetMap())) then ent.IsP = true end if(string.find(string.lower(key),"movedir")) then if(value == "90 0 0") then ent.IsP = true end end if(key == "spawnflags") then ent.SpawnFlags = value end if(string.find(string.lower(key),"sounds")) then ent.BHS = value end if(string.find(string.lower(key),"speed")) then if(tonumber(value) > 100) then ent.IsP = true end ent.BHSp = tonumber(value) end end if(self.BaseClass.EntityKeyValue) then self.BaseClass:EntityKeyValue(ent,key,value) end end function GM:Move(pl, movedata) if(!pl or !pl:IsValid()) then return end if pl:IsOnGround() or !pl:Alive() or pl:WaterLevel() > 0 then return end local aim = movedata:GetMoveAngles() local forward, right = aim:Forward(), aim:Right() local fmove = movedata:GetForwardSpeed() local smove = movedata:GetSideSpeed() if pl:KeyDown( IN_MOVERIGHT ) then smove = (smove * 10) + 500 elseif pl:KeyDown( IN_MOVELEFT ) then smove = (smove * 10) - 500 end --this is just to ensure that lj is fine forward.z, right.z = 0,0 forward:Normalize() right:Normalize() local wishvel = forward * fmove + right * smove wishvel.z = 0 local wishspeed = wishvel:Length() if(wishspeed > movedata:GetMaxSpeed()) then wishvel = wishvel * (movedata:GetMaxSpeed()/wishspeed) wishspeed = movedata:GetMaxSpeed() end local wishspd = wishspeed wishspd = math.Clamp(wishspd, 0, 30) local wishdir = wishvel:GetNormal() local current = movedata:GetVelocity():Dot(wishdir) local addspeed = wishspd - current if(addspeed <= 0) then return end local accelspeed = (120) * wishspeed * FrameTime() if(accelspeed > addspeed) then accelspeed = addspeed end local vel = movedata:GetVelocity() vel = vel + (wishdir * accelspeed) movedata:SetVelocity(vel) if(self.BaseClass && self.BaseClass.Move) then return self.BaseClass:Move(pl, movedata) else return false end end function GM:OnPlayerHitGround(ply) -- this is my simple implementation of the jump boost, possible conditioning in future: jump height should only increase IF the player pressed jump key, any hitgrounds after the jump key should call this until finished jumping. (complex to do and unneccessary but would make certain kz maps easier in a way (and close to where they are on css)) ply:SetJumpPower(268.4) timer.Simple(0.3,function () ply:SetJumpPower(280) end) local leveldata = {} if CLIENT then leveldata = self.Levels[ply:GetNetworkedInt("ssbhop_level", 0)] else leveldata = ply.LevelData end --mpbhop stuff local ent = ply:GetGroundEntity() if(tonumber(ent:GetNWInt("Platform",0)) == 0) then return end if (ent:GetClass() == "func_door" || ent:GetClass() == "func_button") && !table.HasValue(SS.Alldoors,game.GetMap()) && ent.BHSp && ent.BHSp > 100 then ply:SetVelocity( Vector( 0, 0, ent.BHSp*1.9 ) ) elseif ent:GetClass() == "func_door" || ent:GetClass() == "func_button" then if(leveldata and leveldata.id != 1) then timer.Simple( leveldata.staytime, function() -- setting owner stops collision between two entities ent:SetOwner(ply) if(CLIENT)then ent:SetColor(Color(255,255,255,125)) --clientsided setcolor (SHOULD BE AUTORUN SHARED) end end) timer.Simple( leveldata.respawntime, function() ent:SetOwner(nil) end) timer.Simple( leveldata.respawntime, function() if(CLIENT)then ent:SetColor(Color (255,255,255,255)) end end) else ply.cblock = ent if(timer.Exists("BlockTimer")) then timer.Destroy("BlockTimer") end timer.Create("BlockTimer",0.5,1,function() if(ply && ply:IsValid() && ply.cblock && ply.cblock:IsValid() && ply:GetGroundEntity() == ply.cblock) then ply.cblock:SetOwner(ply) if(CLIENT)then ply.cblock:SetColor(Color(255,255,255,125)) --clientsided setcolor (SHOULD BE AUTORUN SHARED) end timer.Simple( 0.5, function() ent:SetOwner(nil) end) timer.Simple( 0.5, function() if(CLIENT)then ent:SetColor(Color (255,255,255,255)) end end) end end) end end if(self.BaseClass && self.BaseClass.OnPlayerHitGround) then self.BaseClass:OnPlayerHitGround(ply) end end /* Spawn Velocity Cap */ function GM:SetupMove(ply, Data) if !ply.InSpawn then return end local vel = Data:GetVelocity() vel.x = math.min(vel.x, 270) vel.y = math.min(vel.y, 270) vel.z = math.min(vel.z, 270) Data:SetVelocity(vel) return Data end
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- GM.Name = "Bunny Hop" GM.Author = "xAaron113x" GM.Email = "[email protected]" GM.Website = "aaron113.pw" GM.TeamBased = false DeriveGamemode("ssbase") DEFINE_BASECLASS("gamemode_ssbase") --for self.BaseClass GM.VIPBonusHP = false GM.HUDShowVel = true GM.HUDShowTimer = true SS.Alldoors = { "bhop_archives", "bhop_monster_jam" } TEAM_BHOP = 1 team.SetUp(TEAM_BHOP, "Hoppers", Color(87, 198, 255), false) function GM:EntityKeyValue(ent, key, value) if(ent:GetClass() == "func_door") then if(table.HasValue(SS.Alldoors,game.GetMap())) then ent.IsP = true end if(string.find(string.lower(key),"movedir")) then if(value == "90 0 0") then ent.IsP = true end end if(string.find(string.lower(key),"noise1")) then ent.BHS = value end if(string.find(string.lower(key),"speed")) then if(tonumber(value) > 100) then ent.IsP = true end ent.BHSp = tonumber(value) end end if(ent:GetClass() == "func_button") then if(table.HasValue(SS.Alldoors,game.GetMap())) then ent.IsP = true end if(string.find(string.lower(key),"movedir")) then if(value == "90 0 0") then ent.IsP = true end end if(key == "spawnflags") then ent.SpawnFlags = value end if(string.find(string.lower(key),"sounds")) then ent.BHS = value end if(string.find(string.lower(key),"speed")) then if(tonumber(value) > 100) then ent.IsP = true end ent.BHSp = tonumber(value) end end if(self.BaseClass.EntityKeyValue) then self.BaseClass:EntityKeyValue(ent,key,value) end end function GM:Move(pl, movedata) if(!pl or !pl:IsValid()) then return end if pl:IsOnGround() or !pl:Alive() or pl:WaterLevel() > 0 then return end local aim = movedata:GetMoveAngles() local forward, right = aim:Forward(), aim:Right() local fmove = movedata:GetForwardSpeed() local smove = movedata:GetSideSpeed() if pl:KeyDown( IN_MOVERIGHT ) then smove = (smove * 10) + 500 elseif pl:KeyDown( IN_MOVELEFT ) then smove = (smove * 10) - 500 end --this is just to ensure that lj is fine forward.z, right.z = 0,0 forward:Normalize() right:Normalize() local wishvel = forward * fmove + right * smove wishvel.z = 0 local wishspeed = wishvel:Length() if(wishspeed > movedata:GetMaxSpeed()) then wishvel = wishvel * (movedata:GetMaxSpeed()/wishspeed) wishspeed = movedata:GetMaxSpeed() end local wishspd = wishspeed wishspd = math.Clamp(wishspd, 0, 30) local wishdir = wishvel:GetNormal() local current = movedata:GetVelocity():Dot(wishdir) local addspeed = wishspd - current if(addspeed <= 0) then return end local accelspeed = (120) * wishspeed * FrameTime() if(accelspeed > addspeed) then accelspeed = addspeed end local vel = movedata:GetVelocity() vel = vel + (wishdir * accelspeed) movedata:SetVelocity(vel) if(self.BaseClass && self.BaseClass.Move) then return self.BaseClass:Move(pl, movedata) else return false end end function GM:OnPlayerHitGround(ply) -- this is my simple implementation of the jump boost, possible conditioning in future: jump height should only increase IF the player pressed jump key, any hitgrounds after the jump key should call this until finished jumping. (complex to do and unneccessary but would make certain kz maps easier in a way (and close to where they are on css)) ply:SetJumpPower(268.4) timer.Simple(0.3,function () ply:SetJumpPower(280) end) local leveldata = {} if CLIENT then leveldata = self.Levels[ply:GetNetworkedInt("ssbhop_level", 0)] else leveldata = ply.LevelData end --mpbhop stuff local ent = ply:GetGroundEntity() if(tonumber(ent:GetNWInt("Platform",0)) == 0) then return end if (ent:GetClass() == "func_door" || ent:GetClass() == "func_button") && !table.HasValue(SS.Alldoors,game.GetMap()) && ent.BHSp && ent.BHSp > 100 then if(game.GetMap() == "bhop_cartoony" then ply:SetVelocity( Vector( 0, 0, ent.BHSp*2.1 ) ) else ply:SetVelocity( Vector( 0, 0, ent.BHSp*1.9 ) ) end elseif ent:GetClass() == "func_door" || ent:GetClass() == "func_button" then if(leveldata and leveldata.id != 1) then timer.Simple( leveldata.staytime, function() -- setting owner stops collision between two entities ent:SetOwner(ply) if(CLIENT)then ent:SetColor(Color(255,255,255,125)) --clientsided setcolor (SHOULD BE AUTORUN SHARED) end end) timer.Simple( leveldata.respawntime, function() ent:SetOwner(nil) end) timer.Simple( leveldata.respawntime, function() if(CLIENT)then ent:SetColor(Color (255,255,255,255)) end end) else ply.cblock = ent if(timer.Exists("BlockTimer")) then timer.Destroy("BlockTimer") end timer.Create("BlockTimer",0.5,1,function() if(ply && ply:IsValid() && ply.cblock && ply.cblock:IsValid() && ply:GetGroundEntity() == ply.cblock) then ply.cblock:SetOwner(ply) if(CLIENT)then ply.cblock:SetColor(Color(255,255,255,125)) --clientsided setcolor (SHOULD BE AUTORUN SHARED) end timer.Simple( 0.5, function() ent:SetOwner(nil) end) timer.Simple( 0.5, function() if(CLIENT)then ent:SetColor(Color (255,255,255,255)) end end) end end) end end if(self.BaseClass && self.BaseClass.OnPlayerHitGround) then self.BaseClass:OnPlayerHitGround(ply) end end /* Spawn Velocity Cap */ function GM:SetupMove(ply, Data) if !ply.InSpawn then return end local vel = Data:GetVelocity() vel.x = math.min(vel.x, 270) vel.y = math.min(vel.y, 270) vel.z = math.min(vel.z, 270) Data:SetVelocity(vel) return Data end
fix 4 a map. twerk dat committ like a miley
fix 4 a map. twerk dat committ like a miley
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
83658d928d4076e431f30c830659095f100ba916
bin/batchTomo.lua
bin/batchTomo.lua
#!/usr/bin/env lua --[[===========================================================================# # This is a program to run tomoAuto in batch to align and reconstruct a large # # number of raw image stacks. # #------------------------------------------------------------------------------# # Author: Dustin Morado # # Written: March 24th 2014 # # Contact: [email protected] # #------------------------------------------------------------------------------# # Arguments: arg[1] = fiducial size in nm <integer> # #===========================================================================--]] local lfs = assert(require 'lfs') local tomoAuto = assert(require 'tomoAuto') local tomoOpt = assert(require 'tomoOpt') shortOptsString = 'cd_hn_p_' longOptsString = 'CTF, defocus, help, max, parallel' arg, Opts = tomoOpt.get(arg, shortOptsString, longOptsString) local fileTable = {} local i = 1 for file in lfs.dir('.') do if file:find('%w+%.st$') then fileTable[i] = file i = i + 1 end end local total = i - 1 local procs = Opts.n_ or 1 local thread = coroutine.create(function () for i = 1, total do runString = 'tomoAuto.lua ' if Opts.c then runString = runString .. '-c' end if Opts.d_ then runString = runString .. ' -d ' .. Opts.d_ end if Opts.p_ then runString = runString .. ' -p ' .. Opts.p_ end runString = runString .. ' ' .. fileTable .. ' ' .. arg[1] success, exit, signal = os.execute(runString) if (i % n == 0) then coroutine.yield() end end end) while coroutine.resume(thread) do print('Running on block ' .. i) end
#!/usr/bin/env lua --[[===========================================================================# # This is a program to run tomoAuto in batch to align and reconstruct a large # # number of raw image stacks. # #------------------------------------------------------------------------------# # Author: Dustin Morado # # Written: March 24th 2014 # # Contact: [email protected] # #------------------------------------------------------------------------------# # Arguments: arg[1] = fiducial size in nm <integer> # #===========================================================================--]] package.path = package.path .. ';' .. os.getenv('TOMOAUTOROOT') .. '/bin/?.lua' local lfs = assert(require 'lfs') local tomoAuto = assert(require 'tomoAuto') local tomoOpt = assert(require 'tomoOpt') shortOptsString = 'cd_hn_p_' longOptsString = 'CTF, defocus, help, max, parallel' arg, Opts = tomoOpt.get(arg, shortOptsString, longOptsString) local fileTable = {} local i = 1 for file in lfs.dir('.') do if file:find('%w+%.st$') then fileTable[i] = file i = i + 1 end end local total = i - 1 local procs = Opts.n_ or 1 local thread = coroutine.create(function () for i = 1, total do runString = 'tomoAuto.lua ' if Opts.c then runString = runString .. '-c' end if Opts.d_ then runString = runString .. ' -d ' .. Opts.d_ end if Opts.p_ then runString = runString .. ' -p ' .. Opts.p_ end runString = runString .. ' ' .. fileTable .. ' ' .. arg[1] success, exit, signal = os.execute(runString) if (i % n == 0) then coroutine.yield() end end end) while coroutine.resume(thread) do print('Running on block ' .. i) end
fixed problem with package path
fixed problem with package path
Lua
mit
DustinMorado/tomoauto
b74bc541dcb7dc50ad4541ae13602829d871412f
src/_premake_main.lua
src/_premake_main.lua
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- local shorthelp = "Type 'premake5 --help' for help" local versionhelp = "premake5 (Premake Build Script Generator) %s" -- Load the collection of core scripts, required for everything else to work local modules = dofile("_modules.lua") local manifest = dofile("_manifest.lua") for i = 1, #manifest do dofile(manifest[i]) end -- Create namespaces for myself local p = premake p.main = {} local m = p.main -- -- Script-side program entry point. -- m.elements = function() return { m.installModuleLoader, m.locateUserScript, m.prepareEnvironment, m.preloadModules, m.runSystemScript, m.prepareAction, m.runUserScript, m.checkInteractive, m.processCommandLine, m.preBake, m.bake, m.postBake, m.validate, m.preAction, m.callAction, m.postAction, } end function _premake_main() p.callArray(p.main.elements) return 0 end --- -- Add a new module loader that knows how to use the Premake paths like -- PREMAKE_PATH and the --scripts option, and follows the module/module.lua -- naming convention. --- function m.installModuleLoader() table.insert(package.loaders, 2, m.moduleLoader) end function m.moduleLoader(name) local dir = path.getdirectory(name) local base = path.getname(name) if dir ~= "." then dir = dir .. "/" .. base else dir = base end local full = dir .. "/" .. base .. ".lua" local p = os.locate("modules/" .. full) or os.locate(full) or os.locate(name .. ".lua") if not p then return "\n\tno file " .. name .. " on module paths" end local chunk, err = loadfile(p) if not chunk then error(err, 0) end return chunk end --- -- Prepare the script environment; anything that should be done -- before the system script gets a chance to run. --- function m.prepareEnvironment() math.randomseed(os.time()) _PREMAKE_DIR = path.getdirectory(_PREMAKE_COMMAND) premake.path = premake.path .. ";" .. _PREMAKE_DIR .. ";" .. _MAIN_SCRIPT_DIR end --- -- Load the required core modules that are shipped as part of Premake -- and expected to be present at startup. --- function m.preloadModules() for i = 1, #modules do local name = modules[i] local preload = name .. "/_preload.lua" local fn = os.locate("modules/" .. preload) or os.locate(preload) if fn then include(fn) else require(name) end end end --- -- Look for and run the system-wide configuration script; make sure any -- configuration scoping gets cleared before continuing. --- function m.runSystemScript() dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" }) filter {} end --- -- Look for a user project script, and set up the related global -- variables if I can find one. --- function m.locateUserScript() local defaults = { "premake5.lua", "premake4.lua" } for i = 1, #defaults do if os.isfile(defaults[i]) then _MAIN_SCRIPT = defaults[i] break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end --- -- Set the action to be performed from the command line arguments. --- function m.prepareAction() -- The "next-gen" actions have now replaced their deprecated counterparts. -- Provide a warning for a little while before I remove them entirely. if _ACTION and _ACTION:endswith("ng") then premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3)) end premake.action.set(_ACTION) end --- -- If there is a project script available, run it to get the -- project information, available options and actions, etc. --- function m.runUserScript() if os.isfile(_MAIN_SCRIPT) then dofile(_MAIN_SCRIPT) end end --- -- Run the interactive prompt, if requested. --- function m.checkInteractive() if _OPTIONS.interactive then debug.prompt() end end --- -- Validate and process the command line options and arguments. --- function m.processCommandLine() -- Process special options if (_OPTIONS["version"]) then printf(versionhelp, _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"]) then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options ok, err = premake.option.validate(_OPTIONS) if not ok then print("Error: " .. err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print(shorthelp) os.exit(1) end local action = premake.action.current() if not action then print("Error: no such action '" .. _ACTION .. "'") os.exit(1) end if p.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then print(string.format("No Premake script (%s) found!", path.getname(_MAIN_SCRIPT))) os.exit(1) end end end --- -- Override point, for logic that should run before baking. --- function m.preBake() if p.action.isConfigurable() then print("Building configurations...") end end --- -- "Bake" the project information, preparing it for use by the action. --- function m.bake() if p.action.isConfigurable() then premake.oven.bake() end end --- -- Override point, for logic that should run after baking but before -- the configurations are validated. --- function m.postBake() end --- -- Sanity check the current project setup. --- function m.validate() if p.action.isConfigurable() then p.container.validate(p.api.rootContainer()) end end --- -- Override point, for logic that should run after validation and -- before the action takes control. --- function m.preAction() local action = premake.action.current() printf("Running action '%s'...", action.trigger) end --- -- Hand over control to the action. --- function m.callAction() local action = premake.action.current() premake.action.call(action.trigger) end --- -- Processing is complete. --- function m.postAction() if p.action.isConfigurable() then print("Done.") end end
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- local shorthelp = "Type 'premake5 --help' for help" local versionhelp = "premake5 (Premake Build Script Generator) %s" -- Load the collection of core scripts, required for everything else to work local modules = dofile("_modules.lua") local manifest = dofile("_manifest.lua") for i = 1, #manifest do dofile(manifest[i]) end -- Create namespaces for myself local p = premake p.main = {} local m = p.main -- -- Script-side program entry point. -- m.elements = function() return { m.installModuleLoader, m.locateUserScript, m.prepareEnvironment, m.preloadModules, m.runSystemScript, m.prepareAction, m.runUserScript, m.checkInteractive, m.processCommandLine, m.preBake, m.bake, m.postBake, m.validate, m.preAction, m.callAction, m.postAction, } end function _premake_main() p.callArray(p.main.elements) return 0 end --- -- Add a new module loader that knows how to use the Premake paths like -- PREMAKE_PATH and the --scripts option, and follows the module/module.lua -- naming convention. --- function m.installModuleLoader() table.insert(package.loaders, 2, m.moduleLoader) end function m.moduleLoader(name) local dir = path.getdirectory(name) local base = path.getname(name) if dir ~= "." then dir = dir .. "/" .. base else dir = base end local full = dir .. "/" .. base .. ".lua" local p = os.locate("modules/" .. full) or os.locate(full) or os.locate(name .. ".lua") if not p then -- try to load from the embedded script p = "$/" .. full end local chunk, err = loadfile(p) if not chunk then error(err, 0) end return chunk end --- -- Prepare the script environment; anything that should be done -- before the system script gets a chance to run. --- function m.prepareEnvironment() math.randomseed(os.time()) _PREMAKE_DIR = path.getdirectory(_PREMAKE_COMMAND) premake.path = premake.path .. ";" .. _PREMAKE_DIR .. ";" .. _MAIN_SCRIPT_DIR end --- -- Load the required core modules that are shipped as part of Premake -- and expected to be present at startup. --- function m.preloadModules() for i = 1, #modules do local name = modules[i] local preload = name .. "/_preload.lua" local fn = os.locate("modules/" .. preload) or os.locate(preload) if fn then include(fn) else require(name) end end end --- -- Look for and run the system-wide configuration script; make sure any -- configuration scoping gets cleared before continuing. --- function m.runSystemScript() dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" }) filter {} end --- -- Look for a user project script, and set up the related global -- variables if I can find one. --- function m.locateUserScript() local defaults = { "premake5.lua", "premake4.lua" } for i = 1, #defaults do if os.isfile(defaults[i]) then _MAIN_SCRIPT = defaults[i] break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end --- -- Set the action to be performed from the command line arguments. --- function m.prepareAction() -- The "next-gen" actions have now replaced their deprecated counterparts. -- Provide a warning for a little while before I remove them entirely. if _ACTION and _ACTION:endswith("ng") then premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3)) end premake.action.set(_ACTION) end --- -- If there is a project script available, run it to get the -- project information, available options and actions, etc. --- function m.runUserScript() if os.isfile(_MAIN_SCRIPT) then dofile(_MAIN_SCRIPT) end end --- -- Run the interactive prompt, if requested. --- function m.checkInteractive() if _OPTIONS.interactive then debug.prompt() end end --- -- Validate and process the command line options and arguments. --- function m.processCommandLine() -- Process special options if (_OPTIONS["version"]) then printf(versionhelp, _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"]) then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options ok, err = premake.option.validate(_OPTIONS) if not ok then print("Error: " .. err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print(shorthelp) os.exit(1) end local action = premake.action.current() if not action then print("Error: no such action '" .. _ACTION .. "'") os.exit(1) end if p.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then print(string.format("No Premake script (%s) found!", path.getname(_MAIN_SCRIPT))) os.exit(1) end end end --- -- Override point, for logic that should run before baking. --- function m.preBake() if p.action.isConfigurable() then print("Building configurations...") end end --- -- "Bake" the project information, preparing it for use by the action. --- function m.bake() if p.action.isConfigurable() then premake.oven.bake() end end --- -- Override point, for logic that should run after baking but before -- the configurations are validated. --- function m.postBake() end --- -- Sanity check the current project setup. --- function m.validate() if p.action.isConfigurable() then p.container.validate(p.api.rootContainer()) end end --- -- Override point, for logic that should run after validation and -- before the action takes control. --- function m.preAction() local action = premake.action.current() printf("Running action '%s'...", action.trigger) end --- -- Hand over control to the action. --- function m.callAction() local action = premake.action.current() premake.action.call(action.trigger) end --- -- Processing is complete. --- function m.postAction() if p.action.isConfigurable() then print("Done.") end end
fixed issue #264
fixed issue #264
Lua
bsd-3-clause
resetnow/premake-core,LORgames/premake-core,resetnow/premake-core,PlexChat/premake-core,kankaristo/premake-core,bravnsgaard/premake-core,premake/premake-core,jstewart-amd/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,grbd/premake-core,prapin/premake-core,alarouche/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,PlexChat/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,PlexChat/premake-core,felipeprov/premake-core,tritao/premake-core,akaStiX/premake-core,mendsley/premake-core,dcourtois/premake-core,mendsley/premake-core,prapin/premake-core,Tiger66639/premake-core,saberhawk/premake-core,felipeprov/premake-core,akaStiX/premake-core,noresources/premake-core,dcourtois/premake-core,Blizzard/premake-core,saberhawk/premake-core,dcourtois/premake-core,tvandijck/premake-core,Yhgenomics/premake-core,akaStiX/premake-core,bravnsgaard/premake-core,starkos/premake-core,xriss/premake-core,starkos/premake-core,tritao/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,prapin/premake-core,martin-traverse/premake-core,Blizzard/premake-core,dcourtois/premake-core,noresources/premake-core,sleepingwit/premake-core,Yhgenomics/premake-core,starkos/premake-core,xriss/premake-core,LORgames/premake-core,LORgames/premake-core,jsfdez/premake-core,mandersan/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,premake/premake-core,noresources/premake-core,noresources/premake-core,grbd/premake-core,kankaristo/premake-core,starkos/premake-core,premake/premake-core,lizh06/premake-core,Blizzard/premake-core,tvandijck/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,LORgames/premake-core,noresources/premake-core,Meoo/premake-core,mandersan/premake-core,felipeprov/premake-core,tvandijck/premake-core,alarouche/premake-core,xriss/premake-core,bravnsgaard/premake-core,PlexChat/premake-core,noresources/premake-core,premake/premake-core,martin-traverse/premake-core,prapin/premake-core,TurkeyMan/premake-core,premake/premake-core,starkos/premake-core,premake/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,LORgames/premake-core,dcourtois/premake-core,soundsrc/premake-core,Meoo/premake-core,tvandijck/premake-core,Yhgenomics/premake-core,mandersan/premake-core,bravnsgaard/premake-core,lizh06/premake-core,TurkeyMan/premake-core,lizh06/premake-core,martin-traverse/premake-core,resetnow/premake-core,sleepingwit/premake-core,jstewart-amd/premake-core,jsfdez/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,Meoo/premake-core,Tiger66639/premake-core,dcourtois/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,starkos/premake-core,noresources/premake-core,jstewart-amd/premake-core,alarouche/premake-core,dcourtois/premake-core,xriss/premake-core,kankaristo/premake-core,mendsley/premake-core,tritao/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,Tiger66639/premake-core,saberhawk/premake-core,sleepingwit/premake-core,Meoo/premake-core,soundsrc/premake-core,jsfdez/premake-core,premake/premake-core,alarouche/premake-core,saberhawk/premake-core,starkos/premake-core,jstewart-amd/premake-core,grbd/premake-core,sleepingwit/premake-core,Yhgenomics/premake-core,Tiger66639/premake-core,jsfdez/premake-core,tritao/premake-core,resetnow/premake-core,felipeprov/premake-core,grbd/premake-core,sleepingwit/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,xriss/premake-core,kankaristo/premake-core,bravnsgaard/premake-core,akaStiX/premake-core,TurkeyMan/premake-core,mendsley/premake-core,mendsley/premake-core,resetnow/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core
4f9e25956bbb6ef308e22741fae63220d5535265
src/single-dir.lua
src/single-dir.lua
-- lua-round-up, Gather all dependencies of Lua module together -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. local function fileExists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function dirExists(name) local renamed = os.rename(name, name) return renamed end local function mkDir(dir) local parts = {} for part in dir:gmatch('([^/]+)') do table.insert(parts, part) local path = table.concat(parts, '/') if not dirExists(path) then os.execute("mkdir " .. path) end end end local function copyFile(old_path, new_path) local new_dir = new_path:match('.*/') mkDir(new_dir) local f = assert(io.open(old_path, "r")) local data = f:read('*all') f:close() local f = assert(io.open(new_path, "w")) f:write(data) f:close() end local function searchModule(name, path) name = name:gsub('%.', '/') for p in path:gmatch("([^;]+)") do local fname = p:gsub('%?', name) if fileExists(fname) then return fname, p end end end local function makeNewName(name, fname, pattern) local suffix = pattern:match('%?(.*)') return 'modules/' .. name:gsub('%.', '/') .. suffix end local function copyModule(name, path) local fname, pattern = searchModule(name, path) assert(fname, "Can't find module " .. name) local new_path = makeNewName(name, fname, pattern) copyFile(fname, new_path) end local function myLoader(original_loader, path, all_in_one) return function(name) local f = original_loader(name) if type(f) == "function" then if all_in_one then name = name:match('^([^.]+)') end copyModule(name, path) end return f end end -- package.loaders (Lua 5.1), package.searchers (Lua >= 5.2) local searchers = package.searchers or package.loaders local lua_searcher = searchers[2] local c_searcher = searchers[3] local allinone_searcher = searchers[4] searchers[2] = myLoader(lua_searcher, package.path) searchers[3] = myLoader(c_searcher, package.cpath) searchers[4] = myLoader(allinone_searcher, package.cpath, true)
-- lua-round-up, Gather all dependencies of Lua module together -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. local function fileExists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function dirExists(name) local renamed = os.rename(name, name) return renamed end local function mkDir(dir) local parts = {} for part in dir:gmatch('([^/]+)') do table.insert(parts, part) local separator = package.config:sub(1, 1) local path = table.concat(parts, separator) if not dirExists(path) then os.execute("mkdir " .. path) end end end local function copyFile(old_path, new_path) local new_dir = new_path:match('.*/') mkDir(new_dir) local f = assert(io.open(old_path, "r")) local data = f:read('*all') f:close() local f = assert(io.open(new_path, "w")) f:write(data) f:close() end local function searchModule(name, path) name = name:gsub('%.', '/') for p in path:gmatch("([^;]+)") do local fname = p:gsub('%?', name) if fileExists(fname) then return fname, p end end end local function makeNewName(name, fname, pattern) local suffix = pattern:match('%?(.*)') return 'modules/' .. name:gsub('%.', '/') .. suffix end local function copyModule(name, path) local fname, pattern = searchModule(name, path) assert(fname, "Can't find module " .. name) local new_path = makeNewName(name, fname, pattern) copyFile(fname, new_path) end local function myLoader(original_loader, path, all_in_one) return function(name) local f = original_loader(name) if type(f) == "function" then if all_in_one then name = name:match('^([^.]+)') end copyModule(name, path) end return f end end -- package.loaders (Lua 5.1), package.searchers (Lua >= 5.2) local searchers = package.searchers or package.loaders local lua_searcher = searchers[2] local c_searcher = searchers[3] local allinone_searcher = searchers[4] searchers[2] = myLoader(lua_searcher, package.path) searchers[3] = myLoader(c_searcher, package.cpath) searchers[4] = myLoader(allinone_searcher, package.cpath, true)
fix path separators for Windows
fix path separators for Windows See https://ci.appveyor.com/project/starius/single-dir-lua/build/0.0.1.7-test/job/22lhmcj4kl08ft3h#L756
Lua
mit
starius/single-dir.lua
3feb451242fcec87fbf34d9b478e97903e3a7cbb
src/lib/yang/value.lua
src/lib/yang/value.lua
-- Use of this source code is governed by the Apache 2.0 license; see -- COPYING. module(..., package.seeall) local util = require("lib.yang.util") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local ffi = require("ffi") local bit = require("bit") local ethernet = require("lib.protocol.ethernet") types = {} local function integer_type(ctype) local ret = {ctype=ctype} local min, max = ffi.new(ctype, 0), ffi.new(ctype, -1) if max < 0 then -- A signed type. Hackily rely on unsigned types having 'u' -- prefix. max = ffi.new(ctype, bit.rshift(ffi.new('u'..ctype, max), 1)) min = max - max - max - 1 end function ret.parse(str, what) return util.tointeger(str, what, min, max) end function ret.tostring(val) local str = tostring(val) if str:match("ULL") then return str:sub(1, -4) elseif str:match("LL") then return str:sub(1, -3) else return str end end return ret end types.int8 = integer_type('int8_t') types.int16 = integer_type('int16_t') types.int32 = integer_type('int32_t') types.int64 = integer_type('int64_t') types.uint8 = integer_type('uint8_t') types.uint16 = integer_type('uint16_t') types.uint32 = integer_type('uint32_t') types.uint64 = integer_type('uint64_t') local function unimplemented(type_name) local ret = {} function ret.parse(str, what) error('unimplemented '..type_name..' when parsing '..what) end function ret.tostring(val) return tostring(val) end return ret end types.binary = unimplemented('binary') types.bits = unimplemented('bits') types.boolean = {ctype='bool'} function types.boolean.parse(str, what) local str = assert(str, 'missing value for '..what) if str == 'true' then return true end if str == 'false' then return false end error('bad boolean value: '..str) end function types.boolean.tostring(val) return tostring(val) end -- FIXME: We lose precision by representing a decimal64 as a double. types.decimal64 = {ctype='double'} function types.decimal64.parse(str, what) local str = assert(str, 'missing value for '..what) return assert(tonumber(str), 'not a number: '..str) end function types.decimal64.tostring(val) -- FIXME: Make sure we are not given too many digits after the -- decimal point. return tostring(val) end types.empty = {} function types.empty.parse (str, what) return assert(str == nil, "not empty value for "..what) end function types.empty.tostring (val) return "" end types.identityref = {} function types.identityref.parse(str, what) -- References are expanded in the validation phase. return assert(str, 'missing value for '..what) end function types.identityref.tostring(val) return val end types['instance-identifier'] = unimplemented('instance-identifier') types.leafref = unimplemented('leafref') types.string = {} function types.string.parse(str, what) return assert(str, 'missing value for '..what) end function types.string.tostring(val) return val end types.enumeration = {} function types.enumeration.parse(str, what) return assert(str, 'missing value for '..what) end function types.enumeration.tostring(val) return val end types.union = unimplemented('union') types['ipv4-address'] = { ctype = 'uint32_t', parse = function(str, what) return util.ipv4_pton(str) end, tostring = function(val) return util.ipv4_ntop(val) end } types['legacy-ipv4-address'] = { ctype = 'uint8_t[4]', parse = function(str, what) return assert(ipv4:pton(str)) end, tostring = function(val) return ipv4:ntop(val) end } types['ipv6-address'] = { ctype = 'uint8_t[16]', parse = function(str, what) return assert(ipv6:pton(str)) end, tostring = function(val) return ipv6:ntop(val) end } types['mac-address'] = { ctype = 'uint8_t[6]', parse = function(str, what) return assert(ethernet:pton(str)) end, tostring = function(val) return ethernet:ntop(val) end } types['ipv4-prefix'] = { ctype = 'struct { uint8_t prefix[4]; uint8_t len; }', parse = function(str, what) local prefix, len = str:match('^([^/]+)/(.*)$') return { ipv4_pton(prefix), util.tointeger(len, 1, 32) } end, tostring = function(val) return ipv4_ntop(val[1])..'/'..tostring(val[2]) end } types['ipv6-prefix'] = { ctype = 'struct { uint8_t prefix[16]; uint8_t len; }', parse = function(str, what) local prefix, len = str:match('^([^/]+)/(.*)$') return { assert(ipv6:pton(prefix)), util.tointeger(len, 1, 128) } end, tostring = function(val) return ipv6:ntop(val[1])..'/'..tostring(val[2]) end } function selftest() assert(types['uint8'].parse('0') == 0) assert(types['uint8'].parse('255') == 255) assert(not pcall(types['uint8'].parse, '256')) assert(types['int8'].parse('-128') == -128) assert(types['int8'].parse('0') == 0) assert(types['int8'].parse('127') == 127) assert(not pcall(types['int8'].parse, '128')) end
-- Use of this source code is governed by the Apache 2.0 license; see -- COPYING. module(..., package.seeall) local util = require("lib.yang.util") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local ffi = require("ffi") local bit = require("bit") local ethernet = require("lib.protocol.ethernet") local ipv4_pton, ipv4_ntop = util.ipv4_pton, util.ipv4_ntop types = {} local function integer_type(ctype) local ret = {ctype=ctype} local min, max = ffi.new(ctype, 0), ffi.new(ctype, -1) if max < 0 then -- A signed type. Hackily rely on unsigned types having 'u' -- prefix. max = ffi.new(ctype, bit.rshift(ffi.new('u'..ctype, max), 1)) min = max - max - max - 1 end function ret.parse(str, what) return util.tointeger(str, what, min, max) end function ret.tostring(val) local str = tostring(val) if str:match("ULL") then return str:sub(1, -4) elseif str:match("LL") then return str:sub(1, -3) else return str end end return ret end types.int8 = integer_type('int8_t') types.int16 = integer_type('int16_t') types.int32 = integer_type('int32_t') types.int64 = integer_type('int64_t') types.uint8 = integer_type('uint8_t') types.uint16 = integer_type('uint16_t') types.uint32 = integer_type('uint32_t') types.uint64 = integer_type('uint64_t') local function unimplemented(type_name) local ret = {} function ret.parse(str, what) error('unimplemented '..type_name..' when parsing '..what) end function ret.tostring(val) return tostring(val) end return ret end types.binary = unimplemented('binary') types.bits = unimplemented('bits') types.boolean = {ctype='bool'} function types.boolean.parse(str, what) local str = assert(str, 'missing value for '..what) if str == 'true' then return true end if str == 'false' then return false end error('bad boolean value: '..str) end function types.boolean.tostring(val) return tostring(val) end -- FIXME: We lose precision by representing a decimal64 as a double. types.decimal64 = {ctype='double'} function types.decimal64.parse(str, what) local str = assert(str, 'missing value for '..what) return assert(tonumber(str), 'not a number: '..str) end function types.decimal64.tostring(val) -- FIXME: Make sure we are not given too many digits after the -- decimal point. return tostring(val) end types.empty = {} function types.empty.parse (str, what) return assert(str == nil, "not empty value for "..what) end function types.empty.tostring (val) return "" end types.identityref = {} function types.identityref.parse(str, what) -- References are expanded in the validation phase. return assert(str, 'missing value for '..what) end function types.identityref.tostring(val) return val end types['instance-identifier'] = unimplemented('instance-identifier') types.leafref = unimplemented('leafref') types.string = {} function types.string.parse(str, what) return assert(str, 'missing value for '..what) end function types.string.tostring(val) return val end types.enumeration = {} function types.enumeration.parse(str, what) return assert(str, 'missing value for '..what) end function types.enumeration.tostring(val) return val end types.union = unimplemented('union') types['ipv4-address'] = { ctype = 'uint32_t', parse = function(str, what) return ipv4_pton(str) end, tostring = function(val) return ipv4_ntop(val) end } types['legacy-ipv4-address'] = { ctype = 'uint8_t[4]', parse = function(str, what) return assert(ipv4:pton(str)) end, tostring = function(val) return ipv4:ntop(val) end } types['ipv6-address'] = { ctype = 'uint8_t[16]', parse = function(str, what) return assert(ipv6:pton(str)) end, tostring = function(val) return ipv6:ntop(val) end } types['mac-address'] = { ctype = 'uint8_t[6]', parse = function(str, what) return assert(ethernet:pton(str)) end, tostring = function(val) return ethernet:ntop(val) end } types['ipv4-prefix'] = { ctype = 'struct { uint8_t prefix[4]; uint8_t len; }', parse = function(str, what) local prefix, len = str:match('^([^/]+)/(.*)$') return { ipv4_pton(prefix), util.tointeger(len, nil, 1, 32) } end, tostring = function(val) return ipv4_ntop(val[1])..'/'..tostring(val[2]) end } types['ipv6-prefix'] = { ctype = 'struct { uint8_t prefix[16]; uint8_t len; }', parse = function(str, what) local prefix, len = str:match('^([^/]+)/(.*)$') return { assert(ipv6:pton(prefix)), util.tointeger(len, nil, 1, 128) } end, tostring = function(val) return ipv6:ntop(val[1])..'/'..tostring(val[2]) end } function selftest() assert(types['uint8'].parse('0') == 0) assert(types['uint8'].parse('255') == 255) assert(not pcall(types['uint8'].parse, '256')) assert(types['int8'].parse('-128') == -128) assert(types['int8'].parse('0') == 0) assert(types['int8'].parse('127') == 127) assert(not pcall(types['int8'].parse, '128')) local ip = types['ipv4-prefix'].parse('10.0.0.1/8') assert(types['ipv4-prefix'].tostring(ip) == '10.0.0.1/8') local ip = types['ipv6-prefix'].parse('fc00::1/64') assert(types['ipv6-prefix'].tostring(ip) == 'fc00::1/64') end
Fix error while parsing ipv4 and ipv6 prefix
Fix error while parsing ipv4 and ipv6 prefix
Lua
apache-2.0
snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch
3455b31dab5f0831e496f1166b91a345aa0c1346
examples/bbs/engine.lua
examples/bbs/engine.lua
local print = print local pcall = pcall local coroutine = coroutine local ui = require 'ui' module 'engine' local STATE = {} function run(conn, engine) while true do -- Get a message from the Mongrel2 server local good, request = pcall(conn.recv_json, conn) if good then local msg_type = request.data.type if msg_type == 'disconnect' then -- The client has disconnected print("disconnect", request.conn_id) STATE[request.conn_id] = nil elseif msg_type == 'msg' then -- The client has sent data local eng = STATE[request.conn_id] -- If the client hasn't sent data before, create a new engine. if not eng then eng = coroutine.create(engine) STATE[request.conn_id] = eng -- Initialize the engine with the client's connection coroutine.resume(eng, conn) end -- Pass the data on to the engine local good, error = coroutine.resume(eng, request) print("status", coroutine.status(eng)) if not good then -- There was an error print("ERROR", error) ui.exit(conn, request, 'error') elseif coroutine.status(eng) == "dead" then -- The engine has finished STATE[request.conn_id] = nil end else print("invalid message.") end print("eng", STATE[request.conn_id]) end end end
local print = print local pcall = pcall local coroutine = coroutine local ui = require 'ui' module 'engine' local STATE = {} function run(conn, engine) while true do -- Get a message from the Mongrel2 server local good, request = pcall(conn.recv_json, conn) if good then local msg_type = request.data.type if msg_type == 'disconnect' then -- The client has disconnected print("disconnect", request.conn_id) STATE[request.conn_id] = nil elseif msg_type == 'msg' then -- The client has sent data local eng = STATE[request.conn_id] -- If the client hasn't sent data before, create a new engine. if not eng then eng = coroutine.create(engine) STATE[request.conn_id] = eng -- Initialize the engine with the client's connection coroutine.resume(eng, conn) end -- Pass the data on to the engine local good, error = coroutine.resume(eng, request) print("status", coroutine.status(eng)) -- If the engine is done, stop tracking the client if coroutine.status(eng) == "dead" then STATE[request.conn_id] = nil if not good then -- There was an error print("ERROR", error) ui.exit(conn, request, 'error') end end else print("invalid message.") end print("eng", STATE[request.conn_id]) end end end
Fixed bug where the STATE entry for a connection wouldn't be cleared if an error occured.
Fixed bug where the STATE entry for a connection wouldn't be cleared if an error occured.
Lua
bsd-3-clause
ged/mongrel2,ged/mongrel2,ged/mongrel2,ged/mongrel2
4bee474c39279d9418470a12f21bc432f5e3b51f
Farming/harvest.lua
Farming/harvest.lua
local args = {...} local delay = 20 local direction -- 0 = Right, 1 = Left local minFuelLevel = 200 function checkArgs() if #args == 3 then if string.lower(args[3]) == "left" then direction = 1 elseif string.lower(args[3]) == "right" then direction = 0 end else print("Usage: <command> <x> <z> <direction>") return 1 end end function checkFuel() for i = 16,1,-1 do if turtle.getFuelLevel() > minFuelLevel then turtle.refuel() turtle.select(turtle.getSelectedSlot()+1) else break end end end function turnLeft() turtle.turnRight() turtle.forward() turtle.turnRight() end function turnRight() turtle.turnLeft() turtle.forward() turtle.turnLeft() end function doNormalTurn(x) if x % 2 == 0 then if direction == 0 then turnRight() else turnLeft() end else if direction == 0 then turnLeft() else turnRight() end end end function doFinalTurn(x) turtle.turnRight() turtle.turnRight() print("Done!") end function checkGrowth() local success, data = turtle.inspectDown() if success then if data.name == "minecraft:wheat" then if data.metadata == 7 then return 1 else --print("Not ready for harvest yet. "..data.metadata) return 0 end else --print("name: "..data.name) end else return 1 end return 0 end function isRightItem() if turtle.getItemCount() > 0 then local data = turtle.getItemDetail() if data.name == "minecraft:wheat_seeds" then return true end end return false end if checkArgs() then return end function unloadAllItems() for i = 16,1,-1 do turtle.select(i) turtle.drop() end end --checkFuel() turtle.select(1) for x=0, (args[2]-1) do for z=1, args[1] do while isRightItem() == false do if turtle.getSelectedSlot() == 16 then print("No items left.") print("Waiting "..delay.." seconds...") sleep(delay) turtle.select(1) else turtle.select(turtle.getSelectedSlot()+1) end end local growth = checkGrowth() if growth == 1 then turtle.digDown() turtle.placeDown() end if z < tonumber(args[1]) then if turtle.detect() then if not turtle.dig() then print("[error] Can't go forward.") return end end turtle.forward() end end if x < tonumber(args[2]-1) then doNormalTurn(x) else doFinalTurn(x) unloadItems() end end
local args = {...} local delay = 20 local direction -- 0 = Right, 1 = Left local minFuelLevel = 200 function checkArgs() if #args == 3 then if string.lower(args[3]) == "left" then direction = 1 elseif string.lower(args[3]) == "right" then direction = 0 end else print("Usage: <command> <x> <z> <direction>") return 1 end end function checkFuel() for i = 16,1,-1 do if turtle.getFuelLevel() > minFuelLevel then turtle.refuel() turtle.select(turtle.getSelectedSlot()+1) else break end end end function turnLeft() turtle.turnRight() turtle.forward() turtle.turnRight() end function turnRight() turtle.turnLeft() turtle.forward() turtle.turnLeft() end function doNormalTurn(x) if x % 2 == 0 then if direction == 0 then turnRight() else turnLeft() end else if direction == 0 then turnLeft() else turnRight() end end end function doFinalTurn(x) turtle.turnRight() turtle.turnRight() print("Done!") end function checkGrowth() local success, data = turtle.inspectDown() if success then if data.name == "minecraft:wheat" then if data.metadata == 7 then return 1 else --print("Not ready for harvest yet. "..data.metadata) return 0 end else --print("name: "..data.name) end else return 1 end return 0 end function isRightItem() if turtle.getItemCount() > 0 then local data = turtle.getItemDetail() if data.name == "minecraft:wheat_seeds" then return true end end return false end if checkArgs() then return end function unloadAllItems() turtle.turnLeft() for i = 16,2,-1 do turtle.select(i) turtle.drop() end turtle.turnRight() end --checkFuel() turtle.select(1) for x=0, (args[2]-1) do for z=1, args[1] do while isRightItem() == false do if turtle.getSelectedSlot() == 16 then print("No items left.") print("Waiting "..delay.." seconds...") sleep(delay) turtle.select(1) else turtle.select(turtle.getSelectedSlot()+1) end end local growth = checkGrowth() if growth == 1 then turtle.digDown() turtle.placeDown() end if z < tonumber(args[1]) then if turtle.detect() then if not turtle.dig() then print("[error] Can't go forward.") return end end turtle.forward() end end if x < tonumber(args[2]-1) then doNormalTurn(x) else doFinalTurn(x) unloadAllItems() end end
Some minor fixes for harvest.lua
Some minor fixes for harvest.lua
Lua
unlicense
Carlgo11/computercraft
40f9b44e8a2036b2f04be1a649847fd00d26775a
lua/framework/graphics/model.lua
lua/framework/graphics/model.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local assimp = require( "assimp" ) local ffi = require( "ffi" ) local bit = require( "bit" ) local GL = require( "opengl" ) class( "framework.graphics.model" ) local model = framework.graphics.model local function processMesh( self, mesh ) local stride = ( 3 + 3 + 3 + 2 ) local vertices = ffi.new( "GLfloat[?]", stride * mesh.mNumVertices ) for i = 0, mesh.mNumVertices - 1 do do vertices[stride * i + 0] = mesh.mVertices[i].x vertices[stride * i + 1] = mesh.mVertices[i].y vertices[stride * i + 2] = mesh.mVertices[i].z end if ( mesh.mNormals ~= nil ) then vertices[stride * i + 3] = mesh.mNormals[i].x vertices[stride * i + 4] = mesh.mNormals[i].y vertices[stride * i + 5] = mesh.mNormals[i].z end if ( mesh.mTangents ~= nil ) then vertices[stride * i + 6] = mesh.mTangents[i].x vertices[stride * i + 7] = mesh.mTangents[i].y vertices[stride * i + 8] = mesh.mTangents[i].z end if ( mesh.mTextureCoords[0] ~= nil ) then vertices[stride * i + 9] = mesh.mTextureCoords[0][i].x vertices[stride * i + 10] = mesh.mTextureCoords[0][i].y end end require( "framework.graphics.mesh" ) return framework.graphics.mesh( vertices, mesh.mNumVertices ) end local function processNode( self, node ) for i = 0, node.mNumMeshes - 1 do local mesh = self.scene.mMeshes[node.mMeshes[i]] table.insert( self.meshes, processMesh( self, mesh ) ) end for i = 0, node.mNumChildren - 1 do processNode( self, node.mChildren[i] ) end end function model:model( filename ) local buffer, length = framework.filesystem.read( filename ) if ( buffer == nil ) then error( length, 3 ) end self.scene = assimp.aiImportFileFromMemory( buffer, length, bit.bor( ffi.C.aiProcess_CalcTangentSpace, ffi.C.aiProcess_GenNormals, ffi.C.aiProcess_Triangulate, ffi.C.aiProcess_GenUVCoords, ffi.C.aiProcess_SortByPType ), nil ) if ( self.scene == nil ) then error( ffi.string( assimp.aiGetErrorString() ), 3 ) end self.meshes = {} processNode( self, self.scene.mRootNode ) setproxy( self ) end function model:draw( x, y, r, sx, sy, ox, oy, kx, ky ) for _, mesh in ipairs( self.meshes ) do framework.graphics.draw( mesh, x, y, r, sx, sy, ox, oy, kx, ky ) end end function model:__gc() assimp.aiReleaseImport( self.scene ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local assimp = require( "assimp" ) local ffi = require( "ffi" ) local bit = require( "bit" ) local GL = require( "opengl" ) class( "framework.graphics.model" ) local model = framework.graphics.model local function processMesh( self, mesh ) local stride = ( 3 + 3 + 3 + 2 ) local vertices = ffi.new( "GLfloat[?]", stride * mesh.mNumVertices ) for i = 0, mesh.mNumVertices - 1 do do vertices[stride * i + 0] = mesh.mVertices[i].x vertices[stride * i + 1] = mesh.mVertices[i].y vertices[stride * i + 2] = mesh.mVertices[i].z end if ( mesh.mNormals ~= nil ) then vertices[stride * i + 3] = mesh.mNormals[i].x vertices[stride * i + 4] = mesh.mNormals[i].y vertices[stride * i + 5] = mesh.mNormals[i].z end if ( mesh.mTangents ~= nil ) then vertices[stride * i + 6] = mesh.mTangents[i].x vertices[stride * i + 7] = mesh.mTangents[i].y vertices[stride * i + 8] = mesh.mTangents[i].z end if ( mesh.mTextureCoords[0] ~= nil ) then vertices[stride * i + 9] = mesh.mTextureCoords[0][i].x vertices[stride * i + 10] = mesh.mTextureCoords[0][i].y end end require( "framework.graphics.mesh" ) return framework.graphics.mesh( vertices, mesh.mNumVertices ) end local function processNode( self, node ) for i = 0, node.mNumMeshes - 1 do local mesh = self.scene.mMeshes[node.mMeshes[i]] table.insert( self.meshes, processMesh( self, mesh ) ) end for i = 0, node.mNumChildren - 1 do processNode( self, node.mChildren[i] ) end end function model:model( filename ) local buffer, length = framework.filesystem.read( filename ) if ( buffer == nil ) then error( length, 3 ) end local hint = "." .. string.match( filename, "%.([^%.]+)$" ) self.scene = assimp.aiImportFileFromMemory( buffer, length, bit.bor( ffi.C.aiProcess_CalcTangentSpace, ffi.C.aiProcess_GenNormals, ffi.C.aiProcess_Triangulate, ffi.C.aiProcess_GenUVCoords, ffi.C.aiProcess_SortByPType ), hint ) if ( self.scene == nil ) then error( ffi.string( assimp.aiGetErrorString() ), 3 ) end self.meshes = {} if ( self.scene.mRootNode ~= nil ) then processNode( self, self.scene.mRootNode ) end setproxy( self ) end function model:draw( x, y, r, sx, sy, ox, oy, kx, ky ) for _, mesh in ipairs( self.meshes ) do framework.graphics.draw( mesh, x, y, r, sx, sy, ox, oy, kx, ky ) end end function model:__gc() assimp.aiReleaseImport( self.scene ) end
Update `model` constructor
Update `model` constructor * Pass file extension hint to assimp * Fix passing NULL pointer to processNode
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
6232ad6b4e9c23d737b82f974c5e042871742cb2
Modules/Utility/os.lua
Modules/Utility/os.lua
-- to use: local os = require(this_script) -- @author Narrev -- Please message Narrev (on Roblox) for any functionality you would like added --[[ This extends the os table to include os.date! It functions just like Lua's built-in os.date, but with a few additions. Note: Padding can be toggled by inserting a '_' like so: os.date("%_x", os.time()) Note: tick() is the default unix time used for os.date() os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %s day suffix %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´ os.clock() returns how long the server has been active, or more realistically, how long since when you required this module --]] local firstRequired = os.time() return setmetatable({ date = function(optString, unix) local stringPassed = false if not (optString == nil and unix == nil) then -- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" and optString ~= "*t" then assert(optString:find("%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then -- If it is a unix time, but in a Roblox format if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end else optString, stringPassed = "%c", true end local floor, ceil = math.floor, math.ceil local overflow = function(tab, seed) for i = 1, #tab do if seed - tab[i] <= 0 then return i, seed end seed = seed - tab[i] end end local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local days, month, year = ceil(unix / 86400) + 719527 local wday = (days + 6) % 7 local _4Years = floor(days % 146097 / 1461) * 4 + floor(days / 146097) * 400 year, days = overflow({366,365,365,365}, days - 365*_4Years - floor(_4Years/4 - .25) + floor(_4Years/100 - .01) - floor(_4Years/400 - .0025)) -- [0-1461] year, _4Years = year + _4Years - 1 local yDay = days month, days = overflow({31,(year%4==0 and(year%100~=0 or year%400==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days) local hours = floor(unix / 3600 % 24) local minutes = floor(unix / 60 % 60) local seconds = floor(unix % 60) - dayAlign local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3) local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} if stringPassed then local padded = function(num) return string.format("%02d", num) end return (optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", months[month]:sub(1,3)) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%s", suffixes[days]) :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") ) end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; clock = function(...) return os.time() - firstRequired end; }, {__index = os})
-- to use: local os = require(this_script) -- @author Narrev -- Please message Narrev (on Roblox) for any functionality you would like added --[[ This extends the os table to include os.date! It functions just like Lua's built-in os.date, but with a few additions. Note: Padding can be toggled by inserting a '_' like so: os.date("%_x", os.time()) Note: tick() is the default unix time used for os.date() os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %s day suffix %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´ os.clock() returns how long the server has been active, or more realistically, how long since when you required this module --]] local firstRequired = os.time() return setmetatable({ date = function(optString, unix) local stringPassed = false if not (optString == nil and unix == nil) then -- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" and optString ~= "*t" then assert(optString:find("%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then -- If it is a unix time, but in a Roblox format if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end else optString, stringPassed = "%c", true end local floor, ceil = math.floor, math.ceil local overflow = function(tab, seed) for i = 1, #tab do if seed - tab[i] <= 0 then return i, seed end seed = seed - tab[i] end end local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local days, month, year = ceil(unix / 86400) + 719527 local wday = (days + 6) % 7 local _4Years = floor(days % 146097 % 36525 / 1461) * 4 + floor(days % 146097 / 36525) * 100 + floor(days / 146097) * 400 year, days = overflow({366,365,365,365}, days - 365*_4Years - floor(.25*_4Years - .25) + floor(.01*_4Years - .01) - floor(.0025*_4Years - .0025) ) -- [0-1461] year, _4Years = year + _4Years - 1 local yDay = days month, days = overflow({31,(year%4==0 and(year%100~=0 or year%400==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days) local hours = floor(unix / 3600 % 24) local minutes = floor(unix / 60 % 60) local seconds = floor(unix % 60) - dayAlign local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3) local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} if stringPassed then local padded = function(num) return string.format("%02d", num) end return (optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", months[month]:sub(1,3)) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%s", suffixes[days]) :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") ) end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; clock = function(...) return os.time() - firstRequired end; }, {__index = os})
Fixed calculation error
Fixed calculation error Previous algorithm wasn't working properly but it's fixed now :D
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
c1a3794f9890d54f1c649500f2f9e32d1bcf3651
layout-a5trim.lua
layout-a5trim.lua
CASILE.layout = "a5trim" local class = SILE.documentState.documentClass SILE.documentState.paperSize = SILE.paperSizeParser("135mm x 195mm") SILE.documentState.orgPaperSize = SILE.documentState.paperSize class:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = { left = "22.5mm", right = "100%pw-15mm", top = "20mm", bottom = "top(footnotes)" }, runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-8mm", bottom = "top(content)-2mm" }, footnotes = { left = "left(content)", right = "right(content)", height = "0", bottom = "100%ph-18mm" }, folio = { left = "left(content)", right = "right(content)", top = "100%ph-12mm", height = "6mm" } } }) class:mirrorMaster("right", "left") SILE.call("switch-master-one-page", { id = "right" }) if class.options.crop() == "true" then class:setupCrop() end SILE.setCommandDefaults("imprint:font", { size = "8.5pt" }) -- Hack to avoid SILE bug in print editions -- See https://github.com/simoncozens/sile/issues/355 SILE.registerCommand("href", function (options, content) SILE.process(content) end)
CASILE.layout = "a5trim" local class = SILE.documentState.documentClass SILE.documentState.paperSize = SILE.paperSizeParser("135mm x 195mm") SILE.documentState.orgPaperSize = SILE.documentState.paperSize class:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = { left = "22.5mm", right = "100%pw-15mm", top = "20mm", bottom = "top(footnotes)" }, runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-8mm", bottom = "top(content)-2mm" }, footnotes = { left = "left(content)", right = "right(content)", height = "0", bottom = "100%ph-18mm" }, folio = { left = "left(content)", right = "right(content)", top = "100%ph-12mm", height = "6mm" } } }) class:mirrorMaster("right", "left") SILE.call("switch-master-one-page", { id = "right" }) if class.options.crop() == "true" then class:setupCrop() end SILE.setCommandDefaults("imprint:font", { size = "8.5pt" }) -- Hack to avoid SILE bug in print editions -- See https://github.com/simoncozens/sile/issues/355 SILE.registerCommand("href", function (options, content) SILE.call("markverse", options, content) SILE.process(content) end)
Fix hack to mark link positios for verse index even though not linking
Fix hack to mark link positios for verse index even though not linking
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
34dc3884e7cacababba7573e1c9d8277298bed09
models/upload.lua
models/upload.lua
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req : -- @field t.file_obj : -- @field t.dest_dir : -- @field t.prefix : -- @field t.postfix : -- local function savefile(t) local req, file_obj = t.req, t.file_obj local dest_dir = (t.dest_dir and 'media/uploads/' + t.dest_dir) or 'media/uploads/' dest_dir = string.trailingPath(dest_dir) local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') --print(filename) body = file_obj.body end if not posix.stat(dest_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + dest_dir) end local newbasename, ext = calcNewFilename(filename) local newname = prefix + newbasename + postfix + ext local path = dest_dir + newname -- write file to disk local fd = io.open(path, "wb") fd:write(body) fd:close() return path, newname end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = 'User\'s upload files.'; __fields = { ['name'] = {}, ['path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.path self.size = posix.stat(t.path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local path, name = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } -- create file instance local file_instance = self { name = name, path = path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(web, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if uploading by html5 way if req.headers['x-requested-with'] then -- stored to disk local path, name = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } local file_instance = self { name = name, path = path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading by html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, oldname) return calcNewFilename(oldname) end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('mkdir -p ' + self.path) return self end; } return Upload
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req : -- @field t.file_obj : -- @field t.dest_dir : -- @field t.prefix : -- @field t.postfix : -- local function savefile(t) local req, file_obj = t.req, t.file_obj local dest_dir = (t.dest_dir and 'media/uploads/' + t.dest_dir) or 'media/uploads/' dest_dir = string.trailingPath(dest_dir) local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') --print(filename) body = file_obj.body end if isFalse(filename) or isFalse(body) then return nil, nil end if not posix.stat(dest_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + dest_dir) end local newbasename, ext = calcNewFilename(filename) local newname = prefix + newbasename + postfix + ext local path = dest_dir + newname -- write file to disk local fd = io.open(path, "wb") fd:write(body) fd:close() return path, newname end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = "User\'s upload files."; __fields = { ['name'] = {}, ['path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.path self.size = posix.stat(t.path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local path, name = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil end -- create file instance local file_instance = self { name = name, path = path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(req, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if upload in html5 way if req.headers['x-requested-with'] then -- stored to disk local path, name = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil, '[ERROR] empty file.' end local file_instance = self { name = name, path = path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading in html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if not files then return nil, '[ERROR] empty file.' end if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, oldname) return calcNewFilename(oldname) end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('mkdir -p ' + self.path) return self end; } return Upload
fix some bugs in models/upload.lua
fix some bugs in models/upload.lua Signed-off-by: Daogang Tang <[email protected]>
Lua
bsd-3-clause
daogangtang/bamboo,daogangtang/bamboo
d65d5cbee4215856c77aff5c16b82acba3ab030c
focuspoints.lrdevplugin/CanonDelegates.lua
focuspoints.lrdevplugin/CanonDelegates.lua
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ A collection of delegate functions to be passed into the DefaultPointRenderer when the camera is Canon --]] local LrStringUtils = import "LrStringUtils" require "Utils" CanonDelegates = {} --[[ -- metaData - the metadata as read by exiftool --]] function CanonDelegates.getAfPoints(photo, metaData) local imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Width", "Exif Image Width" }) local imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Height", "Exif Image Height" }) if imageWidth == nil or imageHeight == nil then return nil end local orgPhotoWidth, orgPhotoHeight = parseDimens(photo:getFormattedMetadata("dimensions")) local xScale = orgPhotoWidth / imageWidth local yScale = orgPhotoHeight / imageHeight if orgPhotoWidth < orgPhotoHeight then xScale = orgPhotoHeight / imageWidth yScale = orgPhotoWidth / imageHeight end local afPointWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Width" }) local afPointHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Height" }) local afPointWidths = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Widths" }) local afPointHeights = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Heights" }) if (afPointWidth == nil and afPointWidths == nil) or (afPointHeight == nil and afPointHeights == nil) then return nil end if afPointWidths == nil then afPointWidths = {} else afPointWidths = split(afPointWidths, " ") end if afPointHeights == nil then afPointHeights = {} else afPointHeights = split(afPointHeights, " ") end local afAreaXPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area X Positions" }) local afAreaYPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Y Positions" }) if afAreaXPositions == nil or afAreaYPositions == nil then return nil end afAreaXPositions = split(afAreaXPositions, " ") afAreaYPositions = split(afAreaYPositions, " ") local afPointsSelected = ExifUtils.findFirstMatchingValue(metaData, { "AF Points Selected", "AF Points In Focus" }) if afPointsSelected == nil then afPointsSelected = {} else afPointsSelected = split(afPointsSelected, ",") end local afPointsInFocus = ExifUtils.findFirstMatchingValue(metaData, { "AF Points In Focus" }) if afPointsInFocus == nil then afPointsInFocus = {} else afPointsInFocus = split(afPointsInFocus, ",") end local result = { pointTemplates = DefaultDelegates.pointTemplates, points = { } } for key,value in pairs(afAreaXPositions) do local x = (imageWidth/2 + afAreaXPositions[key]) * xScale local y = (imageHeight/2 + afAreaYPositions[key]) * yScale local width = 0 local height = 0 if afPointWidths[key] == nil then width = afPointWidth * xScale else width = afPointWidths[key] * xScale end if afPointHeights[key] == nil then height = afPointHeight * xScale else height = afPointHeights[key] * xScale end local pointType = DefaultDelegates.POINTTYPE_AF_INACTIVE local isInFocus = arrayKeyOf(afPointsInFocus, tostring(key - 1)) ~= nil -- 0 index based array by Canon local isSelected = arrayKeyOf(afPointsSelected, tostring(key - 1)) ~= nil if isInFocus and isSelected then pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS elseif isInFocus then pointType = DefaultDelegates.POINTTYPE_AF_INFOCUS elseif isSelected then pointType = DefaultDelegates.POINTTYPE_AF_SELECTED end if width > 0 and height > 0 then table.insert(result.points, { pointType = pointType, x = x, y = y, width = width, height = height }) end end return result end
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ A collection of delegate functions to be passed into the DefaultPointRenderer when the camera is Canon --]] local LrStringUtils = import "LrStringUtils" require "Utils" CanonDelegates = {} --[[ -- metaData - the metadata as read by exiftool --]] function CanonDelegates.getAfPoints(photo, metaData) local cameraModel = string.lower(photo:getFormattedMetadata("cameraModel")) local imageWidth local imageHeight if cameraModel == "canon eos 5d" then -- For some reason for this camera, the AF Image Width/Height has to be replaced by Canon Image Width/Height imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "Canon Image Width", "Exif Image Width" }) imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "Canon Image Height", "Exif Image Height" }) else imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Width", "Exif Image Width" }) imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Height", "Exif Image Height" }) end if imageWidth == nil or imageHeight == nil then return nil end local orgPhotoWidth, orgPhotoHeight = parseDimens(photo:getFormattedMetadata("dimensions")) local xScale = orgPhotoWidth / imageWidth local yScale = orgPhotoHeight / imageHeight if orgPhotoWidth < orgPhotoHeight then xScale = orgPhotoHeight / imageWidth yScale = orgPhotoWidth / imageHeight end local afPointWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Width" }) local afPointHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Height" }) local afPointWidths = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Widths" }) local afPointHeights = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Heights" }) if (afPointWidth == nil and afPointWidths == nil) or (afPointHeight == nil and afPointHeights == nil) then return nil end if afPointWidths == nil then afPointWidths = {} else afPointWidths = split(afPointWidths, " ") end if afPointHeights == nil then afPointHeights = {} else afPointHeights = split(afPointHeights, " ") end local afAreaXPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area X Positions" }) local afAreaYPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Y Positions" }) if afAreaXPositions == nil or afAreaYPositions == nil then return nil end afAreaXPositions = split(afAreaXPositions, " ") afAreaYPositions = split(afAreaYPositions, " ") local afPointsSelected = ExifUtils.findFirstMatchingValue(metaData, { "AF Points Selected", "AF Points In Focus" }) if afPointsSelected == nil then afPointsSelected = {} else afPointsSelected = split(afPointsSelected, ",") end local afPointsInFocus = ExifUtils.findFirstMatchingValue(metaData, { "AF Points In Focus" }) if afPointsInFocus == nil then afPointsInFocus = {} else afPointsInFocus = split(afPointsInFocus, ",") end local result = { pointTemplates = DefaultDelegates.pointTemplates, points = { } } for key,value in pairs(afAreaXPositions) do local x = (imageWidth/2 + afAreaXPositions[key]) * xScale -- On Canon, everithing is referenced from the center, local y = (imageHeight/2 - afAreaYPositions[key]) * yScale -- X positive toward the right and Y positive toward the TOP local width = 0 local height = 0 if afPointWidths[key] == nil then width = afPointWidth * xScale else width = afPointWidths[key] * xScale end if afPointHeights[key] == nil then height = afPointHeight * xScale else height = afPointHeights[key] * xScale end local pointType = DefaultDelegates.POINTTYPE_AF_INACTIVE local isInFocus = arrayKeyOf(afPointsInFocus, tostring(key - 1)) ~= nil -- 0 index based array by Canon local isSelected = arrayKeyOf(afPointsSelected, tostring(key - 1)) ~= nil if isInFocus and isSelected then pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS elseif isInFocus then pointType = DefaultDelegates.POINTTYPE_AF_INFOCUS elseif isSelected then pointType = DefaultDelegates.POINTTYPE_AF_SELECTED end if width > 0 and height > 0 then table.insert(result.points, { pointType = pointType, x = x, y = y, width = width, height = height }) end end return result end
Corrected to direction on the Y axis for Canon cameras Fixed a special case for Canon EOS 5D
Corrected to direction on the Y axis for Canon cameras Fixed a special case for Canon EOS 5D
Lua
apache-2.0
philmoz/Focus-Points,philmoz/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,rderimay/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,project802/Focus-Points,mkjanke/Focus-Points,mkjanke/Focus-Points,project802/Focus-Points,rderimay/Focus-Points
a5c4754cfae6afa08440b960785233fd144e9af4
examples/remove_by_id.lua
examples/remove_by_id.lua
#!/usr/bin/env lua local gumbo = require "gumbo" local serialize = require "gumbo.serialize.html" --- Iterate an element node recursively and remove any descendant element --- with the specified id attribute. local function remove_element_by_id(base, id) local function search_and_remove(node, n) if node[n].type == "element" then if node[n].attr and node[n].attr.id == id then table.remove(node, n) else -- This loop must use ipairs, to allow using table.remove for i in ipairs(node[n]) do search_and_remove(node[n], i) end end end end if base and base.type == "element" or base.type == "document" then for i = 1, #base do search_and_remove(base, i) end end end local filename = assert(arg[1], "No filename specified") local id = assert(arg[2], "No ID specified") local document = assert(gumbo.parse_file(filename)) remove_element_by_id(document, id) io.stdout:write(serialize(document))
#!/usr/bin/env lua local gumbo = require "gumbo" local serialize = require "gumbo.serialize.html" --- Iterate an element node recursively and remove any descendant element --- with the specified id attribute. local function remove_element_by_id(base, id) local function search_and_remove(node, n) if node[n].type == "element" then if node[n].attr and node[n].attr.id == id then table.remove(node, n) else -- This loop must use ipairs, to allow using table.remove for i in ipairs(node[n]) do search_and_remove(node[n], i) end end end end if base and base.type == "element" or base.type == "document" then for i = 1, #base do search_and_remove(base, i) end end end if not arg[1] then io.stderr:write("Error: No element ID specified\n") io.stderr:write("Usage: ", arg[0], " ELEMENT_ID [FILENAME]\n") os.exit(1) end local document = assert(gumbo.parse_file(arg[2] or io.stdin)) remove_element_by_id(document, arg[1]) io.stdout:write(serialize(document))
Fix argument checking in examples/remove_by_id.lua
Fix argument checking in examples/remove_by_id.lua
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
9781fa18186223e864722bb4de755d5940a22ffa
lua/filetypes/cmake.lua
lua/filetypes/cmake.lua
local executable = require'utils'.files.executable local mkdir = require'utils'.files.mkdir local is_dir = require'utils'.files.is_dir local is_file = require'utils'.files.is_file local link = require'utils'.files.link local set_command = require'neovim.commands'.set_command local jobs = require'jobs' local echomsg = require'utils.messages'.echomsg local echoerr = require'utils.messages'.echoerr local M = {} function M.setup() set_command{ lhs = 'CMake', rhs = function(args) args = args or '' local cmd = {'cmake'} vim.list_extend(cmd, vim.split(args, ' ')) jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, } end, args = {nargs = '+', force = true, buffer = true} } set_command{ lhs = 'CMakeConfig', rhs = function(build_type) -- Release, Debug, RelWithDebInfo, etc. build_type = (build_type and build_type ~= '') and build_type or 'RelWithDebInfo' local build_dir = 'build' if not is_dir(build_dir) then mkdir(build_dir) end local cmd = { 'cmake', '.', '-DCMAKE_BUILD_TYPE='..build_type, '-B'..build_dir, } local c_compiler local cpp_compiler if vim.env.CC then c_compiler = {'-DCMAKE_C_COMPILER='..vim.env.CC} elseif vim.g.c_compiler then c_compiler = {'-DCMAKE_C_COMPILER='..vim.g.c_compiler} end if vim.env.CXX then c_compiler = '-DCMAKE_CXX_COMPILER='..vim.env.CXX elseif vim.g.c_compiler then c_compiler = '-DCMAKE_CXX_COMPILER='..vim.g.cpp_compiler end if c_compiler then table.insert(cmd, c_compiler) end if cpp_compiler then table.insert(cmd, cpp_compiler) end jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, } end, args = {nargs = '?', force = true, buffer = true, complete = 'customlist,neovim#cmake_build'} } set_command{ lhs = 'CMakeBuild', rhs = function(build_type) -- Release, Debug, RelWithDebInfo, etc. build_type = (build_type and build_type ~= '') and build_type or 'RelWithDebInfo' local build_dir = 'build' if not is_dir(build_dir) then mkdir(build_dir) end local cmd = { 'cmake', '--build', build_dir, '--config', build_type, } jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, opts = { on_exit = function(jobid, rc, _) local job = STORAGE.jobs[jobid] if rc == 0 then echomsg('Build complete!') if is_file('build/compile_commands.json') then link( 'build/compile_commands.json', '.', false, true ) end vim.fn.setloclist(lint_win, {}, 'r') else echoerr('Build Failed! :c ') local streams = job.streams or {} local stdout = streams.stdout or {} local stderr = streams.stderr or {} if #stdout > 0 or #stderr > 0 then local lines if #streams.stderr > 0 then lines = streams.stderr else lines = streams.stdout end local qf_opts = job.qf or {} qf_opts.lines = lines require'utils'.helpers.dump_to_qf(qf_opts) end end end }, } end, args = {nargs = '?', force = true, buffer = true, complete = 'customlist,neovim#cmake_build'} } -- if executable('ccmake') then -- end end return M
local executable = require'utils'.files.executable local mkdir = require'utils'.files.mkdir local is_dir = require'utils'.files.is_dir local is_file = require'utils'.files.is_file local link = require'utils'.files.link local set_command = require'neovim.commands'.set_command local jobs = require'jobs' local echomsg = require'utils.messages'.echomsg local echoerr = require'utils.messages'.echoerr local M = {} function M.setup() set_command{ lhs = 'CMake', rhs = function(args) args = args or '' local cmd = {'cmake'} vim.list_extend(cmd, vim.split(args, ' ')) jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, } end, args = {nargs = '+', force = true, buffer = true} } set_command{ lhs = 'CMakeConfig', rhs = function(build_type) -- Release, Debug, RelWithDebInfo, etc. build_type = (build_type and build_type ~= '') and build_type or 'RelWithDebInfo' local build_dir = 'build' if not is_dir(build_dir) then mkdir(build_dir) end local cmd = { 'cmake', '.', '-DCMAKE_BUILD_TYPE='..build_type, '-B'..build_dir, } local c_compiler local cpp_compiler if vim.env.CC then c_compiler = {'-DCMAKE_C_COMPILER='..vim.env.CC} elseif vim.g.c_compiler then c_compiler = {'-DCMAKE_C_COMPILER='..vim.g.c_compiler} end if vim.env.CXX then c_compiler = '-DCMAKE_CXX_COMPILER='..vim.env.CXX elseif vim.g.c_compiler then c_compiler = '-DCMAKE_CXX_COMPILER='..vim.g.cpp_compiler end if c_compiler then table.insert(cmd, c_compiler) end if cpp_compiler then table.insert(cmd, cpp_compiler) end jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, } end, args = {nargs = '?', force = true, buffer = true, complete = 'customlist,neovim#cmake_build'} } set_command{ lhs = 'CMakeBuild', rhs = function(build_type) -- Release, Debug, RelWithDebInfo, etc. build_type = (build_type and build_type ~= '') and build_type or 'RelWithDebInfo' local build_dir = 'build' if not is_dir(build_dir) then mkdir(build_dir) end local cmd = { 'cmake', '--build', build_dir, '--config', build_type, } jobs.send_job{ cmd = cmd, qf = { on_fail = { open = true, jump = false, }, open = false, jump = false, context = 'CMake', title = 'CMake', }, opts = { on_exit = function(jobid, rc, _) local job = STORAGE.jobs[jobid] if rc == 0 then echomsg('Build complete!') if is_file('build/compile_commands.json') then link( 'build/compile_commands.json', '.', false, true ) end vim.fn.setloclist(lint_win, {}, 'r') else echoerr('Build Failed! :c ') local streams = job.streams or {} local stdout = streams.stdout or {} local stderr = streams.stderr or {} if #stdout > 0 or #stderr > 0 then local lines if #streams.stderr > 0 then lines = streams.stderr else lines = streams.stdout end local qf_opts = job.qf or {} qf_opts.lines = lines if qf_opts.on_fail then if qf_opts.on_fail.open then qf_opts.open = rc ~= 0 end if qf_opts.on_fail.jump then qf_opts.jump = rc ~= 0 end end require'utils'.helpers.dump_to_qf(qf_opts) end end end }, } end, args = {nargs = '?', force = true, buffer = true, complete = 'customlist,neovim#cmake_build'} } end return M
fix: open qf on failed cmake build
fix: open qf on failed cmake build
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
a2cd0d992775fe39fc98a6c1a3ca867d407ba68c
scheduled/factionLeader.lua
scheduled/factionLeader.lua
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight require("base.common") module("scheduled.factionLeader", package.seeall) function checkFactionLeader() players=world:getPlayersOnline() for player in players do if player.name == "Rosaline Edwards" then npcPositions = {position(122, 521, 0), position(237, 104, 0)}; if world:isCharacterOnField(npcPositions[1]) == true then npcCharObject = world:getCharacterOnField(npcPositions[1]); npcCharObject:forceWarp(npcPositions[2]); end elseif player.name == "Valerio Guilianni" then npcPositions = {position(337, 215, 0), position(238, 104, 0)}; if world:isCharacterOnField(npcPositions[1]) == true then npcCharObject = world:getCharacterOnField(npcPositions[1]); npcCharObject:forceWarp(npcPositions[2]); end elseif player.name == "Elvaine Morgan" then npcPositions = {position(898, 775, 2), position(239, 104, 0)}; if world:isCharacterOnField(npcPositions[1]) == true then npcCharObject = world:getCharacterOnField(npcPositions[1]); npcCharObject:forceWarp(npcPositions[2]); end end end end
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight require("base.common") module("scheduled.factionLeader", package.seeall) function checkFactionLeader() players=world:getPlayersOnline() for index, playerName in pairs(players) do if playerName == "Rosaline Edwards" then npcPositions = {position(122, 521, 0), position(237, 104, 0)}; updatePosition(npcPositions) elseif playerName == "Valerio Guilianni" then npcPositions = {position(337, 215, 0), position(238, 104, 0)}; u pdatePosition(npcPositions) elseif playerName == "Elvaine Morgan" then npcPositions = {position(898, 775, 2), position(239, 104, 0)}; updatePosition(npcPositions) end end end function updatePosition(npcPositions) if world:isCharacterOnField(npcPositions[1]) == true then npcCharObject = world:getCharacterOnField(npcPositions[1]); npcCharObject:forceWarp(npcPositions[2]); end end
fixed for loop
fixed for loop
Lua
agpl-3.0
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
f7bd7cfc3ab55650aab50d7885d00798cabe8497
api/server.lua
api/server.lua
local htmlparser = require("htmlparser") local http = require('socket.http') local app = require('waffle').CmdLine() local search = function(req, res) local query = req.url.args.zoektermen local queryType = tonumber(req.url.args.opZoeken) local queryPage = tonumber(req.url.args.page) or 0 local queryEan = "" if query == nil then res.send("Error") end -- Ean query if queryType == 1 then queryEan = query query = "" end local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage} if queryPage < 1 then url[1] = 'http://livaad.nl/database/' end local body, c, l, h = http.request(table.concat(url, "")) local root = htmlparser.parse(body) if queryPage < 1 then local dataContainer = root:select("#data-container") if #dataContainer>=1 then root = htmlparser.parse(dataContainer[1]:getcontent()) else res.send("Error") end end local products = root:select(".panel") local results = {} -- Get all products for i=1,#products do local header = products[i](".panel-heading") if #header >= 1 then local brand, name = unpack(header[1]:select('div')) brand = brand:getcontent() name, c = string.gsub(name:getcontent(), '<(.*)>', "") local rows = products[i]('.row') local attributes = {} for i=1,#rows do local k, v = unpack(rows[i]('div')) attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent() end local bsm = "" -- By default TODO local source = "" -- By default TODO -- 1 is free, 2 is contains local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij") starch = starch > 0 and 1 or 2 local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij") lactose = lactose > 0 and 1 or 2 local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", ""):gsub("-201", "") -- TODO: Fix in app results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source} end end res.json({api_version=0.2, results=results}) end app.get('/search.php', search) app.get('/glutenvrij/search.php', search) -- 127.0.0.1 app.listen()
local htmlparser = require("htmlparser") local http = require('socket.http') local json = require('json') local app = require('waffle').CmdLine() local search = function(req, res) local query = req.url.args.zoektermen local queryType = tonumber(req.url.args.opZoeken) local queryPage = tonumber(req.url.args.page) or 0 local queryEan = "" if query == nil then res.send("Error") end -- Ean query if queryType == 1 then queryEan = query query = "" end local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage} if queryPage < 1 then url[1] = 'http://livaad.nl/database/' end local body, c, l, h = http.request(table.concat(url, "")) local root = htmlparser.parse(body) if queryPage < 1 then local dataContainer = root:select("#data-container") if #dataContainer>=1 then root = htmlparser.parse(dataContainer[1]:getcontent()) else res.send("Error") end end local products = root:select(".panel") local results = {} -- Get all products for i=1,#products do local header = products[i](".panel-heading") if #header >= 1 then local brand, name = unpack(header[1]:select('div')) brand = brand:getcontent() name, c = string.gsub(name:getcontent(), '<(.*)>', "") local rows = products[i]('.row') local attributes = {} for i=1,#rows do local k, v = unpack(rows[i]('div')) attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent() end local bsm = "" -- By default TODO local source = "" -- By default TODO -- 1 is free, 2 is contains local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij") starch = starch > 0 and 1 or 2 local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij") lactose = lactose > 0 and 1 or 2 local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", ""):gsub("-201", "") -- TODO: Fix in app results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source} end end res.header('Content-Type', 'application/x-json') res.send(json.encode{api_version=0.2, results=results}) end app.get('/search.php', search) app.get('/glutenvrij/search.php', search) -- 127.0.0.1 app.listen()
Fix contenttype for app
Fix contenttype for app App checks the contenttype
Lua
mit
JoostvDoorn/GlutenVrijApp
a3e401dbded84b2a90472024daa28ff51b2c00d3
combine-cdefdbs.lua
combine-cdefdbs.lua
-- Copyright (C) 2014-2015 Brian Downing. MIT License. local ffi = require 'ffi' local cdef, C, ffi_string = ffi.cdef, ffi.C, ffi.string local dbg = function () end -- dbg = print local cdefdb_open = require 'cdefdb.open' local cdefdb_write = require 'cdefdb.write' local db_names = {...} local outfile = table.remove(db_names, 1) assert(outfile) local dbs = { } for _, name in ipairs(db_names) do dbs[name] = cdefdb_open(name) end table.sort(db_names, function (a, b) if dbs[a].header.priority == dbs[b].header.priority then return dbs[a].size > dbs[b].size end return dbs[a].header.priority > dbs[b].header.priority end) local function get_string(db, offset) return ffi_string(db.strings + offset) end local stmt_idx = 1 local stmts = { } local constants = { } local function get_tag(db, stmt_idx) local db_stmt = db.stmts[stmt_idx] local name = get_string(db, db_stmt.name) local kind = get_string(db, db_stmt.kind) return kind..','..name end for _, db_name in ipairs(db_names) do local db = dbs[db_name] for i = 0, db.header.num_stmts - 1 do local db_stmt = db.stmts[i] local stmt = { name = get_string(db, db_stmt.name), kind = get_string(db, db_stmt.kind), extent = get_string(db, db_stmt.extent), file = get_string(db, db_stmt.file), tag = get_tag(db, i), idx = stmt_idx, deps = { }, delayed_deps = { }, db_name = db_name } for _, dep_type in ipairs{'deps', 'delayed_deps'} do local deps = { } local d = db_stmt[dep_type] while db.stmt_deps[d] ~= -1 do stmt[dep_type][get_tag(db, db.stmt_deps[d])] = true d = d + 1 end end if not stmts[stmt.tag] or stmts[stmt.tag].db_name == db_name then -- print('name', stmt.name) -- print('kind', stmt.kind) -- print('extent', stmt.extent) -- print('file', stmt.file) -- print('db_name', stmt.db_name) -- print('deps', db_stmt.deps) -- for dep, _ in pairs(stmt.deps) do -- print('', dep) -- end -- print('delayed_deps', db_stmt.delayed_deps) -- for dep, _ in pairs(stmt.delayed_deps) do -- print('', dep) -- end if stmts[stmt.tag] and stmts[stmt.tag].db_name == db_name then stmt.idx = stmts[stmt.tag].idx else stmt_idx = stmt_idx + 1 end stmts[stmt.tag] = stmt end end for i = 0, db.header.num_constants - 1 do local name = get_string(db, db.constants_idx[i].name) if not constants[name] then constants[name] = stmts[get_tag(db, db.constants_idx[i].stmt)] end end end local f = assert(io.open(outfile, 'w')) cdefdb_write(f, stmts, constants) f:close()
-- Copyright (C) 2014-2015 Brian Downing. MIT License. local ffi = require 'ffi' local cdef, C, ffi_string = ffi.cdef, ffi.C, ffi.string local dbg = function () end -- dbg = print local cdefdb_open = require 'cdefdb.open' local cdefdb_write = require 'cdefdb.write' local db_names = {...} local outfile = table.remove(db_names, 1) assert(outfile) local dbs = { } for _, name in ipairs(db_names) do dbs[name] = cdefdb_open(name) end table.sort(db_names, function (a, b) if dbs[a].header.priority == dbs[b].header.priority then return dbs[a].size > dbs[b].size end return dbs[a].header.priority > dbs[b].header.priority end) local function get_string(db, offset) return ffi_string(db.strings + offset) end local stmt_idx = 1 local stmts = { } local constants = { } local function get_tag(db, stmt_idx) local db_stmt = db.stmts[stmt_idx] local name = get_string(db, db_stmt.name) local kind = get_string(db, db_stmt.kind) if name == '' then name = get_string(db, db_stmt.extent):gsub('%s*', '') end return kind..','..name end for _, db_name in ipairs(db_names) do local db = dbs[db_name] for i = 0, db.header.num_stmts - 1 do local db_stmt = db.stmts[i] local stmt = { name = get_string(db, db_stmt.name), kind = get_string(db, db_stmt.kind), extent = get_string(db, db_stmt.extent), file = get_string(db, db_stmt.file), tag = get_tag(db, i), idx = stmt_idx, deps = { }, delayed_deps = { }, db_name = db_name } for _, dep_type in ipairs{'deps', 'delayed_deps'} do local deps = { } local d = db_stmt[dep_type] while db.stmt_deps[d] ~= -1 do stmt[dep_type][get_tag(db, db.stmt_deps[d])] = true d = d + 1 end end if not stmts[stmt.tag] or stmts[stmt.tag].db_name == db_name then -- print('name', stmt.name) -- print('kind', stmt.kind) -- print('extent', stmt.extent) -- print('file', stmt.file) -- print('db_name', stmt.db_name) -- print('deps', db_stmt.deps) -- for dep, _ in pairs(stmt.deps) do -- print('', dep) -- end -- print('delayed_deps', db_stmt.delayed_deps) -- for dep, _ in pairs(stmt.delayed_deps) do -- print('', dep) -- end if stmts[stmt.tag] and stmts[stmt.tag].db_name == db_name then stmt.idx = stmts[stmt.tag].idx else stmt_idx = stmt_idx + 1 end stmts[stmt.tag] = stmt end end for i = 0, db.header.num_constants - 1 do local name = get_string(db, db.constants_idx[i].name) if not constants[name] then constants[name] = stmts[get_tag(db, db.constants_idx[i].stmt)] end end end local f = assert(io.open(outfile, 'w')) cdefdb_write(f, stmts, constants) f:close()
Add kludgey fix for combining anonymous enums
Add kludgey fix for combining anonymous enums Seems a bit fragile, but I don't have a better idea right now...
Lua
mit
bdowning/lj-cdefdb,bdowning/lj-cdefdb
0096758edb617c5ba874a400ccfa37a9317950bb
MMOCoreORB/bin/scripts/screenplays/tasks/yavin4/ruwan_tokai.lua
MMOCoreORB/bin/scripts/screenplays/tasks/yavin4/ruwan_tokai.lua
ruwan_tokai_missions = { { missionType = "retrieve", primarySpawns = { { npcTemplate = "ruwan_warrant_officer", npcName = "" } }, secondarySpawns = { { npcTemplate = "ruwan_thug", npcName = "" }, { npcTemplate = "ruwan_thug", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/ruwan_tokai_q1_needed.iff", itemName = "Death Star Fragment" } }, rewards = { { rewardType = "credits", amount = 40 }, { rewardType = "faction", faction = "imperial", amount = 10 }, } }, { missionType = "retrieve", primarySpawns = { { npcTemplate = "ruwan_lieutenant_colonel", npcName = "" } }, secondarySpawns = { { npcTemplate = "rebel_first_lieutenant", npcName = "" }, { npcTemplate = "rebel_commando", npcName = "" }, { npcTemplate = "rebel_commando", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/ruwan_tokai_q2_needed.iff", itemName = "Tokai Authorization" } }, rewards = { { rewardType = "credits", amount = 50 }, { rewardType = "faction", faction = "imperial", amount = 10 }, } } } npcMapRuwanTokai = { { spawnData = { npcTemplate = "ruwan_tokai", x = -11.7, z = 2.0, y = 71.1, direction = -179, cellID = 3465355, position = STAND }, worldPosition = { x = -3108, y = -2976 }, npcNumber = 1, stfFile = "@static_npc/yavin/yavin_massassi_ruwan_tokai", missions = ruwan_tokai_missions }, } RuwanTokai = ThemeParkLogic:new { npcMap = npcMapRuwanTokai, className = "RuwanTokai", screenPlayState = "ruwan_tokai_quest", planetName = "yavin4", distance = 500, faction = FACTIONIMPERIAL } registerScreenPlay("RuwanTokai", true) ruwan_tokai_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = RuwanTokai } ruwan_tokai_mission_target_conv_handler = mission_target_conv_handler:new { themePark = RuwanTokai }
ruwan_tokai_missions = { { missionType = "deliver", primarySpawns = { { npcTemplate = "ruwan_warrant_officer", npcName = "" } }, secondarySpawns = { { npcTemplate = "ruwan_thug", npcName = "" }, { npcTemplate = "ruwan_thug", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/ruwan_tokai_q1_needed.iff", itemName = "" } }, rewards = { { rewardType = "credits", amount = 40 }, { rewardType = "faction", faction = "imperial", amount = 10 }, } }, { missionType = "retrieve", primarySpawns = { { npcTemplate = "ruwan_lieutenant_colonel", npcName = "" } }, secondarySpawns = { { npcTemplate = "rebel_first_lieutenant", npcName = "" }, { npcTemplate = "rebel_commando", npcName = "" }, { npcTemplate = "rebel_commando", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/ruwan_tokai_q2_needed.iff", itemName = "" } }, rewards = { { rewardType = "credits", amount = 50 }, { rewardType = "faction", faction = "imperial", amount = 10 }, } } } npcMapRuwanTokai = { { spawnData = { npcTemplate = "ruwan_tokai", x = -11.7, z = 2.0, y = 71.1, direction = -179, cellID = 3465355, position = STAND }, worldPosition = { x = -3108, y = -2976 }, npcNumber = 1, stfFile = "@static_npc/yavin/yavin_massassi_ruwan_tokai", missions = ruwan_tokai_missions }, } RuwanTokai = ThemeParkLogic:new { npcMap = npcMapRuwanTokai, className = "RuwanTokai", screenPlayState = "ruwan_tokai_quest", planetName = "yavin4", distance = 500, faction = FACTIONIMPERIAL } registerScreenPlay("RuwanTokai", true) ruwan_tokai_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = RuwanTokai } ruwan_tokai_mission_target_conv_handler = mission_target_conv_handler:new { themePark = RuwanTokai }
[Fixed] mission type on ruwan tokai's first mission
[Fixed] mission type on ruwan tokai's first mission Change-Id: Iafae5a13fa047e582a188e156946dd47241bd505
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
50379982c099455bf6306f3c37d8a821e7b242b6
lib/luajit/ffi.meta.lua
lib/luajit/ffi.meta.lua
local ffi = require 'ffi' return { ["C"] = { tag = "var", contents = "require('ffi').C", value = ffi.C, }, ["abi"] = { tag = "var", contents = "require('ffi').abi", value = ffi.abi, }, ["alignof"] = { tag = "var", contents = "require('ffi').alignof", value = ffi.alignof, }, ["arch"] = { tag = "var", contents = "require('ffi').arch", value = ffi.arch, }, ["cast"] = { tag = "var", contents = "require('ffi').cast", value = ffi.cast, }, ["cdef"] = { tag = "var", contents = "require('ffi').cdef", value = ffi.cdef, }, ["copy"] = { tag = "var", contents = "require('ffi').copy", value = ffi.copy, }, ["errno"] = { tag = "var", contents = "require('ffi').errno", value = ffi.errno, }, ["fill"] = { tag = "var", contents = "require('ffi').fill", value = ffi.fill, }, ["gc"] = { tag = "var", contents = "require('ffi').gc", value = ffi.gc, }, ["istype"] = { tag = "var", contents = "require('ffi').istype", value = ffi.istype, }, ["load"] = { tag = "var", contents = "require('ffi').load", value = ffi.load, }, ["metatype"] = { tag = "var", contents = "require('ffi').metatype", value = ffi.metatype, }, ["new"] = { tag = "var", contents = "require('ffi').new", value = ffi.new, }, ["offsetof"] = { tag = "var", contents = "require('ffi').offsetof", value = ffi.offsetof, }, ["os"] = { tag = "var", contents = "require('ffi').os", value = ffi.os, }, ["sizeof"] = { tag = "var", contents = "require('ffi').sizeof", value = ffi.sizeof, }, ["string"] = { tag = "var", contents = "require('ffi').string", value = ffi.string, }, ["typeinfo"] = { tag = "var", contents = "require('ffi').typeinfo", value = ffi.typeinfo, }, ["typeof"] = { tag = "var", contents = "require('ffi').typeof", value = ffi.typeof, }, }
local ok, ffi = pcall(require, 'ffi') if not ok then ffi = {} end return { ["C"] = { tag = "var", contents = "require('ffi').C", value = ffi.C, }, ["abi"] = { tag = "var", contents = "require('ffi').abi", value = ffi.abi, }, ["alignof"] = { tag = "var", contents = "require('ffi').alignof", value = ffi.alignof, }, ["arch"] = { tag = "var", contents = "require('ffi').arch", value = ffi.arch, }, ["cast"] = { tag = "var", contents = "require('ffi').cast", value = ffi.cast, }, ["cdef"] = { tag = "var", contents = "require('ffi').cdef", value = ffi.cdef, }, ["copy"] = { tag = "var", contents = "require('ffi').copy", value = ffi.copy, }, ["errno"] = { tag = "var", contents = "require('ffi').errno", value = ffi.errno, }, ["fill"] = { tag = "var", contents = "require('ffi').fill", value = ffi.fill, }, ["gc"] = { tag = "var", contents = "require('ffi').gc", value = ffi.gc, }, ["istype"] = { tag = "var", contents = "require('ffi').istype", value = ffi.istype, }, ["load"] = { tag = "var", contents = "require('ffi').load", value = ffi.load, }, ["metatype"] = { tag = "var", contents = "require('ffi').metatype", value = ffi.metatype, }, ["new"] = { tag = "var", contents = "require('ffi').new", value = ffi.new, }, ["offsetof"] = { tag = "var", contents = "require('ffi').offsetof", value = ffi.offsetof, }, ["os"] = { tag = "var", contents = "require('ffi').os", value = ffi.os, }, ["sizeof"] = { tag = "var", contents = "require('ffi').sizeof", value = ffi.sizeof, }, ["string"] = { tag = "var", contents = "require('ffi').string", value = ffi.string, }, ["typeinfo"] = { tag = "var", contents = "require('ffi').typeinfo", value = ffi.typeinfo, }, ["typeof"] = { tag = "var", contents = "require('ffi').typeof", value = ffi.typeof, }, }
Fix build failing without LuaJIT
Fix build failing without LuaJIT
Lua
bsd-3-clause
SquidDev/urn,SquidDev/urn
3394eba0d4fc9b84bd1f9e8f5d6105cbaca2f996
plugins/muc/mod_muc.lua
plugins/muc/mod_muc.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. -- if module:get_host_type() ~= "component" then error("MUC should be loaded as a component, please see http://prosody.im/doc/components", 0); end local muc_host = module:get_host(); local muc_name = "Chatrooms"; local history_length = 20; local muc_new_room = module:require "muc".new_room; local register_component = require "core.componentmanager".register_component; local deregister_component = require "core.componentmanager".deregister_component; local jid_split = require "util.jid".split; local st = require "util.stanza"; local uuid_gen = require "util.uuid".generate; local datamanager = require "util.datamanager"; local rooms = {}; local persistent_rooms = datamanager.load(nil, muc_host, "persistent") or {}; local component; local function room_route_stanza(room, stanza) core_post_stanza(component, stanza); end local function room_save(room, forced) local node = jid_split(room.jid); persistent_rooms[room.jid] = room._data.persistent; module:log("debug", "1, %s, %s", room.jid, tostring(room._data.persistent)); if room._data.persistent then module:log("debug", "2"); local history = room._data.history; room._data.history = nil; local data = { jid = room.jid; _data = room._data; _affiliations = room._affiliations; }; datamanager.store(node, muc_host, "config", data); room._data.history = history; elseif forced then module:log("debug", "3"); datamanager.store(node, muc_host, "config", nil); end module:log("debug", "4"); if forced then datamanager.store(nil, muc_host, "persistent", persistent_rooms); end end for jid in pairs(persistent_rooms) do local node = jid_split(jid); local data = datamanager.load(node, muc_host, "config") or {}; local room = muc_new_room(jid); room._data = data._data; room._affiliations = data._affiliations; room.route_stanza = room_route_stanza; room.save = room_save; rooms[jid] = room; end local host_room = muc_new_room(muc_host); host_room.route_stanza = room_route_stanza; host_room.save = room_save; local function get_disco_info(stanza) return st.iq({type='result', id=stanza.attr.id, from=muc_host, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info") :tag("identity", {category='conference', type='text', name=muc_name}):up() :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply end local function get_disco_items(stanza) local reply = st.iq({type='result', id=stanza.attr.id, from=muc_host, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items"); for jid, room in pairs(rooms) do if not room._data.hidden then reply:tag("item", {jid=jid, name=jid}):up(); end end return reply; -- TODO cache disco reply end local function handle_to_domain(origin, stanza) local type = stanza.attr.type; if type == "error" or type == "result" then return; end if stanza.name == "iq" and type == "get" then local xmlns = stanza.tags[1].attr.xmlns; if xmlns == "http://jabber.org/protocol/disco#info" then origin.send(get_disco_info(stanza)); elseif xmlns == "http://jabber.org/protocol/disco#items" then origin.send(get_disco_items(stanza)); elseif xmlns == "http://jabber.org/protocol/muc#unique" then origin.send(st.reply(stanza):tag("unique", {xmlns = xmlns}):text(uuid_gen())); -- FIXME Random UUIDs can theoretically have collisions else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc end else host_room:handle_stanza(origin, stanza); --origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it")); end end component = register_component(muc_host, function(origin, stanza) local to_node, to_host, to_resource = jid_split(stanza.attr.to); if to_node then local bare = to_node.."@"..to_host; if to_host == muc_host or bare == muc_host then local room = rooms[bare]; if not room then room = muc_new_room(bare); room.route_stanza = room_route_stanza; room.save = room_save; rooms[bare] = room; end room:handle_stanza(origin, stanza); if not next(room._occupants) and not persistent_rooms[room.jid] then -- empty, non-persistent room rooms[bare] = nil; -- discard room end else --[[not for us?]] end return; end -- to the main muc domain handle_to_domain(origin, stanza); end); prosody.hosts[module:get_host()].muc = { rooms = rooms }; module.unload = function() deregister_component(muc_host); end module.save = function() return {rooms = rooms}; end module.restore = function(data) rooms = {}; for jid, oldroom in pairs(data.rooms or {}) do local room = muc_new_room(jid); room._jid_nick = oldroom._jid_nick; room._occupants = oldroom._occupants; room._data = oldroom._data; room._affiliations = oldroom._affiliations; room.route_stanza = room_route_stanza; room.save = room_save; rooms[jid] = room; end prosody.hosts[module:get_host()].muc = { rooms = rooms }; end
-- 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. -- if module:get_host_type() ~= "component" then error("MUC should be loaded as a component, please see http://prosody.im/doc/components", 0); end local muc_host = module:get_host(); local muc_name = "Chatrooms"; local history_length = 20; local muc_new_room = module:require "muc".new_room; local register_component = require "core.componentmanager".register_component; local deregister_component = require "core.componentmanager".deregister_component; local jid_split = require "util.jid".split; local st = require "util.stanza"; local uuid_gen = require "util.uuid".generate; local datamanager = require "util.datamanager"; local rooms = {}; local persistent_rooms = datamanager.load(nil, muc_host, "persistent") or {}; local component; local function room_route_stanza(room, stanza) core_post_stanza(component, stanza); end local function room_save(room, forced) local node = jid_split(room.jid); persistent_rooms[room.jid] = room._data.persistent; module:log("debug", "1, %s, %s", room.jid, tostring(room._data.persistent)); if room._data.persistent then module:log("debug", "2"); local history = room._data.history; room._data.history = nil; local data = { jid = room.jid; _data = room._data; _affiliations = room._affiliations; }; datamanager.store(node, muc_host, "config", data); room._data.history = history; elseif forced then module:log("debug", "3"); datamanager.store(node, muc_host, "config", nil); end module:log("debug", "4"); if forced then datamanager.store(nil, muc_host, "persistent", persistent_rooms); end end for jid in pairs(persistent_rooms) do local node = jid_split(jid); local data = datamanager.load(node, muc_host, "config") or {}; local room = muc_new_room(jid); room._data = data._data; room._affiliations = data._affiliations; room.route_stanza = room_route_stanza; room.save = room_save; rooms[jid] = room; end local host_room = muc_new_room(muc_host); host_room.route_stanza = room_route_stanza; host_room.save = room_save; local function get_disco_info(stanza) return st.iq({type='result', id=stanza.attr.id, from=muc_host, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info") :tag("identity", {category='conference', type='text', name=muc_name}):up() :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply end local function get_disco_items(stanza) local reply = st.iq({type='result', id=stanza.attr.id, from=muc_host, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items"); for jid, room in pairs(rooms) do if not room._data.hidden then reply:tag("item", {jid=jid, name=jid}):up(); end end return reply; -- TODO cache disco reply end local function handle_to_domain(origin, stanza) local type = stanza.attr.type; if type == "error" or type == "result" then return; end if stanza.name == "iq" and type == "get" then local xmlns = stanza.tags[1].attr.xmlns; if xmlns == "http://jabber.org/protocol/disco#info" then origin.send(get_disco_info(stanza)); elseif xmlns == "http://jabber.org/protocol/disco#items" then origin.send(get_disco_items(stanza)); elseif xmlns == "http://jabber.org/protocol/muc#unique" then origin.send(st.reply(stanza):tag("unique", {xmlns = xmlns}):text(uuid_gen())); -- FIXME Random UUIDs can theoretically have collisions else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc end else host_room:handle_stanza(origin, stanza); --origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it")); end end component = register_component(muc_host, function(origin, stanza) local to_node, to_host, to_resource = jid_split(stanza.attr.to); if to_node then local bare = to_node.."@"..to_host; if to_host == muc_host or bare == muc_host then local room = rooms[bare]; if not room then room = muc_new_room(bare); room.route_stanza = room_route_stanza; room.save = room_save; rooms[bare] = room; end room:handle_stanza(origin, stanza); if not next(room._occupants) and not persistent_rooms[room.jid] then -- empty, non-persistent room rooms[bare] = nil; -- discard room end else --[[not for us?]] end return; end -- to the main muc domain handle_to_domain(origin, stanza); end); function component.send(stanza) -- FIXME do a generic fix if stanza.attr.type == "result" or stanza.attr.type == "error" then core_post_stanza(component, stanza); else error("component.send only supports result and error stanzas at the moment"); end end prosody.hosts[module:get_host()].muc = { rooms = rooms }; module.unload = function() deregister_component(muc_host); end module.save = function() return {rooms = rooms}; end module.restore = function(data) rooms = {}; for jid, oldroom in pairs(data.rooms or {}) do local room = muc_new_room(jid); room._jid_nick = oldroom._jid_nick; room._occupants = oldroom._occupants; room._data = oldroom._data; room._affiliations = oldroom._affiliations; room.route_stanza = room_route_stanza; room.save = room_save; rooms[jid] = room; end prosody.hosts[module:get_host()].muc = { rooms = rooms }; end
MUC: Added a send() method to the component. Fixes issues with local mod_vcard.
MUC: Added a send() method to the component. Fixes issues with local mod_vcard.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
aecdd22c34afc044292ca3769cbc9818fe9248f6
modules/textadept/run.lua
modules/textadept/run.lua
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Module for running/executing source files. module('_m.textadept.run', package.seeall) --- -- Executes the command line parameter and prints the output to Textadept. -- @param command The command line string. -- It can have the following macros: -- * %(filepath) The full path of the current file. -- * %(filedir) The current file's directory path. -- * %(filename) The name of the file including extension. -- * %(filename_noext) The name of the file excluding extension. function execute(command) local filepath = textadept.iconv(buffer.filename, _CHARSET, 'UTF-8') local filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$') local filename_noext = filename:match('^(.+)%.') command = command:gsub('%%%b()', { ['%(filepath)'] = filepath, ['%(filedir)'] = filedir, ['%(filename)'] = filename, ['%(filename_noext)'] = filename_noext, }) local current_dir = lfs.currentdir() lfs.chdir(filedir) local p = io.popen(command..' 2>&1') local out = p:read('*all') p:close() lfs.chdir(current_dir) textadept.print(textadept.iconv('> '..command..'\n'..out, 'UTF-8', _CHARSET)) buffer:goto_pos(buffer.length) end --- -- File extensions and their associated 'compile' actions. -- Each key is a file extension whose value is a either a command line string to -- execute or a function returning one. -- @class table -- @name compile_commands compile_commands = { c = 'gcc -pedantic -Os -o "%(filename_noext)" %(filename)', cpp = 'g++ -pedantic -Os -o "%(filename_noext)" %(filename)', java = 'javac "%(filename)"' } --- -- Compiles the file as specified by its extension in the compile_commands -- table. -- @see compile_commands function compile() if not buffer.filename then return end local action = compile_commands[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- File extensions and their associated 'go' actions. -- Each key is a file extension whose value is either a command line string to -- execute or a function returning one. -- @class table -- @name run_commands run_commands = { c = '%(filedir)%(filename_noext)', cpp = '%(filedir)%(filename_noext)', java = function() local buffer = buffer local text = buffer:get_text() local s, e, package repeat s, e, package = text:find('package%s+([^;]+)', e or 1) until not s or buffer:get_style_name(buffer.style_at[s]) ~= 'comment' if package then local classpath = '' for dot in package:gmatch('%.') do classpath = classpath..'../' end return 'java -cp '..(WIN32 and '%CLASSPATH%;' or '$CLASSPATH:').. classpath..'../ '..package..'.%(filename_noext)' else return 'java %(filename_noext)' end end, lua = 'lua %(filename)', pl = 'perl %(filename)', php = 'php -f %(filename)', py = 'python %(filename)', rb = 'ruby %(filename)', } --- -- Runs/executes the file as specified by its extension in the run_commands -- table. -- @see run_commands function run() if not buffer.filename then return end local action = run_commands[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- [Local table] A table of error string details. -- Each entry is a table with the following fields: -- pattern: the Lua pattern that matches a specific error string. -- filename: the index of the Lua capture that contains the filename the error -- occured in. -- line: the index of the Lua capture that contains the line number the error -- occured on. -- message: [Optional] the index of the Lua capture that contains the error's -- message. A call tip will be displayed if a message was captured. -- When an error message is double-clicked, the user is taken to the point of -- error. -- @class table -- @name error_details local error_details = { -- c, c++, and java errors and warnings have the same format as ruby ones lua = { pattern = '^lua: (.-):(%d+): (.+)$', filename = 1, line = 2, message = 3 }, perl = { pattern = '^(.+) at (.-) line (%d+)', message = 1, filename = 2, line = 3 }, php_error = { pattern = '^Parse error: (.+) in (.-) on line (%d+)', message = 1, filename = 2, line = 3 }, php_warning = { pattern = '^Warning: (.+) in (.-) on line (%d+)', message = 1, filename = 2, line = 3 }, python = { pattern = '^%s*File "([^"]+)", line (%d+)', filename = 1, line = 2 }, ruby = { pattern = '^(.-):(%d+): (.+)$', filename = 1, line = 2, message = 3 }, } --- -- When the user double-clicks an error message, go to the line in the file -- the error occured at and display a calltip with the error message. -- @param pos The position of the caret. -- @param line_num The line double-clicked. -- @see error_details function goto_error(pos, line_num) local type = buffer._type if type == locale.MESSAGE_BUFFER or type == locale.ERROR_BUFFER then line = buffer:get_line(line_num) for _, error_detail in pairs(error_details) do local captures = { line:match(error_detail.pattern) } if #captures > 0 then local lfs = require 'lfs' local utf8_filename = captures[error_detail.filename] local filename = textadept.iconv(utf8_filename, _CHARSET, 'UTF-8') if lfs.attributes(filename) then textadept.io.open(utf8_filename) _m.textadept.editing.goto_line(captures[error_detail.line]) local msg = captures[error_detail.message] if msg then buffer:call_tip_show(buffer.current_pos, msg) end else error(string.format( locale.M_TEXTADEPT_RUN_FILE_DOES_NOT_EXIST, utf8_filename)) end break end end end end textadept.events.add_handler('double_click', goto_error)
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Module for running/executing source files. module('_m.textadept.run', package.seeall) --- -- Executes the command line parameter and prints the output to Textadept. -- @param command The command line string. -- It can have the following macros: -- * %(filepath) The full path of the current file. -- * %(filedir) The current file's directory path. -- * %(filename) The name of the file including extension. -- * %(filename_noext) The name of the file excluding extension. function execute(command) local filepath = textadept.iconv(buffer.filename, _CHARSET, 'UTF-8') local filedir, filename if filepath:find('[/\\]') then filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$') else filedir, filename = '', filepath end local filename_noext = filename:match('^(.+)%.') command = command:gsub('%%%b()', { ['%(filepath)'] = filepath, ['%(filedir)'] = filedir, ['%(filename)'] = filename, ['%(filename_noext)'] = filename_noext, }) local current_dir = lfs.currentdir() lfs.chdir(filedir) local p = io.popen(command..' 2>&1') local out = p:read('*all') p:close() lfs.chdir(current_dir) textadept.print(textadept.iconv('> '..command..'\n'..out, 'UTF-8', _CHARSET)) buffer:goto_pos(buffer.length) end --- -- File extensions and their associated 'compile' actions. -- Each key is a file extension whose value is a either a command line string to -- execute or a function returning one. -- @class table -- @name compile_commands compile_commands = { c = 'gcc -pedantic -Os -o "%(filename_noext)" %(filename)', cpp = 'g++ -pedantic -Os -o "%(filename_noext)" %(filename)', java = 'javac "%(filename)"' } --- -- Compiles the file as specified by its extension in the compile_commands -- table. -- @see compile_commands function compile() if not buffer.filename then return end local action = compile_commands[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- File extensions and their associated 'go' actions. -- Each key is a file extension whose value is either a command line string to -- execute or a function returning one. -- @class table -- @name run_commands run_commands = { c = '%(filedir)%(filename_noext)', cpp = '%(filedir)%(filename_noext)', java = function() local buffer = buffer local text = buffer:get_text() local s, e, package repeat s, e, package = text:find('package%s+([^;]+)', e or 1) until not s or buffer:get_style_name(buffer.style_at[s]) ~= 'comment' if package then local classpath = '' for dot in package:gmatch('%.') do classpath = classpath..'../' end return 'java -cp '..(WIN32 and '%CLASSPATH%;' or '$CLASSPATH:').. classpath..'../ '..package..'.%(filename_noext)' else return 'java %(filename_noext)' end end, lua = 'lua %(filename)', pl = 'perl %(filename)', php = 'php -f %(filename)', py = 'python %(filename)', rb = 'ruby %(filename)', } --- -- Runs/executes the file as specified by its extension in the run_commands -- table. -- @see run_commands function run() if not buffer.filename then return end local action = run_commands[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- [Local table] A table of error string details. -- Each entry is a table with the following fields: -- pattern: the Lua pattern that matches a specific error string. -- filename: the index of the Lua capture that contains the filename the error -- occured in. -- line: the index of the Lua capture that contains the line number the error -- occured on. -- message: [Optional] the index of the Lua capture that contains the error's -- message. A call tip will be displayed if a message was captured. -- When an error message is double-clicked, the user is taken to the point of -- error. -- @class table -- @name error_details local error_details = { -- c, c++, and java errors and warnings have the same format as ruby ones lua = { pattern = '^lua: (.-):(%d+): (.+)$', filename = 1, line = 2, message = 3 }, perl = { pattern = '^(.+) at (.-) line (%d+)', message = 1, filename = 2, line = 3 }, php_error = { pattern = '^Parse error: (.+) in (.-) on line (%d+)', message = 1, filename = 2, line = 3 }, php_warning = { pattern = '^Warning: (.+) in (.-) on line (%d+)', message = 1, filename = 2, line = 3 }, python = { pattern = '^%s*File "([^"]+)", line (%d+)', filename = 1, line = 2 }, ruby = { pattern = '^(.-):(%d+): (.+)$', filename = 1, line = 2, message = 3 }, } --- -- When the user double-clicks an error message, go to the line in the file -- the error occured at and display a calltip with the error message. -- @param pos The position of the caret. -- @param line_num The line double-clicked. -- @see error_details function goto_error(pos, line_num) local type = buffer._type if type == locale.MESSAGE_BUFFER or type == locale.ERROR_BUFFER then line = buffer:get_line(line_num) for _, error_detail in pairs(error_details) do local captures = { line:match(error_detail.pattern) } if #captures > 0 then local lfs = require 'lfs' local utf8_filename = captures[error_detail.filename] local filename = textadept.iconv(utf8_filename, _CHARSET, 'UTF-8') if lfs.attributes(filename) then textadept.io.open(utf8_filename) _m.textadept.editing.goto_line(captures[error_detail.line]) local msg = captures[error_detail.message] if msg then buffer:call_tip_show(buffer.current_pos, msg) end else error(string.format( locale.M_TEXTADEPT_RUN_FILE_DOES_NOT_EXIST, utf8_filename)) end break end end end end textadept.events.add_handler('double_click', goto_error)
Fixed bug for running filename with no path; modules/textadept/run.lua
Fixed bug for running filename with no path; modules/textadept/run.lua --HG-- extra : rebase_source : 050d2fd8ada2b7a96d2e686b7c0fe4a709448f45
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
32f9d3eb428d0687bc80bb302059b7bcaf6fe1dc
nvim/lua/user/ui.lua
nvim/lua/user/ui.lua
local filereadable_key = 'filereadable' local function file_exists(name) local f = io.open(name, 'r') return f ~= nil and io.close(f) end local function buf_get_var(bufnr, name, default) local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name) if ok then return value end return default end local function update_filereadable() local path = vim.api.nvim_buf_get_name(0) if path ~= '' then vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path)) end end local function tabline() local line = {} local tab_list = vim.api.nvim_list_tabpages() local current = vim.api.nvim_get_current_tabpage() for _, tabnr in ipairs(tab_list) do local winnr = vim.api.nvim_tabpage_get_win(tabnr) local bufnr = vim.api.nvim_win_get_buf(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local name = vim.fn.fnamemodify(path, ':t') name = name ~= '' and name or '[No Name]' -- Work around flickering tab with https://github.com/Shougo/ddu-ui-ff if string.match(name, '^ddu-') then name = 'ddu' end local flags = {} if vim.bo[bufnr].mod then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end local tab = { '%', tabnr, 'T', (tabnr == current and '%#TabLineSel#' or '%#TabLine#'), ' ', name, (#flags > 0 and ' ' .. table.concat(flags, '') or ''), ' ', } table.insert(line, table.concat(tab, '')) end table.insert(line, '%#TabLineFill#') return table.concat(line, '') end local function render_statusline(winnr, active) local bufnr = vim.api.nvim_win_get_buf(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local buftype = vim.bo[bufnr].buftype local is_file = (buftype == '') local l0 = {} local l1 = {} local r1 = {} local r0 = {} if active then table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#') else table.insert(l0, '%#StatusLine#') end if active then local filetype = vim.bo[bufnr].filetype table.insert(l0, filetype == '' and 'plain' or filetype) else if is_file and path ~= '' then local rel_path = vim.fn.fnamemodify(path, ':p:~:.') table.insert(l0, rel_path) elseif is_file then table.insert(l0, '[No Name]') else table.insert(l0, buftype) end end local flags = {} if vim.bo[bufnr].readonly then table.insert(flags, '!') end if vim.bo[bufnr].modified then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end if #flags > 0 then table.insert(l0, table.concat(flags, '')) end if active and is_file then local last_saved_time = buf_get_var(bufnr, 'auto_save_last_saved_time', 0) if 0 < last_saved_time and last_saved_time >= os.time() - 60 then table.insert(l1, os.date('✓ %X', last_saved_time)) end end if active then local diagnostics = { E = 0, W = 0, I = 0, H = 0 } local status = buf_get_var(bufnr, 'coc_diagnostic_info', nil) if status then diagnostics.E = diagnostics.E + (status.error or 0) diagnostics.W = diagnostics.W + (status.warning or 0) diagnostics.I = diagnostics.I + (status.information or 0) diagnostics.H = diagnostics.H + (status.hint or 0) end if diagnostics.E > 0 then local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E) table.insert(l1, text) end if diagnostics.W > 0 then local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W) table.insert(l1, text) end if diagnostics.I > 0 then local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I) table.insert(l1, text) end if diagnostics.H > 0 then local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H) table.insert(l1, text) end end local coc_status = vim.g.coc_status or '' if active and coc_status ~= '' then table.insert(r1, string.sub(coc_status, 0, 60)) end if active then local encoding = vim.bo[bufnr].fileencoding local format = vim.bo[bufnr].fileformat table.insert(r0, encoding ~= '' and encoding or vim.o.encoding) table.insert(r0, format) table.insert(r0, '∙') table.insert(r0, '%l:%c') table.insert(r0, '∙') table.insert(r0, '%p%%') end return table.concat({ table.concat(l0, ' '), '%*', table.concat(l1, ' '), '%=', table.concat(r1, ' '), '%*', table.concat(r0, ' '), '%*', }, ' ') end local function statusline() local winnr = vim.g.statusline_winid local active = winnr == vim.fn.win_getid() if active then require('candle').update_mode_highlight() end return render_statusline(winnr, active) end local function setup() vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]] vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]] vim.api.nvim_exec([[ augroup user_ui_statusline autocmd! autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable() autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline() autocmd BufWinEnter,WinEnter,BufEnter * set statusline< autocmd VimResized * redrawstatus augroup END ]], false) end return { setup = setup, statusline = statusline, tabline = tabline, update_filereadable = update_filereadable, }
local filereadable_key = 'filereadable' local current_normal_winnr_key = 'current_normal_winnr' local function file_exists(name) local f = io.open(name, 'r') return f ~= nil and io.close(f) end local function update_filereadable() local path = vim.api.nvim_buf_get_name(0) if path ~= '' then vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path)) end end local function safe_buf_get_var(bufnr, name, default) local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name) if ok then return value end return default end local function safe_tabpage_get_var(tabnr, name, default) local ok, value = pcall(vim.api.nvim_tabpage_get_var, tabnr, name) if ok then return value end return default end local function tabpage_get_win(tabnr) local winnr = vim.api.nvim_tabpage_get_win(tabnr) local config = vim.api.nvim_win_get_config(winnr) local is_normal = config.relative == '' if is_normal then vim.api.nvim_tabpage_set_var(tabnr, current_normal_winnr_key, winnr) return winnr end return safe_tabpage_get_var(tabnr, current_normal_winnr_key, winnr) end local function tabline() local line = {} local tab_list = vim.api.nvim_list_tabpages() local current = vim.api.nvim_get_current_tabpage() for _, tabnr in ipairs(tab_list) do local winnr = tabpage_get_win(tabnr) local bufnr = vim.api.nvim_win_get_buf(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local name = vim.fn.fnamemodify(path, ':t') name = name ~= '' and name or '[No Name]' local flags = {} if vim.bo[bufnr].mod then table.insert(flags, '+') end if not safe_buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end local tab = { '%', tabnr, 'T', (tabnr == current and '%#TabLineSel#' or '%#TabLine#'), ' ', name, (#flags > 0 and ' ' .. table.concat(flags, '') or ''), ' ', } table.insert(line, table.concat(tab, '')) end table.insert(line, '%#TabLineFill#') return table.concat(line, '') end local function render_statusline(winnr, active) local bufnr = vim.api.nvim_win_get_buf(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local buftype = vim.bo[bufnr].buftype local is_file = (buftype == '') local l0 = {} local l1 = {} local r1 = {} local r0 = {} if active then table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#') else table.insert(l0, '%#StatusLine#') end if active then local filetype = vim.bo[bufnr].filetype table.insert(l0, filetype == '' and 'plain' or filetype) else if is_file and path ~= '' then local rel_path = vim.fn.fnamemodify(path, ':p:~:.') table.insert(l0, rel_path) elseif is_file then table.insert(l0, '[No Name]') else table.insert(l0, buftype) end end local flags = {} if vim.bo[bufnr].readonly then table.insert(flags, '!') end if vim.bo[bufnr].modified then table.insert(flags, '+') end if not safe_buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end if #flags > 0 then table.insert(l0, table.concat(flags, '')) end if active and is_file then local last_saved_time = safe_buf_get_var(bufnr, 'auto_save_last_saved_time', 0) if 0 < last_saved_time and last_saved_time >= os.time() - 60 then table.insert(l1, os.date('✓ %X', last_saved_time)) end end if active then local diagnostics = { E = 0, W = 0, I = 0, H = 0 } local status = safe_buf_get_var(bufnr, 'coc_diagnostic_info', nil) if status then diagnostics.E = diagnostics.E + (status.error or 0) diagnostics.W = diagnostics.W + (status.warning or 0) diagnostics.I = diagnostics.I + (status.information or 0) diagnostics.H = diagnostics.H + (status.hint or 0) end if diagnostics.E > 0 then local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E) table.insert(l1, text) end if diagnostics.W > 0 then local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W) table.insert(l1, text) end if diagnostics.I > 0 then local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I) table.insert(l1, text) end if diagnostics.H > 0 then local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H) table.insert(l1, text) end end local coc_status = vim.g.coc_status or '' if active and coc_status ~= '' then table.insert(r1, string.sub(coc_status, 0, 60)) end if active then local encoding = vim.bo[bufnr].fileencoding local format = vim.bo[bufnr].fileformat table.insert(r0, encoding ~= '' and encoding or vim.o.encoding) table.insert(r0, format) table.insert(r0, '∙') table.insert(r0, '%l:%c') table.insert(r0, '∙') table.insert(r0, '%p%%') end return table.concat({ table.concat(l0, ' '), '%*', table.concat(l1, ' '), '%=', table.concat(r1, ' '), '%*', table.concat(r0, ' '), '%*', }, ' ') end local function statusline() local winnr = vim.g.statusline_winid local active = winnr == vim.fn.win_getid() if active then require('candle').update_mode_highlight() end return render_statusline(winnr, active) end local function setup() vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]] vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]] vim.api.nvim_exec([[ augroup user_ui_statusline autocmd! autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable() autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline() autocmd BufWinEnter,WinEnter,BufEnter * set statusline< autocmd VimResized * redrawstatus augroup END ]], false) end return { setup = setup, statusline = statusline, tabline = tabline, update_filereadable = update_filereadable, }
Fix tabline to ignore floating windows
Fix tabline to ignore floating windows
Lua
mit
creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles
41b8703b54f2d58823f6593787cf89e4856537ac
spec/handshake_spec.lua
spec/handshake_spec.lua
package.path = package.path..'../src' local port = os.getenv('LUAWS_WSTEST_PORT') or 8081 local url = 'ws://localhost:'..port local handshake = require'websocket.handshake' local socket = require'socket' require'pack' local request_lines = { 'GET /chat HTTP/1.1', 'Host: server.example.com', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Protocol: chat, superchat', 'Sec-WebSocket-Version: 13', 'Origin: http://example.com', '\r\n' } local request_header = table.concat(request_lines,'\r\n') local bytes = string.char describe( 'The handshake module', function() it( 'RFC 1.3: calculate the correct accept sum', function() local sec_websocket_key = "dGhlIHNhbXBsZSBub25jZQ==" local accept = handshake.sec_websocket_accept(sec_websocket_key) assert.is_same(accept,"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") end) it( 'can create handshake header', function() local req = handshake.upgrade_request { key = 'dGhlIHNhbXBsZSBub25jZQ==', host = 'server.example.com', origin = 'http://example.com', protocols = {'chat','superchat'}, uri = '/chat' } assert.is_same(req,request_header) end) it( 'can parse handshake header', function() local headers,remainder = handshake.http_headers(request_header..'foo') assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-key'],'dGhlIHNhbXBsZSBub25jZQ==') assert.is_same(headers['sec-websocket-version'],'13') assert.is_same(headers['sec-websocket-protocol'],'chat, superchat') assert.is_same(headers['origin'],'http://example.com') assert.is_same(headers['host'],'server.example.com') assert.is_same(remainder,'foo') end) it( 'generates correct upgrade response', function() local response,protocol = handshake.accept_upgrade(request_header,{'chat'}) assert.is_same(type(response),'string') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) assert.is_same(protocol,'chat') local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-protocol'],'chat') assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) it( 'generates correct upgrade response for unsupported protocol', function() local response,protocol = handshake.accept_upgrade(request_header,{'bla'}) assert.is_same(type(response),'string') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) assert.is_same(protocol,nil) local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-protocol'],nil) assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) describe( 'connecting to echo server (echo-js.ws) on port 8081', function() local sock = socket.tcp() sock:settimeout(0.3) it( 'can connect and upgrade to websocket protocol', function() sock:connect('localhost',port) local req = handshake.upgrade_request { key = 'dGhlIHNhbXBsZSBub25jZQ==', host = 'localhost:'..port, protocols = {'echo-protocol'}, origin = 'http://example.com', uri = '/' } sock:send(req) local resp = {} repeat local line,err = sock:receive('*l') resp[#resp+1] = line until err or line == '' assert.is_falsy(err) local response = table.concat(resp,'\r\n') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) it( 'and can send and receive frames', function() -- from rfc doc local hello_unmasked = bytes(0x81,0x05,0x48,0x65,0x6c,0x6c,0x6f) local hello_masked = bytes(0x81,0x85,0x37,0xfa,0x21,0x3d,0x7f,0x9f,0x4d,0x51,0x58) -- the client MUST send masked sock:send(hello_masked) local resp,err = sock:receive(#hello_unmasked) assert.is_falsy(err) -- the server answers unmasked assert.is_same(resp,hello_unmasked) end) end) end)
package.path = package.path..'../src' local port = os.getenv('LUAWS_WSTEST_PORT') or 8081 local url = 'ws://localhost:'..port local handshake = require'websocket.handshake' local socket = require'socket' require'pack' local request_lines = { 'GET /chat HTTP/1.1', 'Host: server.example.com', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Protocol: chat, superchat', 'Sec-WebSocket-Version: 13', 'Origin: http://example.com', '\r\n' } local request_header = table.concat(request_lines,'\r\n') local bytes = string.char describe( 'The handshake module', function() it( 'RFC 1.3: calculate the correct accept sum', function() local sec_websocket_key = "dGhlIHNhbXBsZSBub25jZQ==" local accept = handshake.sec_websocket_accept(sec_websocket_key) assert.is_same(accept,"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") end) it( 'can create handshake header', function() local req = handshake.upgrade_request { key = 'dGhlIHNhbXBsZSBub25jZQ==', host = 'server.example.com', origin = 'http://example.com', protocols = {'chat','superchat'}, uri = '/chat' } assert.is_same(req,request_header) end) it( 'can parse handshake header', function() local headers,remainder = handshake.http_headers(request_header..'foo') assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-key'],'dGhlIHNhbXBsZSBub25jZQ==') assert.is_same(headers['sec-websocket-version'],'13') assert.is_same(headers['sec-websocket-protocol'],'chat, superchat') assert.is_same(headers['origin'],'http://example.com') assert.is_same(headers['host'],'server.example.com') assert.is_same(remainder,'foo') end) it( 'generates correct upgrade response', function() local response,protocol = handshake.accept_upgrade(request_header,{'chat'}) assert.is_same(type(response),'string') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) assert.is_same(protocol,'chat') local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-protocol'],'chat') assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) it( 'generates correct upgrade response for unsupported protocol', function() local response,protocol = handshake.accept_upgrade(request_header,{'bla'}) assert.is_same(type(response),'string') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) assert.is_same(protocol,nil) local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-protocol'],nil) assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) describe( 'connecting to echo server (echo-js.ws) on port 8081', function() local sock = socket.tcp() sock:settimeout(0.3) it( 'can connect and upgrade to websocket protocol', function() sock:connect('localhost',port) local req = handshake.upgrade_request { key = 'dGhlIHNhbXBsZSBub25jZQ==', host = 'localhost:'..port, protocols = {'echo-protocol'}, origin = 'http://example.com', uri = '/' } sock:send(req) local resp = {} repeat local line,err = sock:receive('*l') assert.is_falsy(err) resp[#resp+1] = line until line == '' local response = table.concat(resp,'\r\n') assert.is_truthy(response:match('^HTTP/1.1 101 Switching Protocols\r\n')) local headers = handshake.http_headers(response) assert.is_same(type(headers),'table') assert.is_same(headers['upgrade'],'websocket') assert.is_same(headers['connection'],'upgrade') assert.is_same(headers['sec-websocket-accept'],'s3pPLMBiTxaQ9kYGzzhZRbK+xOo=') end) it( 'and can send and receive frames', function() -- from rfc doc local hello_unmasked = bytes(0x81,0x05,0x48,0x65,0x6c,0x6c,0x6f) local hello_masked = bytes(0x81,0x85,0x37,0xfa,0x21,0x3d,0x7f,0x9f,0x4d,0x51,0x58) -- the client MUST send masked sock:send(hello_masked) local resp,err = sock:receive(#hello_unmasked) assert.is_falsy(err) -- the server answers unmasked assert.is_same(resp,hello_unmasked) end) end) end)
fix test
fix test
Lua
mit
KSDaemon/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets
9408820c8377437b977b25725985d658ee2311ad
lib/lua/lunarender/rendering.lua
lib/lua/lunarender/rendering.lua
-- part of LunaRender -- (c) 2015 Mikoláš Štrajt -- MIT licensed local proj = require 'lunarender.projection' local xmlwriter = require 'lunarender.xmlwriter' local push = table.insert local _M = {} local function apply_style(style, tags, zoom) if type(style)=='function' then return style(tags, zoom) end return style end local function path_d(way, zoom, fx, ty) local x, y local d={} for i, node in ipairs(way) do x,y = proj.wgs84_to_px(node.lat, node.lon, zoom) x = x-fx y = y-ty if i==1 then push(d, 'M') push(d, ' ') push(d, x) push(d, ' ') push(d, y) else push(d, ' L') push(d, ' ') push(d, x) push(d, ' ') push(d, y) end end return table.concat(d) end -- todo: refactor folowing god function -- renders data to SVG file output_filename using ruleset function _M.render(data, ruleset, zoom, output_filename) local id, rule, node, way, textval local target if ruleset.zoom then zoom = ruleset.zoom end local x,y local fx, fy = proj.wgs84_to_px(data.minlat, data.minlon, zoom) local tx, ty = proj.wgs84_to_px(data.maxlat, data.maxlon, zoom) local layers = {} local svg = {[0]='svg', xmlns="http://www.w3.org/2000/svg", ['xmlns:inkscape']='http://www.inkscape.org/namespaces/inkscape', width=math.abs(tx-fx)..'px', height=math.abs(ty-fy)..'px' } if ruleset.background then push(svg, {[0]='rect', width='100%', height='100%', fill=ruleset.background } ) end for _, id in ipairs(ruleset.layers) do layers[id] = {[0]='g', ['inkscape:groupmode']='layer', id=id, ['inkscape:label']=id} push(svg, layers[id] ) end if ruleset.callbacks and ruleset.callbacks.before then ruleset.callbacks.before(data, svg) end for _, rule in ipairs(ruleset) do target = svg if rule.layer then target = layers[rule.layer] or error('Undefined layer named: '..rule.layer) end if rule.type=='node' then for id, node in pairs(data.nodes) do if rule.match(node.tags, zoom) then x,y = proj.wgs84_to_px(node.lat, node.lon, zoom) if rule.draw=='circle' then push(target, {[0]='circle', id='n'..id, cx=x-fx, cy=y-ty, r=2, style=apply_style(rule.style, node.tags, zoom) }) elseif rule.draw=='text' then if type(rule.textkey)=='string' and node.tags[rule.textkey] then textval = node.tags[rule.textkey] end if type(rule.textkey)=='function' then textval = rule.textkey(node.tags, zoom) end if textval then push(target, {[0]='text', id='n'..id, x=x-fx, y=y-ty, r=2, style=apply_style(rule.style, node.tags, zoom), textval}) end elseif rule.draw=='symbola' then push(target, {[0]='text', id='n'..id, x=x-fx, y=y-ty, r=2, style=apply_style(rule.style or ruleset.symbola_style, node.tags, zoom), rule.symbol}) end end print('id',id, node.tags.name or '?') end elseif rule.type=='way' then for id, way in pairs(data.ways) do if not way.closed and rule.match(way.tags, zoom) then push(target, { [0]='path', id='w'..id, d=path_d(way, zoom, fx, ty), style=apply_style(rule.style, way.tags, zoom) } ) end end elseif rule.type=='area' then for id, way in pairs(data.ways) do if way.closed and rule.match(way.tags, zoom) then push(target, { [0]='path', id='w'..id, d=path_d(way, zoom, fx, ty), style=apply_style(rule.style, way.tags, zoom) } ) end end end end if ruleset.callbacks and ruleset.callbacks.after then ruleset.callbacks.after(data, svg) end local out = io.open(output_filename, 'w+') or error('Error opening output file: '..output_filename) out:write(xmlwriter.write(svg)) out:close() end return _M
-- part of LunaRender -- (c) 2015 Mikoláš Štrajt -- MIT licensed local proj = require 'lunarender.projection' local xmlwriter = require 'lunarender.xmlwriter' local push = table.insert local _M = {} local function apply_style(style, tags, zoom) if type(style)=='function' then return style(tags, zoom) end return style end local function path_d(way, zoom, fx, ty) local x, y local d={} for i, node in ipairs(way) do x,y = proj.wgs84_to_px(node.lat, node.lon, zoom) x = x-fx y = y-ty if i==1 then push(d, 'M') push(d, ' ') push(d, x) push(d, ' ') push(d, y) else push(d, ' L') push(d, ' ') push(d, x) push(d, ' ') push(d, y) end end return table.concat(d) end -- todo: refactor folowing god function -- renders data to SVG file output_filename using ruleset function _M.render(data, ruleset, zoom, output_filename) local id, rule, node, way, textval local target if ruleset.zoom then zoom = ruleset.zoom end local x,y local fx, fy = proj.wgs84_to_px(data.minlat, data.minlon, zoom) local tx, ty = proj.wgs84_to_px(data.maxlat, data.maxlon, zoom) local layers = {} local svg = {[0]='svg', xmlns="http://www.w3.org/2000/svg", ['xmlns:inkscape']='http://www.inkscape.org/namespaces/inkscape', width=math.abs(tx-fx)..'px', height=math.abs(ty-fy)..'px' } if ruleset.background then push(svg, {[0]='rect', width='100%', height='100%', fill=ruleset.background } ) end for _, id in ipairs(ruleset.layers) do layers[id] = {[0]='g', ['inkscape:groupmode']='layer', id=id, ['inkscape:label']=id} push(svg, layers[id] ) end if ruleset.callbacks and ruleset.callbacks.before then ruleset.callbacks.before(data, svg) end for _, rule in ipairs(ruleset) do target = svg if rule.layer then target = layers[rule.layer] or error('Undefined layer named: '..rule.layer) end if rule.type=='node' then for id, node in pairs(data.nodes) do if rule.match(node.tags, zoom) then x,y = proj.wgs84_to_px(node.lat, node.lon, zoom) if rule.draw=='circle' then push(target, {[0]='circle', cx=x-fx, cy=y-ty, r=rule.r, style=apply_style(rule.style, node.tags, zoom) }) elseif rule.draw=='text' then if type(rule.textkey)=='string' and node.tags[rule.textkey] then textval = node.tags[rule.textkey] end if type(rule.textkey)=='function' then textval = rule.textkey(node.tags, zoom) end if textval then push(target, {[0]='text', x=x-fx, y=y-ty, style=apply_style(rule.style, node.tags, zoom), transform=rule.transform, textval}) end elseif rule.draw=='symbola' then push(target, {[0]='text', x=x-fx, y=y-ty, style=apply_style(rule.style or ruleset.symbola_style, node.tags, zoom), rule.symbol}) end end end elseif rule.type=='way' then for id, way in pairs(data.ways) do if not way.closed and rule.match(way.tags, zoom) then push(target, { [0]='path', d=path_d(way, zoom, fx, ty), style=apply_style(rule.style, way.tags, zoom) } ) end end elseif rule.type=='area' then for id, way in pairs(data.ways) do if way.closed and rule.match(way.tags, zoom) then push(target, { [0]='path', d=path_d(way, zoom, fx, ty), style=apply_style(rule.style, way.tags, zoom) } ) end end end end if ruleset.callbacks and ruleset.callbacks.after then ruleset.callbacks.after(data, svg) end local out = io.open(output_filename, 'w+') or error('Error opening output file: '..output_filename) out:write(xmlwriter.write(svg)) out:close() end return _M
some rendering bugs
some rendering bugs
Lua
mit
severak/lunarender,severak/lunarender,severak/lunarender
2a0980f23312d2379277d14aece1da1514ba9963
test/grammar_test.lua
test/grammar_test.lua
--[[ test/grammar_test.lua Test suite to validate the Aydede LPeg grammar. Copyright (c) 2014, Joshua Ballanco. Licensed under the BSD 2-Clause License. See COPYING for full license details. --]] require("luaunit") local P = require("lpeg").P local grammar = require("grammar") -- A mock parser that will fail for any function call by default local pmock = {} local function failed_call(table, key) return function (...) error("Unexpected call to method: "..tostring(key), 2) end end setmetatable(pmock, { __index = failed_call }) TestGrammar = {} function TestGrammar:test_string() function pmock.string(str) assert_is(str, "\"Hello, world\"") end local g = grammar(pmock) g[1] = "String" P(g):match("\"Hello, world\"") end function TestGrammar:test_escaped_quote_in_string() function pmock.string(str) assert_is(str, "\"I say, \\\"this works.\\\"\"") end local g = grammar(pmock) g[1] = "String" P(g):match("\"I say, \\\"this works.\\\"\"") end function TestGrammar:test_symbol() function pmock.symbol(str) assert_is(str, "foo") end local g = grammar(pmock) g[1] = "Symbol" P(g):match("foo") end LuaUnit:run()
--[[ test/grammar_test.lua Test suite to validate the Aydede LPeg grammar. Copyright (c) 2014, Joshua Ballanco. Licensed under the BSD 2-Clause License. See COPYING for full license details. --]] require("luaunit") local P = require("lpeg").P local grammar = require("grammar") -- A mock parser that will fail for any function call by default local function failed_call(table, key) return function (...) error("Unexpected call to method: "..tostring(key), 2) end end local function mock(mock_funs) return setmetatable(mock_funs, { __index = failed_call }) end TestGrammar = {} function TestGrammar:test_string() p = mock({ string = function(str) assert_is(str, "\"Hello, world\"") end }) local g = grammar(p) g[1] = "String" P(g):match("\"Hello, world\"") end function TestGrammar:test_escaped_quote_in_string() p = mock({ string = function(str) assert_is(str, "\"I say, \\\"this works.\\\"\"") end }) local g = grammar(p) g[1] = "String" P(g):match("\"I say, \\\"this works.\\\"\"") end function TestGrammar:test_symbol() p = mock({ symbol = function(str) assert_is(str, "foo") end }) local g = grammar(p) g[1] = "Symbol" P(g):match("foo") end LuaUnit:run()
Fix test mock to generate new table each time
Fix test mock to generate new table each time
Lua
bsd-2-clause
jballanc/aydede
95148b796f12367443f69fc0b716107656cd66e3
misc.lua
misc.lua
-- new global functions, either replacing existing ones or providing new -- ones for convenience -- replacements: pairs, ipairs, type -- new: printf, fprintf, eprintf, sprintf, srequire, L -- new version of type() that supports the __type metamethod rawtype = type function type(obj) local mt = getmetatable(obj) if mt and rawget(mt, "__type") then return rawget(mt, "__type")(obj) end return rawtype(obj) end -- update file metatable getmetatable(io.stdout).__type = function() return "file" end -- printf(format, ...) function printf(...) return io.stdout:printf(...) end -- printf to standard error function eprintf(...) return io.stderr:printf(...) end -- bind to io tables, so that file:printf(...) becomes legal getmetatable(io.stdout).__index.printf = function(self, ...) return self:write(string.format(...)) end -- "safe require", returns nil,error if require fails rather than -- throwing an error function srequire(...) local s,r = pcall(require, ...) if s then return r end return nil,r end -- fast one-liner lambda creation function f(src) return assert(loadstring( "return function(" .. src:gsub(" => ", ") return ") .. " end" ))() end -- bind args into function function partial(f, ...) if select('#', ...) == 0 then return f end local arg = (...) return partial(function(...) return f(arg, ...) end, select(2, ...)) end if lfs then function lfs.exists(path) return lfs.attributes(path, "mode") ~= nil end end
-- new global functions, either replacing existing ones or providing new -- ones for convenience -- replacements: pairs, ipairs, type -- new: printf, fprintf, eprintf, sprintf, srequire, L -- new version of type() that supports the __type metamethod rawtype = type function type(obj) local mt = getmetatable(obj) if mt and rawget(mt, "__type") then return rawget(mt, "__type")(obj) end return rawtype(obj) end -- update file metatable getmetatable(io.stdout).__type = function() return "file" end -- printf(format, ...) function printf(...) return io.stdout:printf(...) end -- printf to standard error function eprintf(...) return io.stderr:printf(...) end -- bind to io tables, so that file:printf(...) becomes legal getmetatable(io.stdout).__index.printf = function(self, ...) return self:write(string.format(...)) end -- "safe require", returns nil,error if require fails rather than -- throwing an error function srequire(...) local s,r = pcall(require, ...) if s then return r end return nil,r end -- fast one-liner lambda creation function f(src) return assert(loadstring( "return function(" .. src:gsub(" => ", ") return ") .. " end" ))() end -- bind args into function function partial(f, ...) if select('#', ...) == 0 then return f end local arg = (...) return partial(function(...) return f(arg, ...) end, select(2, ...)) end if lfs then local windows = package.config:sub(1,1) == "\\" -- We make the simplifying assumption in these functions that path separators -- are always forward slashes. This is true on *nix and *should* be true on -- windows, but you can never tell what a user will put into a config file -- somewhere. This function enforces this. function lfs.normalize(path) if windows then return (path:gsub("\\", "/")) else return path end end function lfs.exists(path) path = lfs.normalize(path) if windows then -- Windows stat() is kind of awful. If the path has a trailing slash, it -- will always fail. Except on drive root directories, which *require* a -- trailing slash. Thankfully, appending a "." will always work. path = path:gsub("/$", "/.") end return lfs.attributes(path, "mode") ~= nil end function lfs.dirname(oldpath) local path = lfs.normalize(oldpath):gsub("[^/]+/*$", "") if path == "" then return oldpath end return path end -- Recursive directory creation a la mkdir -p. Unlike lfs.mkdir, this will -- create missing intermediate directories, and will not fail if the -- destination directory already exists. -- It assumes that the directory separator is '/' and that the path is valid -- for the OS it's running on, e.g. no trailing slashes on windows -- it's up -- to the caller to ensure this! function lfs.rmkdir(path) if lfs.exists(path) then return true end if lfs.dirname(path) == path then -- We're being asked to create the root directory! return nil,"mkdir: unable to create root directory" end local r,err = lfs.rmkdir(lfs.dirname(path)) if not r then return nil,err.." (creating "..path..")" end return lfs.mkdir(path) end end
Implement lfs.normalize, lfs.dirname, and lfs.rmkdir; fix lfs.exists on windows
Implement lfs.normalize, lfs.dirname, and lfs.rmkdir; fix lfs.exists on windows It turns out that windows is full of spiders: stat() will fail if the path has a trailing directory, unless it's a root directory path, in which case it will fail if it *doesn't* have one. lfs.exists now contains an ugly workaround for this. lfs.dirname() works as expected, except that \ may be translated to / in the return value on windows. lfs.rmkdir() replicates the behaviour of 'mkdir -p', i.e. it creates missing intermediate directories and does not fail if the target already exists.
Lua
mit
ToxicFrog/luautil
f8fced08fab2f7c1813483cb325d088ff4216200
extensions/vox/init.lua
extensions/vox/init.lua
--- === hs.vox === --- --- Controls for VOX music player local vox = {} local alert = require "hs.alert" local as = require "hs.applescript" local app = require "hs.application" -- Internal function to pass a command to Applescript. local function tell(cmd) local _cmd = 'tell application "vox" to ' .. cmd local ok, result = as.applescript(_cmd) if ok then return result else return nil end end --- hs.vox.pause() --- Function --- Pauses the current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.pause() tell('pause') end --- hs.vox.play() --- Function --- Plays the current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.play() tell('play') end --- hs.vox.playpause() --- Function --- Toggles play/pause of current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.playpause() tell('playpause') end --- hs.vox.next() --- Function --- Skips to the next track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.next() tell('next track') end --- hs.vox.previous() --- Function --- Skips to previous track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.previous() tell('previous track') end --- hs.vox.shuffle() --- Function --- Toggle shuffle state of current list --- --- Parameters: --- * None --- --- Returns: --- * None function vox.shuffle() tell('shuffle') end --- hs.vox.playurl(url) --- Function --- Play media from the given URL --- --- Parameters: --- * url {string} --- --- Returns: --- * None function vox.playurl(url) tell('playurl \"' .. url .. '\"') end --- hs.vox.addurl(url) --- Function --- Add media URL to current list --- --- Parameters: --- * url {string} --- --- Returns: --- * None function vox.addurl(url) tell('addurl \"' .. url .. '\"') end --- hs.vox.forward() --- Function --- Skips the playback position forwards by about 7 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.forward() tell('rewindforward') end --- hs.vox.backward() --- Function --- Skips the playback position backwards by about 7 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.backward() tell('rewindbackward') end --- hs.vox.fastForward() --- Function --- Skips the playback position forwards by about 17 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.fastForward() tell('rewindforwardfast') end --- hs.vox.fastBackward() --- Function --- Skips the playback position backwards by about 14 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.fastBackward() tell('rewindbackwardfast') end --- hs.vox.increaseVolume() --- Function --- Increases the palyer volume --- --- Parameters: --- * None --- --- Returns: --- * None function vox.increaseVolume() tell('increasvolume') end --- hs.vox.decreaseVolume() --- Function --- Decreases the player volume --- --- Parameters: --- * None --- --- Returns: --- * None function vox.decreaseVolume() tell('decreasevolume') end --- hs.vox.togglePlaylist() --- Function --- Toggle playlist --- --- Parameters: --- * None --- --- Returns: --- * None function vox.togglePlaylist() tell('showhideplaylist') end --- hs.vox.trackInfo() --- Function --- Displays information for current track on screen --- --- Parameters: --- * None --- --- Returns: --- * None function vox.trackInfo() local artist = tell('artist') or "Unknown artist" local album = tell('album') or "Unknown album" local track = tell('track') or "Unknown track" alert.show(track .."\n".. album .."\n".. artist, 1.75) end --- hs.vox.getCurrentArtist() --- Function --- Gets the name of the artist of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Artist of the current track, or nil if an error occurred function vox.getCurrentArtist() return tell('artist') or "Unknown artist" end --- hs.vox.getCurrentAlbum() --- Function --- Gets the name of the album of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Album of the current track, or nil if an error occurred function vox.getCurrentAlbum() return tell('album') or "Unknown album" end --- hs.vox.getAlbumArtist() --- Function --- Gets the artist of current Album --- --- Parameters: --- * None --- --- Returns: --- * A string containing the artist of current Album, or nil if an error occurred function vox.getAlbumArtist() return tell('album artist') or "Unknown album artist" end --- hs.vox.getUniqueID() --- Function --- Gets the uniqueID of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the name of the current track, or nil if an error occurred function vox.getUniqueID() return tell('unique id') or "Unknown ID" end --- hs.vox.getPlayerState() --- Function --- Gets the current playback state of vox --- --- Parameters: --- * None --- --- Returns: --- * 0 for paused --- * 1 for playing function vox.getPlayerState() return tell('player state') end --- hs.vox.isRunning() --- Function --- Returns whether VOX is currently open --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether the vox application is running function vox.isRunning() return app.get("VOX"):isRunning() ~= nil end return vox
--- === hs.vox === --- --- Controls for VOX music player local vox = {} local alert = require "hs.alert" local as = require "hs.applescript" local app = require "hs.application" local voxBundleId = "com.coppertino.Vox" -- Internal function to pass a command to Applescript. local function tell(cmd) local _cmd = 'tell application "vox" to ' .. cmd local ok, result = as.applescript(_cmd) if ok then return result else return nil end end --- hs.vox.pause() --- Function --- Pauses the current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.pause() tell('pause') end --- hs.vox.play() --- Function --- Plays the current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.play() tell('play') end --- hs.vox.playpause() --- Function --- Toggles play/pause of current vox track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.playpause() tell('playpause') end --- hs.vox.next() --- Function --- Skips to the next track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.next() tell('next track') end --- hs.vox.previous() --- Function --- Skips to previous track --- --- Parameters: --- * None --- --- Returns: --- * None function vox.previous() tell('previous track') end --- hs.vox.shuffle() --- Function --- Toggle shuffle state of current list --- --- Parameters: --- * None --- --- Returns: --- * None function vox.shuffle() tell('shuffle') end --- hs.vox.playurl(url) --- Function --- Play media from the given URL --- --- Parameters: --- * url {string} --- --- Returns: --- * None function vox.playurl(url) tell('playurl \"' .. url .. '\"') end --- hs.vox.addurl(url) --- Function --- Add media URL to current list --- --- Parameters: --- * url {string} --- --- Returns: --- * None function vox.addurl(url) tell('addurl \"' .. url .. '\"') end --- hs.vox.forward() --- Function --- Skips the playback position forwards by about 7 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.forward() tell('rewindforward') end --- hs.vox.backward() --- Function --- Skips the playback position backwards by about 7 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.backward() tell('rewindbackward') end --- hs.vox.fastForward() --- Function --- Skips the playback position forwards by about 17 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.fastForward() tell('rewindforwardfast') end --- hs.vox.fastBackward() --- Function --- Skips the playback position backwards by about 14 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function vox.fastBackward() tell('rewindbackwardfast') end --- hs.vox.increaseVolume() --- Function --- Increases the palyer volume --- --- Parameters: --- * None --- --- Returns: --- * None function vox.increaseVolume() tell('increasvolume') end --- hs.vox.decreaseVolume() --- Function --- Decreases the player volume --- --- Parameters: --- * None --- --- Returns: --- * None function vox.decreaseVolume() tell('decreasevolume') end --- hs.vox.togglePlaylist() --- Function --- Toggle playlist --- --- Parameters: --- * None --- --- Returns: --- * None function vox.togglePlaylist() tell('showhideplaylist') end --- hs.vox.trackInfo() --- Function --- Displays information for current track on screen --- --- Parameters: --- * None --- --- Returns: --- * None function vox.trackInfo() local artist = tell('artist') or "Unknown artist" local album = tell('album') or "Unknown album" local track = tell('track') or "Unknown track" alert.show(track .."\n".. album .."\n".. artist, 1.75) end --- hs.vox.getCurrentArtist() --- Function --- Gets the name of the artist of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Artist of the current track, or nil if an error occurred function vox.getCurrentArtist() return tell('artist') or "Unknown artist" end --- hs.vox.getCurrentAlbum() --- Function --- Gets the name of the album of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Album of the current track, or nil if an error occurred function vox.getCurrentAlbum() return tell('album') or "Unknown album" end --- hs.vox.getAlbumArtist() --- Function --- Gets the artist of current Album --- --- Parameters: --- * None --- --- Returns: --- * A string containing the artist of current Album, or nil if an error occurred function vox.getAlbumArtist() return tell('album artist') or "Unknown album artist" end --- hs.vox.getUniqueID() --- Function --- Gets the uniqueID of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the name of the current track, or nil if an error occurred function vox.getUniqueID() return tell('unique id') or "Unknown ID" end --- hs.vox.getPlayerState() --- Function --- Gets the current playback state of vox --- --- Parameters: --- * None --- --- Returns: --- * 0 for paused --- * 1 for playing function vox.getPlayerState() return tell('player state') end --- hs.vox.isRunning() --- Function --- Returns whether VOX is currently open --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether the vox application is running function vox.isRunning() local apps = app.applicationsForBundleID(voxBundleId) return #apps > 0 end return vox
Handle VOX not running in isRunning() - fixes #2906
Handle VOX not running in isRunning() - fixes #2906
Lua
mit
Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon
b06d945651d41c64381fda22a6c7189e4850d294
lib/lua/virgo-time.lua
lib/lua/virgo-time.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local logging = require('logging') local Error = require('core').Error local math = require('math') local delta = 0 local delay = 0 local function now() return math.floor(virgo.gmtnow() + delta) end local function raw() return math.floor(virgo.gmtnow()) end local function setDelta(_delta) delta = _delta end local function getDelta() return delta end --[[ This algorithm follows the NTP algorithm found here: http://www.eecis.udel.edu/~mills/ntp/html/warp.html T1 = agent departure timestamp T2 = server receieved timestamp T3 = server transmit timestamp T4 = agent destination timestamp ]]-- local function timesync(T1, T2, T3, T4) if not T1 or not T2 or not T3 or not T4 then return Error:new('T1, T2, T3, or T4 was null. Failed to sync time.') end logging.debug('T1 = %i', T1) logging.debug('T2 = %i', T2) logging.debug('T3 = %i', T3) logging.debug('T4 = %i', T4) delta = ((T2 - T1) + (T3 - T4)) / 2 delay = ((T4 - T1) + (T3 - T2)) logging.infof('Setting time delta to %i', delta) return end local exports = {} exports.setDelta = setDelta exports.getDelta = getDelta exports.now = now exports.raw = raw exports.timesync = timesync return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local logging = require('logging') local Error = require('core').Error local math = require('math') local delta = 0 local delay = 0 local function now() return math.floor(virgo.gmtnow() + delta) end local function raw() return math.floor(virgo.gmtnow()) end local function setDelta(_delta) delta = _delta end local function getDelta() return delta end --[[ This algorithm follows the NTP algorithm found here: http://www.eecis.udel.edu/~mills/ntp/html/warp.html T1 = agent departure timestamp T2 = server receieved timestamp T3 = server transmit timestamp T4 = agent destination timestamp ]]-- local function timesync(T1, T2, T3, T4) if not T1 or not T2 or not T3 or not T4 then return Error:new('T1, T2, T3, or T4 was null. Failed to sync time.') end logging.debugf('time_sync data: T1 = %.0f T2 = %.0f T3 = %.0f T4 = %.0f', T1, T2, T3, T4) delta = ((T2 - T1) + (T3 - T4)) / 2 delay = ((T4 - T1) + (T3 - T2)) logging.infof('Setting time delta to %.0fms based on server time %.0fms', delta, T2) return end local exports = {} exports.setDelta = setDelta exports.getDelta = getDelta exports.now = now exports.raw = raw exports.timesync = timesync return exports
lib: virgo-time: improve debug statement
lib: virgo-time: improve debug statement the debug statement had two problems: 1) it didn't use debugf so the timestamps weren't printed 2) it printed in 4 lines what could be said in 1 Fix both these issues.
Lua
apache-2.0
kans/birgo,kans/birgo,kans/birgo,kans/birgo,kans/birgo
82eecef77502d1d00529492f18a51a33a9d1c8b8
src/apps/tap/tap.lua
src/apps/tap/tap.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local link = require("core.link") local packet = require("core.packet") local counter = require("core.counter") local ethernet = require("lib.protocol.ethernet") local ffi = require("ffi") local C = ffi.C local const = require("syscall.linux.constants") local os = require("os") local t = S.types.t Tap = { } function Tap:new (name) assert(name, "missing tap interface name") local sock, err = S.open("/dev/net/tun", "rdwr, nonblock"); assert(sock, "Error opening /dev/net/tun: " .. tostring(err)) local ifr = t.ifreq() ifr.flags = "tap, no_pi" ifr.name = name local ok, err = sock:ioctl("TUNSETIFF", ifr) if not ok then sock:close() error("Error opening /dev/net/tun: " .. tostring(err)) end return setmetatable({sock = sock, name = name, pkt = packet.allocate(), shm = { rxbytes = {counter}, rxpackets = {counter}, rxmcast = {counter}, rxbcast = {counter}, txbytes = {counter}, txpackets = {counter}, txmcast = {counter}, txbcast = {counter} }}, {__index = Tap}) end function Tap:pull () local l = self.output.output if l == nil then return end local p = self.pkt for i=1,engine.pull_npackets do local len, err = S.read(self.sock, p.data, C.PACKET_PAYLOAD_SIZE) -- errno == EAGAIN indicates that the read would of blocked as there is no -- packet waiting. It is not a failure. if not len and err.errno == const.E.AGAIN then return end if not len then error("Failed read on " .. self.name .. ": " .. tostring(err)) end p.length = len link.transmit(l, p) counter.add(self.shm.rxbytes, len) counter.add(self.shm.rxpackets) if ethernet:is_mcast(p.data) then counter.add(self.shm.rxmcast) end if ethernet:is_bcast(p.data) then counter.add(self.shm.rxbcast) end p = packet.allocate() end self.pkt = p end function Tap:push () local l = self.input.input while not link.empty(l) do -- The socket write might of blocked so don't dequeue the packet from the link -- until the write has completed. local p = link.front(l) local len, err = S.write(self.sock, p.data, p.length) -- errno == EAGAIN indicates that the write would of blocked if not len and err.errno ~= const.E.AGAIN or len and len ~= p.length then error("Failed write on " .. self.name .. tostring(err)) end if len ~= p.length and err.errno == const.E.AGAIN then return end counter.add(self.shm.txbytes, len) counter.add(self.shm.txpackets) if ethernet:is_mcast(p.data) then counter.add(self.shm.txmcast) end if ethernet:is_bcast(p.data) then counter.add(self.shm.txbcast) end -- The write completed so dequeue it from the link and free the packet link.receive(l) packet.free(p) end end function Tap:stop() self.sock:close() end function selftest() -- tapsrc and tapdst are bridged together in linux. Packets are sent out of tapsrc and they are expected -- to arrive back on tapdst. -- The linux bridge does mac address learning so some care must be taken with the preparation of selftest.cap -- A mac address should appear only as the source address or destination address -- This test should only be run from inside apps/tap/selftest.sh if not os.getenv("SNABB_TAPTEST") then os.exit(engine.test_skipped_code) end local Synth = require("apps.test.synth").Synth local Match = require("apps.test.match").Match local c = config.new() config.app(c, "tap_in", Tap, "tapsrc") config.app(c, "tap_out", Tap, "tapdst") config.app(c, "match", Match, {fuzzy=true,modest=true}) config.app(c, "comparator", Synth, {dst="00:50:56:fd:19:ca", src="00:0c:29:3e:ca:7d"}) config.app(c, "source", Synth, {dst="00:50:56:fd:19:ca", src="00:0c:29:3e:ca:7d"}) config.link(c, "comparator.output->match.comparator") config.link(c, "source.output->tap_in.input") config.link(c, "tap_out.output->match.rx") engine.configure(c) engine.main({duration = 0.01, report = {showapps=true,showlinks=true}}) assert(#engine.app_table.match:errors() == 0) end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local link = require("core.link") local packet = require("core.packet") local counter = require("core.counter") local ethernet = require("lib.protocol.ethernet") local ffi = require("ffi") local C = ffi.C local const = require("syscall.linux.constants") local os = require("os") local t = S.types.t Tap = { } function Tap:new (name) assert(name, "missing tap interface name") local sock, err = S.open("/dev/net/tun", "rdwr, nonblock"); assert(sock, "Error opening /dev/net/tun: " .. tostring(err)) local ifr = t.ifreq() ifr.flags = "tap, no_pi" ifr.name = name local ok, err = sock:ioctl("TUNSETIFF", ifr) if not ok then sock:close() error("Error opening /dev/net/tun: " .. tostring(err)) end return setmetatable({sock = sock, name = name, pkt = packet.allocate(), shm = { rxbytes = {counter}, rxpackets = {counter}, rxmcast = {counter}, rxbcast = {counter}, txbytes = {counter}, txpackets = {counter}, txmcast = {counter}, txbcast = {counter} }}, {__index = Tap}) end function Tap:pull () local l = self.output.output if l == nil then return end for i=1,engine.pull_npackets do local len, err = S.read(self.sock, self.pkt.data, C.PACKET_PAYLOAD_SIZE) -- errno == EAGAIN indicates that the read would of blocked as there is no -- packet waiting. It is not a failure. if not len and err.errno == const.E.AGAIN then return end if not len then error("Failed read on " .. self.name .. ": " .. tostring(err)) end self.pkt.length = len link.transmit(l, self.pkt) counter.add(self.shm.rxbytes, len) counter.add(self.shm.rxpackets) if ethernet:is_mcast(self.pkt.data) then counter.add(self.shm.rxmcast) end if ethernet:is_bcast(self.pkt.data) then counter.add(self.shm.rxbcast) end self.pkt = packet.allocate() end end function Tap:push () local l = self.input.input while not link.empty(l) do -- The socket write might of blocked so don't dequeue the packet from the link -- until the write has completed. local p = link.front(l) local len, err = S.write(self.sock, p.data, p.length) -- errno == EAGAIN indicates that the write would of blocked if not len and err.errno ~= const.E.AGAIN or len and len ~= p.length then error("Failed write on " .. self.name .. tostring(err)) end if len ~= p.length and err.errno == const.E.AGAIN then return end counter.add(self.shm.txbytes, len) counter.add(self.shm.txpackets) if ethernet:is_mcast(p.data) then counter.add(self.shm.txmcast) end if ethernet:is_bcast(p.data) then counter.add(self.shm.txbcast) end -- The write completed so dequeue it from the link and free the packet link.receive(l) packet.free(p) end end function Tap:stop() self.sock:close() end function selftest() -- tapsrc and tapdst are bridged together in linux. Packets are sent out of tapsrc and they are expected -- to arrive back on tapdst. -- The linux bridge does mac address learning so some care must be taken with the preparation of selftest.cap -- A mac address should appear only as the source address or destination address -- This test should only be run from inside apps/tap/selftest.sh if not os.getenv("SNABB_TAPTEST") then os.exit(engine.test_skipped_code) end local Synth = require("apps.test.synth").Synth local Match = require("apps.test.match").Match local c = config.new() config.app(c, "tap_in", Tap, "tapsrc") config.app(c, "tap_out", Tap, "tapdst") config.app(c, "match", Match, {fuzzy=true,modest=true}) config.app(c, "comparator", Synth, {dst="00:50:56:fd:19:ca", src="00:0c:29:3e:ca:7d"}) config.app(c, "source", Synth, {dst="00:50:56:fd:19:ca", src="00:0c:29:3e:ca:7d"}) config.link(c, "comparator.output->match.comparator") config.link(c, "source.output->tap_in.input") config.link(c, "tap_out.output->match.rx") engine.configure(c) engine.main({duration = 0.01, report = {showapps=true,showlinks=true}}) assert(#engine.app_table.match:errors() == 0) end
The last fix for allocating on every breath actually broke under load, this one does not
The last fix for allocating on every breath actually broke under load, this one does not
Lua
apache-2.0
wingo/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,kbara/snabb,mixflowtech/logsensor,Igalia/snabbswitch,eugeneia/snabb,wingo/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,snabbco/snabb,dpino/snabb,eugeneia/snabb,heryii/snabb,kbara/snabb,eugeneia/snabbswitch,dpino/snabb,wingo/snabb,snabbco/snabb,dpino/snabbswitch,heryii/snabb,eugeneia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,wingo/snabb,dpino/snabb,Igalia/snabbswitch,Igalia/snabb,Igalia/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabb,Igalia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,wingo/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,dpino/snabb,kbara/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,heryii/snabb,wingo/snabb,Igalia/snabb,SnabbCo/snabbswitch,eugeneia/snabbswitch,wingo/snabb,kbara/snabb,wingo/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,kbara/snabb,Igalia/snabb,mixflowtech/logsensor,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,kbara/snabb,wingo/snabbswitch,heryii/snabb,snabbco/snabb,Igalia/snabbswitch,mixflowtech/logsensor,Igalia/snabb,heryii/snabb,dpino/snabb,wingo/snabb,dpino/snabb,eugeneia/snabb,Igalia/snabb
a14049f39d29c57b654bacab033948fd7996022e
nyagos.d/suffix.lua
nyagos.d/suffix.lua
share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else print(args[i].."="..(share._suffixes[args[i]] or "")) end end end
share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end
Fix: `suffix ps1` => ?:-1: attempt to concatenate a table value
Fix: `suffix ps1` => ?:-1: attempt to concatenate a table value
Lua
bsd-3-clause
nocd5/nyagos,tyochiai/nyagos,zetamatta/nyagos,tsuyoshicho/nyagos
566171eacc29dbc3e59652b9805ac4fedbbcd28b
scripts/shaderc.lua
scripts/shaderc.lua
-- -- Copyright 2010-2016 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- project "glslang" kind "StaticLib" 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 { "not osx" } buildoptions { "-Wno-unused-but-set-variable", } configuration {} includedirs { "../3rdparty/glslang", } files { "../3rdparty/glslang/glslang/**.cpp", "../3rdparty/glslang/glslang/**.h", "../3rdparty/glslang/hlsl/**.cpp", "../3rdparty/glslang/hlsl/**.h", "../3rdparty/glslang/SPIRV/**.cpp", "../3rdparty/glslang/SPIRV/**.h", "../3rdparty/glslang/OGLCompilersDLL/**.cpp", "../3rdparty/glslang/OGLCompilersDLL/**.h", "../3rdparty/glsl-parser/**.cpp", "../3rdparty/glsl-parser/**.h", } removefiles { "../3rdparty/glslang/glslang/OSDependent/Windows/**.cpp", "../3rdparty/glslang/glslang/OSDependent/Windows/**.h", "../3rdparty/glsl-parser/main.cpp", } 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"), } 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 {} 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-2016 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- project "glslang" kind "StaticLib" 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 { "not osx" } buildoptions { "-Wno-unused-but-set-variable", } configuration {} includedirs { "../3rdparty/glslang", } files { "../3rdparty/glslang/glslang/**.cpp", "../3rdparty/glslang/glslang/**.h", "../3rdparty/glslang/hlsl/**.cpp", "../3rdparty/glslang/hlsl/**.h", "../3rdparty/glslang/SPIRV/**.cpp", "../3rdparty/glslang/SPIRV/**.h", "../3rdparty/glslang/OGLCompilersDLL/**.cpp", "../3rdparty/glslang/OGLCompilersDLL/**.h", "../3rdparty/glsl-parser/**.cpp", "../3rdparty/glsl-parser/**.h", } removefiles { "../3rdparty/glslang/glslang/OSDependent/Windows/**.cpp", "../3rdparty/glslang/glslang/OSDependent/Windows/**.h", "../3rdparty/glsl-parser/main.cpp", } 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"), } 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 {} 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
bkaradzic/bgfx,MikePopoloski/bgfx,jdryg/bgfx,attilaz/bgfx,jdryg/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,septag/bgfx,fluffyfreak/bgfx,septag/bgfx,mmicko/bgfx,bkaradzic/bgfx,jpcy/bgfx,emoon/bgfx,septag/bgfx,attilaz/bgfx,fluffyfreak/bgfx,emoon/bgfx,mendsley/bgfx,fluffyfreak/bgfx,LWJGL-CI/bgfx,Synxis/bgfx,Synxis/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,Synxis/bgfx,mmicko/bgfx,MikePopoloski/bgfx,jpcy/bgfx,jdryg/bgfx,mendsley/bgfx,attilaz/bgfx,jdryg/bgfx,fluffyfreak/bgfx,bkaradzic/bgfx,mendsley/bgfx,bkaradzic/bgfx,mmicko/bgfx,jpcy/bgfx,emoon/bgfx,jpcy/bgfx
c552131c3d1f752e8f42d3503c971b4dfe579a98
apps/yodnsconf/scripts/lua/domain_list.lua
apps/yodnsconf/scripts/lua/domain_list.lua
--[[ <!-- Program: YoDNSConf Component: domain_list.lua Copyright: Savonix Corporation Author: Albert L. Lash, IV License: Gnu Affero Public License version 3 http://www.gnu.org/licenses This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA --> --]] require "luasql.mysql" require "config" env = assert (luasql.mysql()) con = assert (env:connect(dbconfig["database"],dbconfig["username"],dbconfig["password"],dbconfig["hostname"])) function rows (connection, sql_statement) local cursor = assert (connection:execute (sql_statement)) return function () return cursor:fetch() end end for origin,ns,mbox,refresh,retry,minimum,ttl,expire,serial,id in rows (con, "select origin,ns,mbox,refresh,retry,minimum,ttl,expire,serial,id from soa WHERE serial>="..os.date("%Y%m%d00")) do myzone = "$ORIGIN "..origin.."\n".."$TTL 12h\n" myzone = myzone..origin.." IN SOA "..ns.." "..mbox.." (" myzone = myzone.."\n\t\t"..serial myzone = myzone.."\n\t\t"..refresh myzone = myzone.."\n\t\t"..retry myzone = myzone.."\n\t\t"..expire myzone = myzone.."\n\t\t"..minimum.."\n\t\t)" for name,data,ttl in rows (con, "select name,data,ttl from rr WHERE zone="..id) do myzone = myzone..name.." IN "..ttl if (type == "MX") then myzone = myzone .." "..aux end if (type == "SRV") then myzone = myzone .." "..aux.." "..weight.." "..port end if (type == "TXT") then myzone = myzone .." \""..data.."\"" else myzone = myzone.." "..data end myzone = myzone.."\n" end F = io.open("zones/"..origin..".zone.","w") F:write(string.format ("%s", myzone)) F:close() end
--[[ <!-- Program: YoDNSConf Component: domain_list.lua Copyright: Savonix Corporation Author: Albert L. Lash, IV License: Gnu Affero Public License version 3 http://www.gnu.org/licenses This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA --> --]] require "luasql.mysql" require "config" env = assert (luasql.mysql()) con = assert (env:connect(dbconfig["database"],dbconfig["username"],dbconfig["password"],dbconfig["hostname"])) function rows (connection, sql_statement) local cursor = assert (connection:execute (sql_statement)) return function () return cursor:fetch() end end for origin,ns,mbox,refresh,retry,minimum,ttl,expire,serial,id in rows (con, "select origin,ns,mbox,refresh,retry,minimum,ttl,expire,serial,id from soa WHERE serial>="..os.date("%Y%m%d00")) do myzone = "$ORIGIN "..origin.."\n".."$TTL 12h\n" myzone = myzone..origin.." IN SOA "..ns.." "..mbox.." (" myzone = myzone.."\n\t\t"..serial myzone = myzone.."\n\t\t"..refresh myzone = myzone.."\n\t\t"..retry myzone = myzone.."\n\t\t"..expire myzone = myzone.."\n\t\t"..minimum.."\n\t\t)" for name,data,ttl,type,aux,weight,port in rows (con, "select name,data,ttl,type,aux,weight,port from rr WHERE zone="..id) do myzone = myzone..name.." IN "..ttl.." "..type if (type == "MX") then myzone = myzone .." "..aux end if (type == "SRV") then myzone = myzone .." "..aux.." "..weight.." "..port end if (type == "TXT") then myzone = myzone .." \""..data.."\"" else myzone = myzone.." "..data end myzone = myzone.."\n" end F = io.open("zones/"..origin.."zone.","w") F:write(string.format ("%s", myzone)) F:close() --print (string.format ("%s", myzone)) end
fixed minor oversight about records
fixed minor oversight about records
Lua
agpl-3.0
savonix/yodnsconf,savonix/yodnsconf,savonix/yodnsconf,savonix/yodnsconf
f7b9bb75af8d65ea9f2ed445516d8f0e22a4b8ac
init.lua
init.lua
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local uv = require('uv') return function (main, ...) -- Inject the global process table _G.process = require('process').globalProcess() -- Seed Lua's RNG do local math = require('math') local os = require('os') math.randomseed(os.time()) end -- Load Resolver do local dns = require('dns') dns.loadResolver() end -- EPIPE ignore do if jit.os ~= 'Windows' then local sig = uv.new_signal() uv.signal_start(sig, 'sigpipe') uv.unref(sig) end end local args = {...} local success, err = xpcall(function () -- Call the main app main(unpack(args)) -- Start the event loop uv.run() end, function(err) require('hooks'):emit('process.uncaughtException',err) return debug.traceback(err) end) if success then -- Allow actions to run at process exit. require('hooks'):emit('process.exit') uv.run() else _G.process.exitCode = -1 require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n") end local function isFileHandle(handle, name, fd) return _G.process[name].handle == handle and uv.guess_handle(fd) == 'file' end local function isStdioFileHandle(handle) return isFileHandle(handle, 'stdin', 0) or isFileHandle(handle, 'stdout', 1) or isFileHandle(handle, 'stderr', 2) end -- When the loop exits, close all unclosed uv handles (flushing any streams found). uv.walk(function (handle) if handle then local function close() if not handle:is_closing() then handle:close() end end -- The isStdioFileHandle check is a hacky way to avoid an abort when a stdio handle is a pipe to a file -- TODO: Fix this in a better way, see https://github.com/luvit/luvit/issues/1094 if handle.shutdown and not isStdioFileHandle(handle) then handle:shutdown(close) else close() end end end) uv.run() -- Send the exitCode to luvi to return from C's main. return _G.process.exitCode end
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local uv = require('uv') return function (main, ...) -- Inject the global process table _G.process = require('process').globalProcess() -- Seed Lua's RNG do local math = require('math') local os = require('os') math.randomseed(os.time()) end -- Load Resolver do local dns = require('dns') dns.loadResolver() end -- EPIPE ignore do if jit.os ~= 'Windows' then local sig = uv.new_signal() uv.signal_start(sig, 'sigpipe') uv.unref(sig) end end local args = {...} local success, err = xpcall(function () -- Call the main app main(unpack(args)) -- Start the event loop uv.run() end, function(err) -- During a stack overflow error, this can fail due to exhausting the remaining stack. -- We can't recover from that failure, but wrapping it in a pcall allows us to still -- return the stack overflow error even if the 'process.uncaughtException' fails to emit pcall(function() require('hooks'):emit('process.uncaughtException',err) end) return debug.traceback(err) end) if success then -- Allow actions to run at process exit. require('hooks'):emit('process.exit') uv.run() else _G.process.exitCode = -1 require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n") end local function isFileHandle(handle, name, fd) return _G.process[name].handle == handle and uv.guess_handle(fd) == 'file' end local function isStdioFileHandle(handle) return isFileHandle(handle, 'stdin', 0) or isFileHandle(handle, 'stdout', 1) or isFileHandle(handle, 'stderr', 2) end -- When the loop exits, close all unclosed uv handles (flushing any streams found). uv.walk(function (handle) if handle then local function close() if not handle:is_closing() then handle:close() end end -- The isStdioFileHandle check is a hacky way to avoid an abort when a stdio handle is a pipe to a file -- TODO: Fix this in a better way, see https://github.com/luvit/luvit/issues/1094 if handle.shutdown and not isStdioFileHandle(handle) then handle:shutdown(close) else close() end end end) uv.run() -- Send the exitCode to luvi to return from C's main. return _G.process.exitCode end
Mitigate bogus errors being returned on stack overflows (#1102)
Mitigate bogus errors being returned on stack overflows (#1102) This is one possible way to fix #1101; it means that some stack overflow errors would never get emitted via 'process.uncaughtException'. The alternative would be to reduce the amount of work that needs to be done for emitting 'process.uncaughtException' in order to avoid the stack exhaustion. Closes #1101
Lua
apache-2.0
luvit/luvit,zhaozg/luvit,zhaozg/luvit,luvit/luvit
6c613918f1eca3a565cbcaf39014af94b3170a7f
src/ui/MainMenuView.lua
src/ui/MainMenuView.lua
local class = require 'lib/30log' local GameObject = require 'src/GameObject' local Transform = require 'src/component/Transform' local Renderable = require 'src/component/Renderable' local Interfaceable = require 'src/component/Interfaceable' local Polygon = require 'src/datatype/Polygon' local TouchDelegate = require 'src/datatype/TouchDelegate' local MainMenuView = class("MainMenuView", { root = nil, is_attached = false, scenegraph = nil }) function MainMenuView:init (registry, scenegraph) self.root = registry:add(GameObject:new("mmv_root", { Transform:new(0,0) })) self.scenegraph = scenegraph self.registry = registry local save_button_handler = TouchDelegate:new() save_button_handler:setHandler('onTouch', function(this, x, y) print('Button pressed: save') end) local load_button_handler = TouchDelegate:new() load_button_handler:setHandler('onTouch', function(this, x, y) print('Button pressed: load. Loading disabled for the moment') self:hide() end) local return_button_handler = TouchDelegate:new() return_button_handler:setHandler('onTouch', function(this, x, y) self.scenegraph:detach(self.root) self.is_attached = false print('Button pressed: return') end) local quit_button_handler = TouchDelegate:new() quit_button_handler:setHandler('onTouch', function(this, x, y) love.event.quit() end) local switch_next_handler = TouchDelegate:new() switch_next_handler:setHandler('onTouch', function(this, x, y) registry:publish("ui/debug_nextscene") self:hide() end) local switch_prev_handler = TouchDelegate:new() switch_prev_handler:setHandler('onTouch', function(this, x, y) registry:publish("ui/debug_prevscene") self:hide() end) local Block_Below_Delegate = TouchDelegate:new() Block_Below_Delegate:setHandler('onTouch', function(this, x, y) print('Blocking event') return true end) local windowW = love.graphics:getWidth() local windowH = love.graphics:getHeight() local gray_out = registry:add(GameObject:new("mmv_grayout", { Transform:new(0,0), Renderable:new( Polygon:new({w = windowW, h = windowH}), nil, {0,0,0,128}, math.floor(math.random()*100000)), Interfaceable:new( Polygon:new({w = windowW, h = windowH}), Block_Below_Delegate) })) local panelW = 400 local panelH = 600 local panelX = ( windowW - panelW ) / 2 local panelY = ( windowH - panelH ) / 2 local margin = 10 local bg_rect = registry:add(GameObject:new("mmv_bgrect", { Transform:new(panelX,panelY), Renderable:new( Polygon:new({w = panelW, h = panelH}), nil, {128, 60, 128}) })) local subPanelW = panelW - 2 * margin local buttonW = subPanelW - 2 * margin local titleH = 40 local title_panel = registry:add(GameObject:new("mmv_title",{ Transform:new(margin,margin), Renderable:new( Polygon:new({w = subPanelW, h = titleH}), nil, {200,100,200}, "HELIOS 2400 DEBUG MENU") })) local saveLoadY = titleH + 2 * margin local buttonH = 30 local bigMargin = 40 local saveLoadH = buttonH * 4 + margin * 4 + bigMargin local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{ Transform:new(margin,saveLoadY), Renderable:new( Polygon:new({w = subPanelW, h = saveLoadH}), nil, {200,100,200}) })) local save_btn = registry:add(GameObject:new("mmv_save_btn",{ Transform:new(margin, margin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Save Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), save_button_handler) })) local load_btn = registry:add(GameObject:new("mmv_load_btn",{ Transform:new(margin, margin + buttonH + margin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Load Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), load_button_handler) })) local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{ Transform:new(margin , margin + (buttonH + margin) * 2), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Quit Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), quit_button_handler) })) local return_btn = registry:add(GameObject:new("mmv_return_btn",{ Transform:new(margin , margin + buttonH * 3 + margin * 2 + bigMargin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Return (or press Escape)"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), return_button_handler) })) local switchButtonH = 60 local view_switcher_panelH = switchButtonH + 2 * margin local view_switcher_panelY = saveLoadY + saveLoadH + margin local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{ Transform:new(margin,view_switcher_panelY), Renderable:new( Polygon:new({w = subPanelW, h = view_switcher_panelH}), nil, {200,100,200}, nil) })) local switchButtonW = (subPanelW - margin) / 2 local AHO = switchButtonH/4 local AHW = switchButtonW/4 local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{ Transform:new(margin,margin), Renderable:new( Polygon:new({ 0,switchButtonH/2, AHW,0, AHW,AHO, switchButtonW,AHO, switchButtonW,switchButtonH-AHO, AHW,switchButtonH-AHO, AHW,switchButtonH} ), nil, {150,100,180}, "Previous View"), Interfaceable:new( Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}), switch_prev_handler) })) local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{ Transform:new(2 * margin + switchButtonW,margin), Renderable:new( Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}), nil, {150,100,180}, "Next View"), Interfaceable:new( Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}), switch_next_handler) })) self.scenegraph:attach(self.root, nil) self.scenegraph:attachAll({gray_out, bg_rect}, self.root) self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect) self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel) self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel) self.scenegraph:detach(self.root) end function MainMenuView:show( attachTo ) if not self.is_attached then self.scenegraph:attach(self.root, attachTo) self.is_attached = true end end function MainMenuView:hide() if self.is_attached then self.scenegraph:detach(self.root) self.is_attached = false end end return MainMenuView
local class = require 'lib/30log' local GameObject = require 'src/GameObject' local Transform = require 'src/component/Transform' local Renderable = require 'src/component/Renderable' local Interfaceable = require 'src/component/Interfaceable' local Polygon = require 'src/datatype/Polygon' local TouchDelegate = require 'src/datatype/TouchDelegate' local MainMenuView = class("MainMenuView", { root = nil, is_attached = false, scenegraph = nil }) function MainMenuView:init (registry, scenegraph) self.root = registry:add(GameObject:new("mmv_root", { Transform:new(0,0) })) self.scenegraph = scenegraph self.registry = registry local save_button_handler = TouchDelegate:new() save_button_handler:setHandler('onTouch', function(this, x, y) print('Button pressed: save') end) local load_button_handler = TouchDelegate:new() load_button_handler:setHandler('onTouch', function(this, x, y) print('Button pressed: load. Loading disabled for the moment') self:hide() end) local return_button_handler = TouchDelegate:new() return_button_handler:setHandler('onTouch', function(this, x, y) self.scenegraph:detach(self.root) self.is_attached = false print('Button pressed: return') end) local quit_button_handler = TouchDelegate:new() quit_button_handler:setHandler('onTouch', function(this, x, y) love.event.quit() end) local switch_next_handler = TouchDelegate:new() switch_next_handler:setHandler('onTouch', function(this, x, y) registry:publish("ui/debug_nextscene") self:hide() end) local switch_prev_handler = TouchDelegate:new() switch_prev_handler:setHandler('onTouch', function(this, x, y) registry:publish("ui/debug_prevscene") self:hide() end) local Block_Below_Delegate = TouchDelegate:new() Block_Below_Delegate:setHandler('onTouch', function(this, x, y) print('Blocking event') return true end) local windowW = love.graphics:getWidth() local windowH = love.graphics:getHeight() local gray_out = registry:add(GameObject:new("mmv_grayout", { Transform:new(0,0), Renderable:new( Polygon:new({w = windowW, h = windowH}), nil, {0,0,0,128}, math.floor(math.random()*100000)), Interfaceable:new( Polygon:new({w = windowW, h = windowH}), Block_Below_Delegate) })) local panelW = 400 local panelH = 600 local panelX = ( windowW - panelW ) / 2 local panelY = ( windowH - panelH ) / 2 local margin = 10 local bg_rect = registry:add(GameObject:new("mmv_bgrect", { Transform:new(panelX,panelY), Renderable:new( Polygon:new({w = panelW, h = panelH}), nil, {128, 60, 128}) })) local subPanelW = panelW - 2 * margin local buttonW = subPanelW - 2 * margin local titleH = 40 local title_panel = registry:add(GameObject:new("mmv_title",{ Transform:new(margin,margin), Renderable:new( Polygon:new({w = subPanelW, h = titleH}), nil, {200,100,200}, "HELIOS 2400 DEBUG MENU") })) local saveLoadY = titleH + 2 * margin local buttonH = 30 local bigMargin = 40 local saveLoadH = buttonH * 4 + margin * 4 + bigMargin local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{ Transform:new(margin,saveLoadY), Renderable:new( Polygon:new({w = subPanelW, h = saveLoadH}), nil, {200,100,200}) })) local save_btn = registry:add(GameObject:new("mmv_save_btn",{ Transform:new(margin, margin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Save Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), save_button_handler) })) local load_btn = registry:add(GameObject:new("mmv_load_btn",{ Transform:new(margin, margin + buttonH + margin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Load Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), load_button_handler) })) local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{ Transform:new(margin , margin + (buttonH + margin) * 2), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Quit Game"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), quit_button_handler) })) local return_btn = registry:add(GameObject:new("mmv_return_btn",{ Transform:new(margin , margin + buttonH * 3 + margin * 2 + bigMargin), Renderable:new( Polygon:new({w = buttonW, h = buttonH}), nil, {150,100,180}, "Return (or press Escape)"), Interfaceable:new( Polygon:new({w = buttonW, h = buttonH}), return_button_handler) })) local switchButtonH = 60 local view_switcher_panelH = switchButtonH + 2 * margin local view_switcher_panelY = saveLoadY + saveLoadH + margin local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{ Transform:new(margin,view_switcher_panelY), Renderable:new( Polygon:new({w = subPanelW, h = view_switcher_panelH}), nil, {200,100,200}, nil) })) local switchButtonW = (subPanelW - 3 * margin) / 2 local AHO = switchButtonH/4 local AHW = switchButtonW/4 local prevPoly = Polygon:new({ 0,switchButtonH/2, AHW,0, AHW,AHO, switchButtonW,AHO, switchButtonW,switchButtonH-AHO, AHW,switchButtonH-AHO, AHW,switchButtonH} ) local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{ Transform:new(margin,margin), Renderable:new( prevPoly, nil, {150,100,180}, "Previous View"), Interfaceable:new( prevPoly, switch_prev_handler) })) local nextPoly = Polygon:new({ switchButtonW,switchButtonH/2, switchButtonW - AHW,0, switchButtonW - AHW,AHO, 0,AHO, 0,switchButtonH-AHO, switchButtonW - AHW,switchButtonH-AHO, switchButtonW - AHW,switchButtonH} ) local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{ Transform:new(2 * margin + switchButtonW,margin), Renderable:new( nextPoly, nil, {150,100,180}, "Next View"), Interfaceable:new( nextPoly, switch_next_handler) })) self.scenegraph:attach(self.root, nil) self.scenegraph:attachAll({gray_out, bg_rect}, self.root) self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect) self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel) self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel) self.scenegraph:detach(self.root) end function MainMenuView:show( attachTo ) if not self.is_attached then self.scenegraph:attach(self.root, attachTo) self.is_attached = true end end function MainMenuView:hide() if self.is_attached then self.scenegraph:detach(self.root) self.is_attached = false end end return MainMenuView
fixed scaling of left and right arrows
fixed scaling of left and right arrows
Lua
mit
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
02e19830508c06ef26ae08656e8fdb46e553c6b1
interface/options/mode.lua
interface/options/mode.lua
local function get_update_delay_one(flow) return function() flow.updatePacket = flow._update_packet flow._update_packet = nil end end local function _random(dv, pkt) local index = math.random(dv.count) dv[index]:update() dv:applyAll(pkt) end local function _random_alt(dv, pkt) local index = math.random(dv.count) dv[index]:updateApply(pkt) end local function _all(dv, pkt) dv:updateApplyAll(pkt) end local _valid_modes = { single = function() local index = 0 return function(dv, pkt) dv[index + 1]:update() dv:applyAll(pkt) index = incAndWrap(index, dv.count) -- luacheck: globals incAndWrap end end, alternating = function() local index = 0 return function(dv, pkt) dv[index + 1]:updateApply(pkt) index = incAndWrap(index, dv.count) -- luacheck: globals incAndWrap end end, random = function() return _random end, random_alt = function() return _random_alt end, all = function() return _all end, } local _modelist = { "none" } for i in pairs(_valid_modes) do table.insert(_modelist, i) end local option = {} option.description = "Control how fields of dynamic flows are updated and applied." option.configHelp = "Will also accept a function that will be called for each" .. " packet sent but the first. Use closures for flow control purposes." .. " The following function demonstrates the available api:\n\n" .. [[function mode(dynvars, packet) -- available api dynvars[1]:update() dynvars[1]:apply(packet) dynvars[1]:updateApply(packet) -- convenience api dynvars:updateAll() dynvars:applyAll(packet) dynvars:updateApplyAll(packet) end]] .. "\n\nSingle dynvars can also be accessed by name using" .. " 'dynvars.index.<pktVar>' (e.g. udpSrc)." option.usage = { { "none", "Ignore all dynamic fields and send the first packet created." }, { "single", "Update one field at a time, but apply every change so far." }, { "alternating", "Update and apply one field at a time." }, { "random", "Like single, but the order of updates is not fixed."}, { "random_alt", "Like alternating, but the order of updates is not fixed."}, { "all", "Update and apply all fields every time."}, } option.formatString = {} for _,v in ipairs(_modelist) do table.insert(option.formatString, v) end option.formatString = "<" .. table.concat(option.formatString, "|") .. ">" option.helpString = "Change how dynamic fields are updated. (default = single)" -- TODO add value documentation function option.parse(self, mode, error) if #self.packet.dynvars == 0 then error:assert(not mode or mode == "none", "Value set, but no dynvars in associated packet.") return elseif mode == "none" then return end -- Don't change the first packet self.updatePacket = get_update_delay_one(self) local t = type(mode) if t == "string" then mode = _valid_modes[string.lower(mode)] if error:assert(mode, "Invalid value %q. Can be one of %s.", mode, table.concat(_modelist, ", ")) then mode = mode() end elseif t ~= "function" and t ~= "nil" then error("Invalid argument. String or function expected, got %s.", t) end self._update_packet = mode or _valid_modes.single() end return option
local function get_update_delay_one(flow) return function() flow.updatePacket = flow._update_packet flow._update_packet = nil end end local function _random(dv, pkt) local index = math.random(dv.count) dv[index]:update() dv:applyAll(pkt) end local function _random_alt(dv, pkt) local index = math.random(dv.count) dv[index]:updateApply(pkt) end local function _all(dv, pkt) dv:updateApplyAll(pkt) end local _valid_modes = { single = function() local index = 0 return function(dv, pkt) dv[index + 1]:update() dv:applyAll(pkt) index = incAndWrap(index, dv.count) -- luacheck: globals incAndWrap end end, alternating = function() local index = 0 return function(dv, pkt) dv[index + 1]:updateApply(pkt) index = incAndWrap(index, dv.count) -- luacheck: globals incAndWrap end end, random = function() return _random end, random_alt = function() return _random_alt end, all = function() return _all end, } local _modelist = { "none" } for i in pairs(_valid_modes) do table.insert(_modelist, i) end local option = {} option.description = "Control how fields of dynamic flows are updated and applied." option.configHelp = "Will also accept a function that will be called for each" .. " packet sent but the first. Use closures for flow control purposes." .. " The following function demonstrates the available api:\n\n" .. [[function mode(dynvars, packet) -- available api dynvars[1]:update() dynvars[1]:apply(packet) dynvars[1]:updateApply(packet) -- convenience api dynvars:updateAll() dynvars:applyAll(packet) dynvars:updateApplyAll(packet) end]] .. "\n\nSingle dynvars can also be accessed by name using" .. " 'dynvars.index.<pktVar>' (e.g. udpSrc)." option.usage = { { "none", "Ignore all dynamic fields and send the first packet created." }, { "single", "Update one field at a time, but apply every change so far." }, { "alternating", "Update and apply one field at a time." }, { "random", "Like single, but the order of updates is not fixed."}, { "random_alt", "Like alternating, but the order of updates is not fixed."}, { "all", "Update and apply all fields every time."}, } option.formatString = {} for _,v in ipairs(_modelist) do table.insert(option.formatString, v) end option.formatString = "<" .. table.concat(option.formatString, "|") .. ">" option.helpString = "Change how dynamic fields are updated. (default = single)" -- TODO add value documentation function option.parse(self, mode, error) if #self.packet.dynvars == 0 then error:assert(not mode or mode == "none", "Value set, but no dynvars in associated packet.") return elseif mode == "none" then return end -- Don't change the first packet self.updatePacket = get_update_delay_one(self) local t = type(mode) if t == "string" then mode = error:assert(_valid_modes[string.lower(mode)], "Invalid value %q. Can be one of %s.", mode, table.concat(_modelist, ", ")) if mode then mode = mode() end elseif t ~= "function" and t ~= "nil" then error("Invalid argument. String or function expected, got %s.", t) end self._update_packet = mode or _valid_modes.single() end return option
Fix error message for invalid mode.
Fix error message for invalid mode.
Lua
mit
gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,emmericp/MoonGen
be65e83fb6d0aaa8b2842c9f584b3d85abcff011
TemporalConvolution.lua
TemporalConvolution.lua
local TemporalConvolution, parent = torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution') --use cudnn to perform temporal convolutions --note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution --however, instead of separately padding data, as is required now for nn.TemporalConvolution, --it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities. --limitation is that padding will be equal on both sides. function TemporalConvolution:__init(inputFrameSize, outputFrameSize, kH, dH, padH) local delayedReset = self.reset local kW = inputFrameSize local nInputPlane = 1 -- single channel local nOutputPlane = outputFrameSize self.inputFrameSize = inputFrameSize self.outputFrameSize = outputFrameSize cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH) self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH) self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH) --self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because --W and H are switched in temporal and spatial end function TemporalConvolution:createIODescriptors(input) local sizeChanged = false if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then sizeChanged = true end cudnn.SpatialConvolution.createIODescriptors(self,input) if sizeChanged then self.oSize = self.output:size() end end function TemporalConvolution:fastest(mode) self = cudnn.SpatialConvolution.fastest(self,mode) return self end function TemporalConvolution:resetWeightDescriptors() cudnn.SpatialConvolution.resetWeightDescriptors(self) end local function inputview(input) local _input = input if input:dim()==2 then _input = input:view(1,input:size(1),input:size(2)) end return _input:view(_input:size(1),1,_input:size(2),_input:size(3)) end function TemporalConvolution:updateOutput(input) local _input = inputview(input) assert(_input:size(4) == self.inputFrameSize,'invalid input frame size') self.buffer = self.buffer or torch.CudaTensor() self._output = self._output or torch.CudaTensor() if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end if self.buffer:storage() then self.output:set(self.buffer:storage(), 1, self.output:size()) else self.output = self.buffer end cudnn.SpatialConvolution.updateOutput(self,_input) self.buffer = self.output:view(self.oSize):transpose(2,3) self.output = self._output:resize(self.buffer:size()):copy(self.buffer) -- self.output here is always 4D, use input dimensions to properly view output if input:dim()==3 then self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2]) else self.output=self.output:view(self.oSize[3], self.oSize[2]) end return self.output end local function transposeGradOutput(src,dst) assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D'); local srctransposed = src:transpose(src:dim(),src:dim()-1) dst:resize(srctransposed:size()) dst:copy(srctransposed) if src:dim()==3 then dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1) else dst = dst:view(dst:size(1),dst:size(2),1) end return dst end function TemporalConvolution:updateGradInput(input, gradOutput) if not self.gradInput then return end local _gradOutput = transposeGradOutput(gradOutput,self.buffer) local _input = inputview(input) if input:dim()==3 and self.gradInput:dim() == 3 then self.gradInput = self.gradInput:view(self.gradInput:size(1), 1, self.gradInput:size(2),self.gradInput:size(3)) elseif input:dim() == 2 and self.gradInput:dim() == 2 then self.gradInput = self.gradInput:view(1, 1, self.gradInput:size(1),self.gradInput:size(2)) end self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput) if input:dim()==3 then self.gradInput = self.gradInput:view(self.iSize[1],self.iSize[3],self.iSize[4]) else self.gradInput = self.gradInput:view(self.iSize[3],self.iSize[4]) end return self.gradInput end function TemporalConvolution:accGradParameters(input,gradOutput,scale) --2d (4d) view of input local _input = inputview(input) -- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal local _gradOutput = transposeGradOutput(gradOutput,self.buffer) cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale) end function TemporalConvolution:clearDesc() self.buffer = nil self._output = nil self.oSize = nil end function TemporalConvolution:write(f) self:clearDesc() cudnn.SpatialConvolution.clearDesc(self) local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end function TemporalConvolution:clearState() self:clearDesc() nn.utils.clear(self, '_input', '_gradOutput') return parent.clearState(self) end
local TemporalConvolution, parent = torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution') --use cudnn to perform temporal convolutions --note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution --however, instead of separately padding data, as is required now for nn.TemporalConvolution, --it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities. --limitation is that padding will be equal on both sides. function TemporalConvolution:__init(inputFrameSize, outputFrameSize, kH, dH, padH) local delayedReset = self.reset local kW = inputFrameSize local nInputPlane = 1 -- single channel local nOutputPlane = outputFrameSize self.inputFrameSize = inputFrameSize self.outputFrameSize = outputFrameSize cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH) self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH) self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH) --self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because --W and H are switched in temporal and spatial end function TemporalConvolution:createIODescriptors(input) local sizeChanged = false if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then sizeChanged = true end cudnn.SpatialConvolution.createIODescriptors(self,input) if sizeChanged then self.oSize = self.output:size() end end function TemporalConvolution:fastest(mode) self = cudnn.SpatialConvolution.fastest(self,mode) return self end function TemporalConvolution:resetWeightDescriptors() cudnn.SpatialConvolution.resetWeightDescriptors(self) end local function inputview(input) local _input = input if input:dim()==2 then _input = input:view(1,input:size(1),input:size(2)) end return _input:view(_input:size(1),1,_input:size(2),_input:size(3)) end function TemporalConvolution:updateOutput(input) local _input = inputview(input) assert(_input:size(4) == self.inputFrameSize,'invalid input frame size') self.buffer = self.buffer or torch.CudaTensor() self._output = self._output or torch.CudaTensor() if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end if self.buffer:storage() then self.output:set(self.buffer:storage(), 1, self.output:size()) else self.output = self.buffer end cudnn.SpatialConvolution.updateOutput(self,_input) self.buffer = self.output:view(self.oSize):transpose(2,3) self.output = self._output:resize(self.buffer:size()):copy(self.buffer) -- self.output here is always 4D, use input dimensions to properly view output if input:dim()==3 then self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2]) else self.output=self.output:view(self.oSize[3], self.oSize[2]) end return self.output end local function transposeGradOutput(src,dst) assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D'); local srctransposed = src:transpose(src:dim(),src:dim()-1) dst:resize(srctransposed:size()) dst:copy(srctransposed) if src:dim()==3 then dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1) else dst = dst:view(dst:size(1),dst:size(2),1) end return dst end function TemporalConvolution:updateGradInput(input, gradOutput) if not self.gradInput then return end local _gradOutput = transposeGradOutput(gradOutput,self.buffer) local _input = inputview(input) self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput) if input:dim()==3 then self.gradInput = self.gradInput:view(self.iSize[1],self.iSize[3],self.iSize[4]) else self.gradInput = self.gradInput:view(self.iSize[3],self.iSize[4]) end return self.gradInput end function TemporalConvolution:accGradParameters(input,gradOutput,scale) --2d (4d) view of input local _input = inputview(input) -- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal local _gradOutput = transposeGradOutput(gradOutput,self.buffer) cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale) end function TemporalConvolution:clearDesc() self.buffer = nil self._output = nil self.oSize = nil end function TemporalConvolution:write(f) self:clearDesc() cudnn.SpatialConvolution.clearDesc(self) local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end function TemporalConvolution:clearState() self:clearDesc() nn.utils.clear(self, '_input', '_gradOutput') return parent.clearState(self) end
Update TemporalConvolution.lua
Update TemporalConvolution.lua Cleaner way of what fbesse was doing (thans fbesse!) and typo fix
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
096baefd5a0a7a5af7aaf962936837197293a394
focuspoints.lrdevplugin/OlympusDelegates.lua
focuspoints.lrdevplugin/OlympusDelegates.lua
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ A collection of delegate functions to be passed into the DefaultPointRenderer when the camera is Olympus Assume that focus point metadata look like: AF Areas : (118,32)-(137,49) AF Point Selected : (50%,15%) (50%,15%) Where: AF Point Selected appears to be % of photo from upper left corner (X%, Y%) AF Areas appears to be focus box as coordinates relative to 0..255 from upper left corner (x,y) 2017-01-06 - MJ - Test for 'AF Point Selected' in Metadata, assume it's good if found Add basic errorhandling if not found 2017-01-07 - MJ Use 'AF Areas' tag to size focus box Note that on cameras where it is possible to change the size of the focus box, I.E - E-M1, the metadata doesn't show the true size, so all focus boxes will be the same size. TODO: Verify math by comparing focus point locations with in-camera views. --]] local LrStringUtils = import "LrStringUtils" local LrErrors = import 'LrErrors' require "Utils" OlympusDelegates = {} --[[ -- metaData - the metadata as read by exiftool --]] function OlympusDelegates.getAfPoints(photo, metaData) -- find selected AF point local focusPoint = ExifUtils.findFirstMatchingValue(metaData, { "AF Point Selected" }) if focusPoint == nil then LrErrors.throwUserError("Unsupported Olympus Camera or 'AF Point Selected' metadata tag not found.") return nil end local focusX, focusY = string.match(focusPoint, "%((%d+)%%,(%d+)") if focusX == nil or focusY == nil then LrErrors.throwUserError("Focus point not found in 'AF Point Selected' metadata tag") return nil end log ("Focus %: " .. focusX .. "," .. focusY .. "," .. focusPoint) local orgPhotoWidth, orgPhotoHeight = parseDimens(photo:getFormattedMetadata("dimensions")) if orgPhotoWidth == nil or orgPhotoHeight == nil then LrErrors.throwUserError("Metadata has no Dimensions") return nil end log ( "Focus px: " .. tonumber(orgPhotoWidth) * tonumber(focusX)/100 .. "," .. tonumber(orgPhotoHeight) * tonumber(focusY)/100) -- determine size of bounding box of AF area in image pixels local afArea = ExifUtils.findFirstMatchingValue(metaData, { "AF Areas" }) local afAreaX1, afAreaY1, afAreaX2, afAreaY2 = string.match(afArea, "%((%d+),(%d+)%)%-%((%d+),(%d+)%)" ) local afAreaWidth = 300 local afAreaHeight = 300 if (afAreaX1 ~= nill and afAreaY1 ~= nill and afAreaX2 ~= nill and afAreaY2 ~= nill ) then afAreaWidth = math.floor((tonumber(afAreaX2) - tonumber(afAreaX1)) * tonumber(orgPhotoWidth)/255) afAreaHeight = math.floor((tonumber(afAreaY2) - tonumber(afAreaY1)) * tonumber(orgPhotoHeight)/255) end log ( "Focus Area: " .. afArea .. ", " .. afAreaX1 .. ", " .. afAreaY1 .. ", " .. afAreaX2 .. ", " .. afAreaY2 .. ", " .. afAreaWidth .. ", " .. afAreaHeight ) -- determine x,y location of center of focus point in image pixels local x = math.floor(tonumber(orgPhotoWidth) * tonumber(focusX) / 100) local y = math.floor(tonumber(orgPhotoHeight) * tonumber(focusY) / 100) if orgPhotoWidth < orgPhotoHeight then x = math.floor(tonumber(orgPhotoWidth) * tonumber(y) / 100) y = math.floor(tonumber(orgPhotoHeight) * tonumber(x) / 100) end local result = { pointTemplates = DefaultDelegates.pointTemplates, points = { { pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS, x = x, y = y, width = afAreaWidth, height = afAreaHeight } } } return result end
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ A collection of delegate functions to be passed into the DefaultPointRenderer when the camera is Olympus Assume that focus point metadata look like: AF Areas : (118,32)-(137,49) AF Point Selected : (50%,15%) (50%,15%) Where: AF Point Selected appears to be % of photo from upper left corner (X%, Y%) AF Areas appears to be focus box as coordinates relative to 0..255 from upper left corner (x,y) 2017-01-06 - MJ - Test for 'AF Point Selected' in Metadata, assume it's good if found Add basic errorhandling if not found 2017-01-07 - MJ Use 'AF Areas' tag to size focus box Note that on cameras where it is possible to change the size of the focus box, I.E - E-M1, the metadata doesn't show the true size, so all focus boxes will be the same size. 2017-01-07 - MJ Fix math bug TODO: Verify math by comparing focus point locations with in-camera views. --]] local LrStringUtils = import "LrStringUtils" local LrErrors = import 'LrErrors' require "Utils" OlympusDelegates = {} --[[ -- metaData - the metadata as read by exiftool --]] function OlympusDelegates.getAfPoints(photo, metaData) -- find selected AF point local focusPoint = ExifUtils.findFirstMatchingValue(metaData, { "AF Point Selected" }) if focusPoint == nil then LrErrors.throwUserError("Unsupported Olympus Camera or 'AF Point Selected' metadata tag not found.") return nil end local focusX, focusY = string.match(focusPoint, "%((%d+)%%,(%d+)") if focusX == nil or focusY == nil then LrErrors.throwUserError("Focus point not found in 'AF Point Selected' metadata tag") return nil end log ("Focus %: " .. focusX .. "," .. focusY .. "," .. focusPoint) local orgPhotoWidth, orgPhotoHeight = parseDimens(photo:getFormattedMetadata("dimensions")) if orgPhotoWidth == nil or orgPhotoHeight == nil then LrErrors.throwUserError("Metadata has no Dimensions") return nil end log("Focus px: " .. tonumber(orgPhotoWidth) * tonumber(focusX)/100 .. "," .. tonumber(orgPhotoHeight) * tonumber(focusY)/100) -- determine size of bounding box of AF area in image pixels local afArea = ExifUtils.findFirstMatchingValue(metaData, { "AF Areas" }) local afAreaX1, afAreaY1, afAreaX2, afAreaY2 = string.match(afArea, "%((%d+),(%d+)%)%-%((%d+),(%d+)%)" ) local afAreaWidth = 300 local afAreaHeight = 300 if (afAreaX1 ~= nill and afAreaY1 ~= nill and afAreaX2 ~= nill and afAreaY2 ~= nill ) then afAreaWidth = math.floor((tonumber(afAreaX2) - tonumber(afAreaX1)) * tonumber(orgPhotoWidth)/255) afAreaHeight = math.floor((tonumber(afAreaY2) - tonumber(afAreaY1)) * tonumber(orgPhotoHeight)/255) end log ( "Focus Area: " .. afArea .. ", " .. afAreaX1 .. ", " .. afAreaY1 .. ", " .. afAreaX2 .. ", " .. afAreaY2 .. ", " .. afAreaWidth .. ", " .. afAreaHeight ) -- determine x,y location of center of focus point in image pixels local x = math.floor(tonumber(orgPhotoWidth) * tonumber(focusX) / 100) local y = math.floor(tonumber(orgPhotoHeight) * tonumber(focusY) / 100) if orgPhotoWidth < orgPhotoHeight then x = math.floor(tonumber(orgPhotoWidth) * tonumber(focusY) / 100) y = math.floor(tonumber(orgPhotoHeight) * tonumber(focusX) / 100) end log("FocusXY: " .. x .. ", " .. y) local result = { pointTemplates = DefaultDelegates.pointTemplates, points = { { pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS, x = x, y = y, width = afAreaWidth, height = afAreaHeight } } } return result end
Fix math bug in rotated images
Fix math bug in rotated images
Lua
apache-2.0
mkjanke/Focus-Points,mkjanke/Focus-Points,rderimay/Focus-Points,philmoz/Focus-Points,project802/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,project802/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,philmoz/Focus-Points,rderimay/Focus-Points
d95917ecbc5d0efbc1b4b67c1974d7f0421eebf9
misc/freeswitch/scripts/common/gateway.lua
misc/freeswitch/scripts/common/gateway.lua
-- Gemeinschaft 5 module: gateway class -- (c) AMOOMA GmbH 2013 -- module(...,package.seeall) Gateway = {} -- Create Gateway object function Gateway.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'gateway'; self.log = arg.log; self.database = arg.database; self.record = arg.record; return object; end function Gateway.list(self, technology) technology = technology or 'sip'; local sql_query = 'SELECT * FROM `gateways` WHERE (`outbound` IS TRUE OR `inbound` IS TRUE) AND `technology` = "' .. technology .. '"'; local gateways = {}; self.database:query(sql_query, function(entry) table.insert(gateways, entry); end) return gateways; end function Gateway.find_by_id(self, id) local sql_query = 'SELECT * FROM `gateways` WHERE `id`= ' .. tonumber(id) .. ' LIMIT 1'; local gateway = nil; self.database:query(sql_query, function(entry) gateway = Gateway:new(self); gateway.record = entry; gateway.id = tonumber(entry.id); gateway.name = entry.name; end) if gateway then gateway.settings = self:config_table_get('gateway_settings', gateway.id); end return gateway; end function Gateway.authenticate(self, technology, caller) local sql_query = 'SELECT `c`.`name`, `c`.`id`, `a`.`value` `auth_source`, `b`.`value` `auth_pattern` \ FROM `gateway_settings` `a` \ INNER JOIN `gateway_settings` `b` \ ON (`a`.`gateway_id` = `b`.`gateway_id` AND `a`.`name` = "auth_source" AND `b`.`name` = "auth_pattern" ) \ LEFT JOIN `gateways` `c` \ ON (`a`.`gateway_id` = `c`.`id`) \ WHERE `c`.`inbound` IS TRUE AND `c`.`technology` = "' .. tostring(technology) .. '"'; local gateway = false; self.database:query(sql_query, function(entry) if caller:to_s(entry.auth_source):match(entry.auth_pattern) then gateway = entry; return; end end) return gateway; end function Gateway.profile_get(self, gateway_id) local sql_query = 'SELECT `value` FROM `gateway_settings` WHERE `gateway_id` = ' .. tonumber(gateway_id) .. ' AND `name` = "profile" LIMIT 1'; return self.database:query_return_value(sql_query); end function Gateway.config_table_get(self, config_table, gateway_id) require 'common.str' local sql_query = 'SELECT * FROM `'.. config_table ..'` WHERE `gateway_id` = ' .. tonumber(gateway_id); local settings = {}; self.database:query(sql_query, function(entry) local p_class_type = common.str.strip(entry.class_type):lower(); local p_name = common.str.strip(entry.name):lower(); if p_class_type == 'boolean' then settings[p_name] = common.str.to_b(entry.value); elseif p_class_type == 'integer' then settings[p_name] = common.str.to_i(entry.value); else settings[p_name] = tostring(entry.value); end end) return settings end function Gateway.parameters_build(self, gateway_id) local settings = self:config_table_get('gateway_settings', gateway_id); local parameters = { realm = settings.domain, extension = 'auto_to_user', }; require 'common.str' if common.str.blank(settings.username) then parameters.username = 'gateway' .. gateway_id; parameters.register = false; else parameters.username = settings.username; parameters.register = true; end if not common.str.blank(settings.register) then parameters.register = common.str.to_b(settings.register); end if common.str.blank(settings.password) then parameters.password = 'gateway' .. gateway_id; else parameters.password = settings.password; end parameters['extension-in-contact'] = true; if common.str.blank(settings.contact) then parameters['extension'] = 'gateway' .. gateway_id; else parameters['extension'] = settings.contact; end for key, value in pairs(self:config_table_get('gateway_parameters', gateway_id)) do parameters[key] = value; end return parameters; end
-- Gemeinschaft 5 module: gateway class -- (c) AMOOMA GmbH 2013 -- module(...,package.seeall) Gateway = {} -- Create Gateway object function Gateway.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'gateway'; self.log = arg.log; self.database = arg.database; self.record = arg.record; self.GATEWAY_PREFIX = 'gateway'; return object; end function Gateway.list(self, technology) technology = technology or 'sip'; local sql_query = 'SELECT * FROM `gateways` WHERE (`outbound` IS TRUE OR `inbound` IS TRUE) AND `technology` = "' .. technology .. '"'; local gateways = {}; self.database:query(sql_query, function(entry) table.insert(gateways, entry); end) return gateways; end function Gateway.find_by_id(self, id) local sql_query = 'SELECT * FROM `gateways` WHERE `id`= ' .. tonumber(id) .. ' LIMIT 1'; local gateway = nil; self.database:query(sql_query, function(entry) gateway = Gateway:new(self); gateway.record = entry; gateway.id = tonumber(entry.id); gateway.name = entry.name; end) if gateway then gateway.settings = self:config_table_get('gateway_settings', gateway.id); end return gateway; end function Gateway.authenticate(self, technology, caller) local sql_query = 'SELECT `c`.`name`, `c`.`id`, `a`.`value` `auth_source`, `b`.`value` `auth_pattern` \ FROM `gateway_settings` `a` \ INNER JOIN `gateway_settings` `b` \ ON (`a`.`gateway_id` = `b`.`gateway_id` AND `a`.`name` = "auth_source" AND `b`.`name` = "auth_pattern" ) \ LEFT JOIN `gateways` `c` \ ON (`a`.`gateway_id` = `c`.`id`) \ WHERE `c`.`inbound` IS TRUE AND `c`.`technology` = "' .. tostring(technology) .. '"'; local gateway = false; self.database:query(sql_query, function(entry) if caller:to_s(entry.auth_source):match(entry.auth_pattern) then gateway = entry; return; end end) return gateway; end function Gateway.profile_get(self, gateway_id) local sql_query = 'SELECT `value` FROM `gateway_settings` WHERE `gateway_id` = ' .. tonumber(gateway_id) .. ' AND `name` = "profile" LIMIT 1'; return self.database:query_return_value(sql_query); end function Gateway.config_table_get(self, config_table, gateway_id) require 'common.str' local sql_query = 'SELECT * FROM `'.. config_table ..'` WHERE `gateway_id` = ' .. tonumber(gateway_id); local settings = {}; self.database:query(sql_query, function(entry) local p_class_type = common.str.strip(entry.class_type):lower(); local p_name = common.str.strip(entry.name):lower(); if p_class_type == 'boolean' then settings[p_name] = common.str.to_b(entry.value); elseif p_class_type == 'integer' then settings[p_name] = common.str.to_i(entry.value); else settings[p_name] = tostring(entry.value); end end) return settings end function Gateway.parameters_build(self, gateway_id) local settings = self:config_table_get('gateway_settings', gateway_id); local parameters = { realm = settings.domain, extension = 'auto_to_user', }; require 'common.str' if common.str.blank(settings.username) then parameters.username = 'gateway' .. gateway_id; parameters.register = false; else parameters.username = settings.username; parameters.register = true; end if not common.str.blank(settings.register) then parameters.register = common.str.to_b(settings.register); end if common.str.blank(settings.password) then parameters.password = 'gateway' .. gateway_id; else parameters.password = settings.password; end parameters['extension-in-contact'] = true; if common.str.blank(settings.contact) then parameters['extension'] = 'gateway' .. gateway_id; else parameters['extension'] = settings.contact; end for key, value in pairs(self:config_table_get('gateway_parameters', gateway_id)) do parameters[key] = value; end return parameters; end
set gateway prefix
set gateway prefix
Lua
mit
funkring/gs5,amooma/GS5,funkring/gs5,amooma/GS5,funkring/gs5,amooma/GS5,amooma/GS5,funkring/gs5
a2435e70e8e07492bff8eec9a9c37f729ee49725
otouto/plugins/twitter.lua
otouto/plugins/twitter.lua
local twitter = {} function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)', 'twitter.com/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg, config, matches) if not matches[2] then id = matches[1] else id = matches[2] end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end -- MD: local header = 'Tweet von '..full_name..' ([@' ..user_name.. '](https://twitter.com/'..user_name..')'..verified..')\n' local header = 'Tweet von '..full_name..' (@' ..user_name..verified..')\n' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = favorites elseif retweets ~= "" and favorites == "" then footer = retweets elseif retweets ~= "" and favorites ~= "" then footer = retweets..' - '..favorites else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url_https if v.video_info then if not v.video_info.variants[3] then local vid = v.video_info.variants[1].url table.insert(videos, vid) else local vid = v.video_info.variants[3].url table.insert(videos, vid) end end text = text:gsub(url, "") table.insert(images, pic) end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end -- MD: quote = 'Als Antwort auf '..quoted_name..' ([@' ..quoted_screen_name.. '](https://twitter.com/'..quoted_screen_name..')'..quoted_verified..'):\n'..quoted_text quote = 'Als Antwort auf '..quoted_name..' (@' ..quoted_screen_name..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts local text = unescape(text) utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer) for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(self, msg.chat.id, file, nil, msg.message_id) end end return twitter
local twitter = {} function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)', 'twitter.com/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg, config, matches) if not matches[2] then id = matches[1] else id = matches[2] end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end -- MD: local header = 'Tweet von '..full_name..' ([@' ..user_name.. '](https://twitter.com/'..user_name..')'..verified..')\n' local header = 'Tweet von '..full_name..' (@' ..user_name..verified..')\n' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = favorites elseif retweets ~= "" and favorites == "" then footer = retweets elseif retweets ~= "" and favorites ~= "" then footer = retweets..' - '..favorites else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url local long = long:gsub('%%', '%%%%') text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url_https if v.video_info then if not v.video_info.variants[3] then local vid = v.video_info.variants[1].url table.insert(videos, vid) else local vid = v.video_info.variants[3].url table.insert(videos, vid) end end text = text:gsub(url, "") table.insert(images, pic) end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end -- MD: quote = 'Als Antwort auf '..quoted_name..' ([@' ..quoted_screen_name.. '](https://twitter.com/'..quoted_screen_name..')'..quoted_verified..'):\n'..quoted_text quote = 'Als Antwort auf '..quoted_name..' (@' ..quoted_screen_name..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts local text = unescape(text) utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer) for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(self, msg.chat.id, file, nil, msg.message_id) end end return twitter
Twitter: Fix, wenn Prozent in einer URL vorkommt
Twitter: Fix, wenn Prozent in einer URL vorkommt
Lua
agpl-3.0
Brawl345/Brawlbot-v2
fe8c368a032bce5f606b9bf30a83e9375f850ccd
realism/server/character_kill.lua
realism/server/character_kill.lua
function characterKill( player, causeOfDeath ) exports.database:execute( "UPDATE `characters` SET `is_dead` = '1', `cause_of_death` = ? WHERE `id` = ?", causeOfDeath, exports.common:getCharacterID( player ) ) setElementAlpha( player, 0 ) local ped = createPed( getElementModel( player ), getElementPosition( player ) ) setElementRotation( ped, getElementRotation( player ) ) setElementInterior( ped, getElementInterior( player ) ) setElementDimension( ped, getElementDimension( player ) ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", exports.common:getCharacterID( player ), true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", causeOfDeath, true ) exports.accounts:characterSelection( player ) end function characterResurrect( characterName ) local character = exports.accounts:getCharacterByName( characterName ) if ( character ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '0', `cause_of_death` = '' WHERE `id` = ?", character.id ) local ped = findCharacterKillPed( character.id ) if ( ped ) then destroyElement( ped ) end return true end return false end function findCharacterKillPed( characterID ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then return ped end end return false end function loadCharacterKills( ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then destroyElement( ped ) end end for _, data in ipairs( exports.database:query( "SELECT * FROM `characters` WHERE `is_dead` = '1'" ) ) do local ped = createPed( data.skin_id, data.pos_x, data.pos_y, data.pos_z ) setPedRotation( ped, data.rotation ) setElementInterior( ped, data.interior ) setElementDimension( ped, data.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", data.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", data.cause_of_death, true ) end end
function characterKill( characterID, causeOfDeath ) local characterPlayer = exports.common:getPlayerByCharacterID( characterID ) if ( characterPlayer ) then exports.accounts:saveCharacter( characterPlayer ) end local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead == 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '1', `cause_of_death` = ? WHERE `id` = ?", causeOfDeath, characterID ) local ped = createPed( character.skin_id, character.pos_x, character.pos_y, character.pos_z, character.rotation, false ) setElementInterior( ped, character.interior ) setElementDimension( ped, character.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", character.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", causeOfDeath, true ) local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) then if ( characterPlayer ) then exports.accounts:characterSelection( player ) outputChatBox( "You were character killed by an administrator.", player, 230, 180, 95, false ) outputChatBox( " Cause of death: " .. causeOfDeath, player, 230, 180, 95, false ) else exports.accounts:updateCharacters( player ) end end return true end return false end function characterResurrect( characterID ) local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead ~= 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '0', `cause_of_death` = '' WHERE `id` = ?", character.id ) local ped = findCharacterKillPed( character.id ) if ( ped ) then destroyElement( ped ) end local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) and ( not getElementData( player, "player:playing" ) ) then exports.accounts:updateCharacters( player ) end return true end return false end function findCharacterKillPed( characterID ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then return ped end end return false end function loadCharacterKills( ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then destroyElement( ped ) end end for _, data in ipairs( exports.database:query( "SELECT * FROM `characters` WHERE `is_dead` = '1'" ) ) do local ped = createPed( data.skin_id, data.pos_x, data.pos_y, data.pos_z ) setPedRotation( ped, data.rotation ) setElementInterior( ped, data.interior ) setElementDimension( ped, data.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", data.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", data.cause_of_death, true ) end end addEventHandler( "onResourceStart", resourceRoot, function( ) loadCharacterKills( ) end )
realism: fixes and improvements to cks
realism: fixes and improvements to cks
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
48b85ac89cc58341095d7c7d13abb1b5d34feb74
tests/httpredirect.lua
tests/httpredirect.lua
-- test redirecting http <-> https combinations local copas = require("copas") local http = require("copas.http") local ltn12 = require("ltn12") local dump_all_headers = false local redirect local function doreq(url) local reqt = { url = url, redirect = redirect, --> allows https-> http redirect target = {}, } reqt.sink = ltn12.sink.table(reqt.target) local result, code, headers, status = http.request(reqt) print(string.rep("=",70)) print("Fetching:",url,"==>",code, status) if dump_all_headers then if headers then print("HEADERS") for k,v in pairs(headers) do print("",k,v) end end else print(" at:", (headers or {}).location) end --print(string.rep("=",70)) return result, code, headers, status end local done = false copas.addthread(function() local result, code, headers, status = doreq("https://goo.gl/UBCUc5") -- https --> https redirect assert(tonumber(code)==200) assert(headers.location == "https://github.com/brunoos/luasec") print("https -> https redirect OK!") copas.addthread(function() local result, code, headers, status = doreq("http://goo.gl/UBCUc5") -- http --> https redirect assert(tonumber(code)==200) assert(headers.location == "https://github.com/brunoos/luasec") print("http -> https redirect OK!") copas.addthread(function() local result, code, headers, status = doreq("http://goo.gl/tBfqNu") -- http --> http redirect assert(tonumber(code)==200) assert(headers.location == "http://www.thijsschreijer.nl/blog/") print("http -> http redirect OK!") copas.addthread(function() local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case assert(result==nil and code == "Unallowed insecure redirect https to http") print("https -> http redirect, while not allowed OK!:", code) copas.addthread(function() redirect = "all" local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case assert(tonumber(code)==200) assert(headers.location == "http://www.thijsschreijer.nl/blog/") print("https -> http redirect, while allowed OK!") done = true end) end) end) end) end) copas.loop() if not done then print("Some checks above failed") os.exit(1) end
-- test redirecting http <-> https combinations local copas = require("copas") local http = require("copas.http") local ltn12 = require("ltn12") local dump_all_headers = false local redirect local socket = require "socket" local function doreq(url) local reqt = { url = url, redirect = redirect, --> allows https-> http redirect target = {}, } reqt.sink = ltn12.sink.table(reqt.target) local result, code, headers, status = http.request(reqt) print(string.rep("=",70)) print("Fetching:",url,"==>",code, status) if dump_all_headers then if headers then print("HEADERS") for k,v in pairs(headers) do print("",k,v) end end else print(" at:", (headers or {}).location) end --print(string.rep("=",70)) return result, code, headers, status end local done = false copas.addthread(function() local result, code, headers, status = doreq("https://goo.gl/UBCUc5") -- https --> https redirect assert(tonumber(code)==200) assert(headers.location == "https://github.com/brunoos/luasec") print("https -> https redirect OK!") copas.addthread(function() local result, code, headers, status = doreq("http://goo.gl/UBCUc5") -- http --> https redirect assert(tonumber(code)==200) assert(headers.location == "https://github.com/brunoos/luasec") print("http -> https redirect OK!") copas.addthread(function() --local result, code, headers, status = doreq("http://goo.gl/tBfqNu") -- http --> http redirect -- the above no longer works for testing, since Google auto-inserts a -- initial redirect to the same url, over https, hence the final -- redirect is a downgrade which then errors out -- so we set up a local http-server to deal with this local server = assert(socket.bind("127.0.0.1", 9876)) local crlf = string.char(13)..string.char(10) copas.addserver(server, function(skt) skt = copas.wrap(skt) local request = assert(skt:receive()) local response = "HTTP/1.1 302 Found" .. crlf .. "Location: http://www.thijsschreijer.nl/blog/" .. crlf .. crlf assert(skt:send(response)) skt:close() end) -- execute test request local result, code, headers, status = doreq("http://localhost:9876/") -- http --> http redirect copas.removeserver(server) -- immediately close server again assert(tonumber(code)==200) assert(headers.location == "http://www.thijsschreijer.nl/blog/") print("http -> http redirect OK!") copas.addthread(function() local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case assert(result==nil and code == "Unallowed insecure redirect https to http") print("https -> http redirect, while not allowed OK!:", code) copas.addthread(function() redirect = "all" local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case assert(tonumber(code)==200) assert(headers.location == "http://www.thijsschreijer.nl/blog/") print("https -> http redirect, while allowed OK!") done = true end) end) end) end) end) copas.loop() if not done then print("Some checks above failed") os.exit(1) end
fix(test) fixes the test for redirecting http->http
fix(test) fixes the test for redirecting http->http fixes #75
Lua
mit
keplerproject/copas
1bab0c5b74a81dbda9ff52cc15223a455ba9d1d1
mods/death_messages/init.lua
mods/death_messages/init.lua
----------------------------------------------------------------------------------------------- local title = "Death Messages" local version = "0.1.2" local mname = "death_messages" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("death_messages").."/settings.txt") ----------------------------------------------------------------------------------------------- -- A table of quips for death messages local messages = {} -- Fill this table with sounds local sounds = { [1] = "death_messages_death_1.ogg", } -- Lava death messages messages.lava = { " pensait que la lave etait cool.", " s'est sentit oblige de toucher la lave.", " est tombe dans la lave.", " est mort(e) dans de la lave.", " ne savait pas que la lave etait vraiment chaude." } -- Drowning death messages messages.water = { " a manque d'air.", " a essaye d'usurper l'identite d'une ancre.", " a oublie qu'il n'etait pas un poisson.", " a oublier qu'il lui fallait respirer sous l'eau.", " n'est pas bon en natation." } -- Burning death messages messages.fire = { " a eut un peu trop chaud.", " a ete trop pres du feu.", " vient de se faire rotir.", " a ete carbonise.", " s'est prit pour torch man. (des quatres fantastiques)" } -- Acid death messages messages.acid = { " a desormais des parties en moins.", " a decouvert que l'acide c'est fun.", " a mis sa tete la ou elle a fondu.", " a decouvert que son corps dans l'acide, c'est comme du sucre dans de l'eau.", " a cru qu'il se baignait dans du jus de pomme." } -- Other death messages messages.other = { " a fait quelque chose qui lui a ete fatale.", " est mort(e).", " n'est plus de ce monde.", " a rejoint le paradis des mineurs.", " a perdu la vie." } if RANDOM_MESSAGES == true then minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. messages.lava[math.random(1,#messages.lava)] ) -- Death by acid elseif node.groups.acid ~= nil then minetest.chat_send_all(player_name .. messages.acid[math.random(1,#messages.acid)] ) -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. messages.water[math.random(1,#messages.water)] ) -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. messages.fire[math.random(1,#messages.fire)] ) -- Death by something else else minetest.chat_send_all(player_name .. messages.other[math.random(1,#messages.other)] ) end minetest.sound_play({name = sounds[math.random(1,#messages.other)],gain=0.5*sounds.get_gain(player:get_player_name(),"other")}) end) else minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. " melted into a ball of fire") -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. " ran out of air.") -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. " burned to a crisp.") -- Death by something else else minetest.chat_send_all(player_name .. " died.") end minetest.sound_play({name = sounds[math.random(1,#messages.other)],gain=0.5*sounds.get_gain(player:get_player_name(),"other")}) end) end ----------------------------------------------------------------------------------------------- print("[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------- local title = "Death Messages" local version = "0.1.2" local mname = "death_messages" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("death_messages").."/settings.txt") ----------------------------------------------------------------------------------------------- -- A table of quips for death messages local messages = {} -- Fill this table with sounds local sounds = { [1] = "death_messages_death_1", } -- Lava death messages messages.lava = { " pensait que la lave etait cool.", " s'est sentit oblige de toucher la lave.", " est tombe dans la lave.", " est mort(e) dans de la lave.", " ne savait pas que la lave etait vraiment chaude." } -- Drowning death messages messages.water = { " a manque d'air.", " a essaye d'usurper l'identite d'une ancre.", " a oublie qu'il n'etait pas un poisson.", " a oublier qu'il lui fallait respirer sous l'eau.", " n'est pas bon en natation." } -- Burning death messages messages.fire = { " a eut un peu trop chaud.", " a ete trop pres du feu.", " vient de se faire rotir.", " a ete carbonise.", " s'est prit pour torch man. (des quatres fantastiques)" } -- Acid death messages messages.acid = { " a desormais des parties en moins.", " a decouvert que l'acide c'est fun.", " a mis sa tete la ou elle a fondu.", " a decouvert que son corps dans l'acide, c'est comme du sucre dans de l'eau.", " a cru qu'il se baignait dans du jus de pomme." } -- Other death messages messages.other = { " a fait quelque chose qui lui a ete fatale.", " est mort(e).", " n'est plus de ce monde.", " a rejoint le paradis des mineurs.", " a perdu la vie." } if RANDOM_MESSAGES == true then minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. messages.lava[math.random(1,#messages.lava)] ) -- Death by acid elseif node.groups.acid ~= nil then minetest.chat_send_all(player_name .. messages.acid[math.random(1,#messages.acid)] ) -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. messages.water[math.random(1,#messages.water)] ) -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. messages.fire[math.random(1,#messages.fire)] ) -- Death by something else else minetest.chat_send_all(player_name .. messages.other[math.random(1,#messages.other)] ) end minetest.sound_play({name = sounds[math.random(1,#sounds)],gain=0.5*soundset.get_gain(player:get_player_name(),"other")}) end) else minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. " melted into a ball of fire") -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. " ran out of air.") -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. " burned to a crisp.") -- Death by something else else minetest.chat_send_all(player_name .. " died.") end minetest.sound_play({name = sounds[math.random(1,#sounds)],gain=0.5*soundset.get_gain(player:get_player_name(),"other")}) end) end ----------------------------------------------------------------------------------------------- print("[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
fix mores bug fix wrong param adapt to new soundset version due to conflict name with death_messages
fix mores bug fix wrong param adapt to new soundset version due to conflict name with death_messages
Lua
unlicense
Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server
4c84b9699024fdd2d8e1797dace396ef084b70d2
aspects/vim/files/.vim/lua/wincent/init.lua
aspects/vim/files/.vim/lua/wincent/init.lua
local wincent = {} local focused_flag = 'wincent_focused' local ownsyntax_flag = 'wincent_ownsyntax' -- +0,+1,+2, ... +254 local focused_colorcolumn = '+' .. table.concat({ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254' }, ',+') local winhighlight_blurred = table.concat({ 'CursorLineNr:LineNr', 'EndOfBuffer:ColorColumn', 'IncSearch:ColorColumn', 'Normal:ColorColumn', 'NormalNC:ColorColumn', 'SignColumn:ColorColumn' }, ',') -- "Safe" version of `nvim_win_get_var()` that returns `nil` if the -- variable is not set. local win_get_var = function(handle, name) local result pcall(function () result = vim.api.nvim_win_get_var(handle, name) end) return result end -- As described in a7e4d8b8383a375d124, `ownsyntax` resets spelling -- settings, so we capture and restore them. Note that there is some trickiness -- here because multiple autocmds can trigger "focus" or "blur" operations; this -- means that we can't just naively save and restore: we have to use a flag to -- make sure that we only capture the initial state. local ownsyntax = function(active) if active and win_get_var(0, ownsyntax_flag) == false then -- We are focussing; restore previous settings. vim.cmd('ownsyntax on') vim.api.nvim_win_set_option(0, 'spell', win_get_var(0, 'spell') or false) vim.api.nvim_buf_set_option(0, 'spellcapcheck', win_get_var(0, 'spellcapcheck') or '') vim.api.nvim_buf_set_option(0, 'spellfile', win_get_var(0, 'spellfile') or '') vim.api.nvim_buf_set_option(0, 'spelllang', win_get_var(0, 'spelllang') or 'en') -- Set flag to show that we have restored the captured options. vim.api.nvim_win_set_var(0, ownsyntax_flag, true) elseif not active and win_get_var(0, ownsyntax_flag) ~= false then -- We are blurring; save settings for later restoration. vim.api.nvim_win_set_var(0, 'spell', vim.api.nvim_win_get_option(0, 'spell')) vim.api.nvim_win_set_var(0, 'spellcapcheck', vim.api.nvim_buf_get_option(0, 'spellcapcheck')) vim.api.nvim_win_set_var(0, 'spellfile', vim.api.nvim_buf_get_option(0, 'spellfile')) vim.api.nvim_win_set_var(0, 'spelllang', vim.api.nvim_buf_get_option(0, 'spelllang')) vim.cmd('ownsyntax off') -- Suppress spelling in blurred buffer. vim.api.nvim_win_set_option(0, 'spell', false) -- Set flag to show that we have captured options. vim.api.nvim_win_set_var(0, ownsyntax_flag, false) end return spell end local when_supports_blur_and_focus = function(callback) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') local listed = vim.api.nvim_buf_get_option(0, 'buflisted') if wincent.colorcolumn_filetype_blacklist[filetype] ~= true and listed then callback() end end local focus_window = function() if win_get_var(0, focused_flag) ~= true then vim.api.nvim_win_set_option(0, 'winhighlight', '') when_supports_blur_and_focus(function() vim.api.nvim_win_set_option(0, 'colorcolumn', focused_colorcolumn) if filetype ~= '' then ownsyntax(true) vim.api.nvim_win_set_option(0, 'list', true) vim.api.nvim_win_set_option(0, 'conceallevel', 1) end end) vim.api.nvim_win_set_var(0, focused_flag, true) end end local blur_window = function() if win_get_var(0, focused_flag) ~= false then vim.api.nvim_win_set_option(0, 'winhighlight', winhighlight_blurred) when_supports_blur_and_focus(function() ownsyntax(false) vim.api.nvim_win_set_option(0, 'list', false) vim.api.nvim_win_set_option(0, 'conceallevel', 0) end) vim.api.nvim_win_set_var(0, focused_flag, false) end end local set_cursorline = function(active) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') if wincent.cursorline_blacklist[filetype] ~= true then vim.api.nvim_win_set_option(0, 'cursorline', active) end end -- TODO: maybe move this into an autocmds.lua file, or possibly even more granular than that wincent.buf_enter = function() focus_window() end wincent.focus_gained = function() focus_window() end wincent.focus_lost = function() blur_window() end wincent.insert_enter = function() set_cursorline(false) end wincent.insert_leave = function() set_cursorline(true) end wincent.vim_enter = function() set_cursorline(true) focus_window() end wincent.win_enter = function() set_cursorline(true) focus_window() end wincent.win_leave = function() set_cursorline(false) blur_window() end wincent.colorcolumn_filetype_blacklist = { ['command-t'] = true, ['diff'] = true, ['dirvish'] = true, ['fugitiveblame']= true, ['undotree'] = true, ['qf'] = true, } wincent.cursorline_blacklist = { ['command-t'] = true, } return wincent
local wincent = {} local focused_flag = 'wincent_focused' local ownsyntax_flag = 'wincent_ownsyntax' -- +0,+1,+2, ... +254 local focused_colorcolumn = '+' .. table.concat({ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254' }, ',+') local winhighlight_blurred = table.concat({ 'CursorLineNr:LineNr', 'EndOfBuffer:ColorColumn', 'IncSearch:ColorColumn', 'Normal:ColorColumn', 'NormalNC:ColorColumn', 'SignColumn:ColorColumn' }, ',') -- "Safe" version of `nvim_win_get_var()` that returns `nil` if the -- variable is not set. local win_get_var = function(handle, name) local result pcall(function () result = vim.api.nvim_win_get_var(handle, name) end) return result end -- As described in a7e4d8b8383a375d124, `ownsyntax` resets spelling -- settings, so we capture and restore them. Note that there is some trickiness -- here because multiple autocmds can trigger "focus" or "blur" operations; this -- means that we can't just naively save and restore: we have to use a flag to -- make sure that we only capture the initial state. local ownsyntax = function(active) if active and win_get_var(0, ownsyntax_flag) == false then -- We are focussing; restore previous settings. vim.cmd('ownsyntax on') vim.api.nvim_win_set_option(0, 'spell', win_get_var(0, 'spell') or false) vim.api.nvim_buf_set_option(0, 'spellcapcheck', win_get_var(0, 'spellcapcheck') or '') vim.api.nvim_buf_set_option(0, 'spellfile', win_get_var(0, 'spellfile') or '') vim.api.nvim_buf_set_option(0, 'spelllang', win_get_var(0, 'spelllang') or 'en') -- Set flag to show that we have restored the captured options. vim.api.nvim_win_set_var(0, ownsyntax_flag, true) elseif not active and win_get_var(0, ownsyntax_flag) ~= false then -- We are blurring; save settings for later restoration. vim.api.nvim_win_set_var(0, 'spell', vim.api.nvim_win_get_option(0, 'spell')) vim.api.nvim_win_set_var(0, 'spellcapcheck', vim.api.nvim_buf_get_option(0, 'spellcapcheck')) vim.api.nvim_win_set_var(0, 'spellfile', vim.api.nvim_buf_get_option(0, 'spellfile')) vim.api.nvim_win_set_var(0, 'spelllang', vim.api.nvim_buf_get_option(0, 'spelllang')) vim.cmd('ownsyntax off') -- Suppress spelling in blurred buffer. vim.api.nvim_win_set_option(0, 'spell', false) -- Set flag to show that we have captured options. vim.api.nvim_win_set_var(0, ownsyntax_flag, false) end return spell end local when_supports_blur_and_focus = function(callback) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') local listed = vim.api.nvim_buf_get_option(0, 'buflisted') if wincent.colorcolumn_filetype_blacklist[filetype] ~= true and listed then callback(filetype) end end local focus_window = function() if win_get_var(0, focused_flag) ~= true then vim.api.nvim_win_set_option(0, 'winhighlight', '') when_supports_blur_and_focus(function(filetype) vim.api.nvim_win_set_option(0, 'colorcolumn', focused_colorcolumn) if filetype ~= '' then ownsyntax(true) end vim.api.nvim_win_set_option(0, 'list', true) vim.api.nvim_win_set_option(0, 'conceallevel', 1) end) vim.api.nvim_win_set_var(0, focused_flag, true) end end local blur_window = function() if win_get_var(0, focused_flag) ~= false then vim.api.nvim_win_set_option(0, 'winhighlight', winhighlight_blurred) when_supports_blur_and_focus(function(filetype) ownsyntax(false) vim.api.nvim_win_set_option(0, 'list', false) vim.api.nvim_win_set_option(0, 'conceallevel', 0) end) vim.api.nvim_win_set_var(0, focused_flag, false) end end local set_cursorline = function(active) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') if wincent.cursorline_blacklist[filetype] ~= true then vim.api.nvim_win_set_option(0, 'cursorline', active) end end -- TODO: maybe move this into an autocmds.lua file, or possibly even more granular than that wincent.buf_enter = function() focus_window() end wincent.focus_gained = function() focus_window() end wincent.focus_lost = function() blur_window() end wincent.insert_enter = function() set_cursorline(false) end wincent.insert_leave = function() set_cursorline(true) end wincent.vim_enter = function() set_cursorline(true) focus_window() end wincent.win_enter = function() set_cursorline(true) focus_window() end wincent.win_leave = function() set_cursorline(false) blur_window() end wincent.colorcolumn_filetype_blacklist = { ['command-t'] = true, ['diff'] = true, ['dirvish'] = true, ['fugitiveblame']= true, ['undotree'] = true, ['qf'] = true, } wincent.cursorline_blacklist = { ['command-t'] = true, } return wincent
fix(vim): avoid "filetype unknown" messages on empty buffers
fix(vim): avoid "filetype unknown" messages on empty buffers
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
1a5b9bd5d9b4f383ef8ea132a2fde9c8a305b01c
modules/protocol/udp/udp.lua
modules/protocol/udp/udp.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local ipv4 = require("protocol/ipv4") local function compute_checksum(pkt) local checksum = ipv4.inet_checksum() -- UDP checksum is computed using a -- pseudo-header made of some fields -- of ipv4 header -- size of the udp pseudo-header local pseudo_header = haka.vbuffer_allocate(12) -- source and destination ipv4 addresses pseudo_header:sub(0,4):setnumber(pkt.ip.src.packed) pseudo_header:sub(4,4):setnumber(pkt.ip.dst.packed) -- padding (null byte) pseudo_header:sub(8,1):setnumber(0) -- UDP protocol number pseudo_header:sub(9,1):setnumber(0x11) -- UDP message length (header + data) pseudo_header:sub(10,2):setnumber(pkt.length) checksum:process(pseudo_header) checksum:process(pkt._payload) return checksum:reduce() end local udp_dissector = haka.dissector.new{ type = haka.helper.PacketDissector, name = 'udp' } udp_dissector.grammar = haka.grammar.new("udp", function () packet = record{ field('srcport', number(16)), field('dstport', number(16)), field('length', number(16)) :validate(function (self) self.len = 8 + #self.payload end), field('checksum', number(16)) :validate(function (self) self.checksum = 0 self.checksum = compute_checksum(self) end), field('payload', bytes()) } export(packet) end) function udp_dissector.method:parse_payload(pkt, payload) self.ip = pkt local res = udp_dissector.grammar.packet:parse(payload:pos("begin")) table.merge(self, res) end function udp_dissector.method:create_payload(pkt, payload, init) self.ip = pkt local res = udp_dissector.grammar.packet:create(payload:pos("begin"), init) table.merge(self, res) end function udp_dissector.method:forge_payload(pkt, payload) if payload.modified then self.checksum = nil end self:validate() end function udp_dissector.method:verify_checksum() return compute_checksum(self) == 0 end function udp_dissector:create(pkt, init) if not init then init = {} end if not init.length then init.length = 8 end pkt.payload:pos(0):insert(haka.vbuffer_allocate(init.length)) pkt.proto = 17 local udp = udp_dissector:new(pkt) udp:create(init, pkt) return udp end function udp_dissector.method:install_criterion() return { port = self.port } end haka.policy { name = "udp", on = haka.dissectors.ipv4.policies.next_dissector, proto = 17, action = haka.dissectors.udp.install }
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local ipv4 = require("protocol/ipv4") local function compute_checksum(pkt) local checksum = ipv4.inet_checksum() -- UDP checksum is computed using a -- pseudo-header made of some fields -- of ipv4 header -- size of the udp pseudo-header local pseudo_header = haka.vbuffer_allocate(12) -- source and destination ipv4 addresses pseudo_header:sub(0,4):setnumber(pkt.ip.src.packed) pseudo_header:sub(4,4):setnumber(pkt.ip.dst.packed) -- padding (null byte) pseudo_header:sub(8,1):setnumber(0) -- UDP protocol number pseudo_header:sub(9,1):setnumber(0x11) -- UDP message length (header + data) pseudo_header:sub(10,2):setnumber(pkt.length) checksum:process(pseudo_header) checksum:process(pkt._payload) return checksum:reduce() end local udp_dissector = haka.dissector.new{ type = haka.helper.PacketDissector, name = 'udp' } udp_dissector.grammar = haka.grammar.new("udp", function () packet = record{ field('srcport', number(16)), field('dstport', number(16)), field('length', number(16)) :validate(function (self) self.len = 8 + #self.payload end), field('checksum', number(16)) :validate(function (self) self.checksum = 0 self.checksum = compute_checksum(self) end), field('payload', bytes()) } export(packet) end) function udp_dissector.method:parse_payload(pkt, payload) self.ip = pkt local res = udp_dissector.grammar.packet:parse(payload:pos("begin")) table.merge(self, res) end function udp_dissector.method:create_payload(pkt, payload, init) self.ip = pkt local res = udp_dissector.grammar.packet:create(payload:pos("begin"), init) table.merge(self, res) end function udp_dissector.method:forge_payload(pkt, payload) if payload.modified then self.checksum = nil end self:validate() end function udp_dissector.method:verify_checksum() return compute_checksum(self) == 0 end function udp_dissector:create(pkt, init) if not init then init = {} end if not init.length then init.length = 8 end pkt.payload:pos(0):insert(haka.vbuffer_allocate(init.length)) pkt.proto = 17 local udp = udp_dissector:new(pkt) udp:create(init, pkt) return udp end function udp_dissector.method:install_criterion() return { srcport = self.srcport, dstport = self.dstport } end haka.policy { name = "udp", on = haka.dissectors.ipv4.policies.next_dissector, proto = 17, action = haka.dissectors.udp.install }
Fix udp install criterions
Fix udp install criterions
Lua
mpl-2.0
nabilbendafi/haka,haka-security/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,nabilbendafi/haka
7b87c1e46e64ad9534c9ac550d1a433533951d35
kernel/turtle/ttl2flr.lua
kernel/turtle/ttl2flr.lua
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI -- prefix index necessary to expand Qnames with a prefix only and no -- name local __PREFIXES = {} local print = print local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else __PREFIXES[p.name] = p.uri print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- prefix only and no name if n == "" then assert(__PREFIXES[r.prefix], "Prefix must be defined: " .. r.prefix) return string.format("\"%s\"^^\\iri", __PREFIXES[r.prefix]) -- dcterms has "dcterms:ISO639-2" elseif n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) elseif r.type == "Blank" then -- TODO change this -- just use them as oids for now -- note, this is currently acceptable because we are translating -- one stardog export with unique bnode ids --return string.format("\\#[bnodeId->%s]", r.nodeID) return r.nodeID else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then -- we should *ONLY* emit "string" objects, not charlist return '"' .. o:gsub('"', '\\"') .. '"^^\\string' elseif o.type == "TypedString" then local t local v = o.value:gsub('"', '\\"') if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end -- Flora doesn't like Z at the end of dates if o.datatype.uri == "http://www.w3.org/2001/XMLSchema#date" then v = v:gsub("Z$", "") end return string.format("\"%s\"^^%s", v, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if not pcall(getfenv, 4) then -- run script local infile = arg[1] local outfile = arg[2] if not arg[1] or not arg[2] then print("Turtle to Flora translator") print("Argument 1: input file") print("Argument 2: output file") return end local f = io.open(infile, "r") local content = f:read("*all") f:close() local out = io.open(outfile, "w") print = function (x) out:write(x) out:write("\n") end local s = turtleparse.parse(content) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI -- prefix index necessary to expand Qnames with a prefix only and no -- name local __PREFIXES = {} local print = print local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else __PREFIXES[p.name] = p.uri print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- prefix only and no name if n == "" then assert(__PREFIXES[r.prefix], "Prefix must be defined: " .. r.prefix) return string.format("\"%s\"^^\\iri", __PREFIXES[r.prefix]) -- dcterms has "dcterms:ISO639-2" elseif n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) elseif r.type == "Blank" then -- TODO change this -- just use them as oids for now -- note, this is currently acceptable because we are translating -- one stardog export with unique bnode ids --return string.format("\\#[bnodeId->%s]", r.nodeID) return r.nodeID else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then -- we should *ONLY* emit "string" objects, not charlist return '"' .. o:gsub('"', '\\"') .. '"^^\\string' elseif o.type == "TypedString" then local t local v = o.value:gsub('"', '\\"') if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end -- Flora doesn't like Z at the end of dates if t:match("#date$") then v = v:gsub("Z$", "") end return string.format("\"%s\"^^%s", v, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if not pcall(getfenv, 4) then -- run script local infile = arg[1] local outfile = arg[2] if not arg[1] or not arg[2] then print("Turtle to Flora translator") print("Argument 1: input file") print("Argument 2: output file") return end local f = io.open(infile, "r") local content = f:read("*all") f:close() local out = io.open(outfile, "w") print = function (x) out:write(x) out:write("\n") end local s = turtleparse.parse(content) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then -- represent class membership via an RDF triple, -- handle the Flora class membership via rules print(string.format("%s[\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\"^^\\iri -> %s].", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
ttl2flr: fix dates properly whether they're parsed as Qname or URI represent class membership via an RDF triple
ttl2flr: fix dates properly whether they're parsed as Qname or URI represent class membership via an RDF triple
Lua
mit
jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico
b055584e7b8f38890e8ee76e7c1a0e106b5158d1
plugins/mod_motd.lua
plugins/mod_motd.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local host = module:get_host(); local motd_text = module:get_option_string("motd_text"); local motd_jid = module:get_option_string("motd_jid", host); if not motd_text then return; end local st = require "util.stanza"; motd_text = motd_text:gsub("^%s*(.-)%s*$", "%1"):gsub("\n%s+", "\n"); -- Strip indentation from the config module:hook("resource-bind", function (event) local session = event.session; local motd_stanza = st.message({ to = session.username..'@'..session.host, from = motd_jid }) :tag("body"):text(motd_text); core_route_stanza(hosts[host], motd_stanza); module:log("debug", "MOTD send to user %s@%s", session.username, session.host); end);
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local host = module:get_host(); local motd_text = module:get_option_string("motd_text"); local motd_jid = module:get_option_string("motd_jid", host); if not motd_text then return; end local jid_join = require "util.jid".join; local st = require "util.stanza"; motd_text = motd_text:gsub("^%s*(.-)%s*$", "%1"):gsub("\n%s+", "\n"); -- Strip indentation from the config module:hook("resource-bind", function (event) local session = event.session; local motd_stanza = st.message({ to = jid_join(session.username, session.host, session.resource), from = motd_jid }) :tag("body"):text(motd_text); core_route_stanza(hosts[host], motd_stanza); module:log("debug", "MOTD send to user %s@%s", session.username, session.host); end);
mod_motd: Send only to resource coming online, not the user's bare JID (fixes #282)
mod_motd: Send only to resource coming online, not the user's bare JID (fixes #282)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
cceb3fce68c8403722d113f9975c119a92a9e56a
SparseBlockTemporalMaxPooling.lua
SparseBlockTemporalMaxPooling.lua
local SparseBlockTemporalMaxPooling, parent = torch.class('nn.SparseBlockTemporalMaxPooling', 'nn.Module') function SparseBlockTemporalMaxPooling:__init(kW, dW, isRelax, isBP) dW = dW or kW self.kW = kW self.dW = dW self.isRelax = isRelax or false self.isBP = isBP or true end function SparseBlockTemporalMaxPooling:pri_ensureOutput(input) if self.output ~= nil then return end self.output = { nBatchSize = input.nBatchSize, taData = {} } local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] taOutputCurr = { teValue = torch.Tensor(), teRowIdx = taInputCurr.teRowIdx } table.insert(self.output.taData, taOutputCurr) end end function SparseBlockTemporalMaxPooling:pri_ensureTaIndices(input) if self.taIndices ~= nil then return end self.taIndices = {} local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] table.insert(self.taIndices, taInputCurr.teValue.new()) end end function SparseBlockTemporalMaxPooling:pri_updateOutput_column(taInput, taOutput, teIndices) local input = taInput.teValue local output = taOutput.teValue local kW = self.kW if self.isRelax then kW = math.min(input:size(2), kW) end input.THNN.TemporalMaxPooling_updateOutput( input:cdata(), output:cdata(), teIndices:cdata(), kW, self.dW ) end function SparseBlockTemporalMaxPooling:updateOutput(input) self:pri_ensureTaIndices(input) self:pri_ensureOutput(input) local nColumns = table.getn(self.output.taData) for i=1, nColumns do self:pri_updateOutput_column(input.taData[i], self.output.taData[i], self.taIndices[i]) end return self.output end function SparseBlockTemporalMaxPooling:pri_ensureGradInput(input) if self.gradInput ~= nil then return end self.gradInput = { nBatchSize = input.nBatchSize, taData = {} } local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] taGradInputCurr = { teValue = torch.Tensor(), teRowIdx = taInputCurr.teRowIdx } table.insert(self.gradInput.taData, taGradInputCurr) end end function SparseBlockTemporalMaxPooling:pri_updateGradInput_column(taInput, taGradOutput, taGradInput, teIndices) local input = taInput.teValue local gradOutput = taGradOutput.teValue local gradInput = taGradInput.teValue local kW = self.kW if self.isRelax then kW = math.min(input:size(2), kW) end input.THNN.TemporalMaxPooling_updateGradInput( input:cdata(), gradOutput:cdata(), gradInput:cdata(), teIndices:cdata(), kW, self.dW ) end function SparseBlockTemporalMaxPooling:updateGradInput(input, gradOutput) if not self.isBP then return nil end self:pri_ensureGradInput(input) local nColumns = table.getn(self.gradInput.taData) for i=1, nColumns do self:pri_updateGradInput_column(input.taData[i], gradOutput.taData[i], self.gradInput.taData[i], self.taIndices[i]) end return self.gradInput end function SparseBlockTemporalMaxPooling:empty() assert(false, "empty not implemented!") end
local SparseBlockTemporalMaxPooling, parent = torch.class('nn.SparseBlockTemporalMaxPooling', 'nn.Module') function SparseBlockTemporalMaxPooling:__init(kW, dW, isRelax, isBP) dW = dW or kW self.kW = kW self.dW = dW self.isRelax = isRelax or false self.isBP = isBP or true end function SparseBlockTemporalMaxPooling:pri_ensureOutput(input) if self.output ~= nil then return end self.output = { nBatchSize = input.nBatchSize, taData = {} } local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] taOutputCurr = { teValue = torch.Tensor(), teRowIdx = taInputCurr.teRowIdx } table.insert(self.output.taData, taOutputCurr) end end function SparseBlockTemporalMaxPooling:pri_ensureTaIndices(input) if self.taIndices ~= nil then return end self.taIndices = {} local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] table.insert(self.taIndices, taInputCurr.teValue.new():long()) -- fixe just here, maybe not optimal!? end end function SparseBlockTemporalMaxPooling:pri_updateOutput_column(taInput, taOutput, teIndices) local input = taInput.teValue local output = taOutput.teValue local kW = self.kW if self.isRelax then kW = math.min(input:size(2), kW) end input.THNN.TemporalMaxPooling_updateOutput( input:cdata(), output:cdata(), teIndices:cdata(), kW, self.dW ) end function SparseBlockTemporalMaxPooling:updateOutput(input) self:pri_ensureTaIndices(input) self:pri_ensureOutput(input) local nColumns = table.getn(self.output.taData) for i=1, nColumns do self:pri_updateOutput_column(input.taData[i], self.output.taData[i], self.taIndices[i]) end return self.output end function SparseBlockTemporalMaxPooling:pri_ensureGradInput(input) if self.gradInput ~= nil then return end self.gradInput = { nBatchSize = input.nBatchSize, taData = {} } local nColumns = table.getn(input.taData) for i=1, nColumns do local taInputCurr = input.taData[i] taGradInputCurr = { teValue = torch.Tensor(), teRowIdx = taInputCurr.teRowIdx } table.insert(self.gradInput.taData, taGradInputCurr) end end function SparseBlockTemporalMaxPooling:pri_updateGradInput_column(taInput, taGradOutput, taGradInput, teIndices) local input = taInput.teValue local gradOutput = taGradOutput.teValue local gradInput = taGradInput.teValue local kW = self.kW if self.isRelax then kW = math.min(input:size(2), kW) end input.THNN.TemporalMaxPooling_updateGradInput( input:cdata(), gradOutput:cdata(), gradInput:cdata(), teIndices:cdata(), kW, self.dW ) end function SparseBlockTemporalMaxPooling:updateGradInput(input, gradOutput) if not self.isBP then return nil end self:pri_ensureGradInput(input) local nColumns = table.getn(self.gradInput.taData) for i=1, nColumns do self:pri_updateGradInput_column(input.taData[i], gradOutput.taData[i], self.gradInput.taData[i], self.taIndices[i]) end return self.gradInput end function SparseBlockTemporalMaxPooling:empty() assert(false, "empty not implemented!") end
minor SparseBlockTemporalMaxPooling fix, due to torch update
minor SparseBlockTemporalMaxPooling fix, due to torch update
Lua
apache-2.0
ameenetemady/DeepPep,ameenetemady/DeepPep,ameenetemady/DeepPep
5f00699af289b43930d63101fe0425241bf56892
App/NevermoreEngine.lua
App/NevermoreEngine.lua
--- Nevermore module loader. -- Used to simply resource loading and networking so a more unified server / client codebased can be used -- @module Nevermore local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ServerScriptService = game:GetService("ServerScriptService") assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") --- Handles yielded operations by caching the retrieval process local function _handleRetrieving(Retrieving, Function, Argument) assert(type(Retrieving) == "table", "Error: Retrieving must be a table") assert(type(Function) == "function", "Error: Function must be a function") local Signal = Instance.new("BindableEvent") local Result Retrieving[Argument] = function() if Result ~= nil and Result then return Result end Signal.Event:Wait() return Result end Result = Function(Argument) assert(Result ~= nil, "Result cannot be nil") Retrieving[Argument] = nil Signal:Fire() Signal:Destroy() return Result end --- Caches single argument, single output only local function _asyncCache(Function) assert(type(Function) == "function", "Error: Function must be a userdata") local Cache = {} local Retrieving = {} return function(Argument) assert(Argument ~= nil, "Error: ARgument ") if Cache[Argument] ~= nil then return Cache[Argument] elseif Retrieving[Argument] then return Retrieving[Argument]() else Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument) return Cache[Argument] end end end --- Retrieves an instance from a parent local function _retrieve(Parent, ClassName) assert(type(ClassName) == "string", "Error: ClassName must be a string") assert(typeof(Parent) == "Instance", "Error: Parent must be an Instance") return RunService:IsServer() and function(Name) local Item = Parent:FindFirstChild(Name) if not Item then Item = Instance.new(ClassName) Item.Archivable = false Item.Name = Name Item.Parent = Parent end return Item end or function(Name) local Resource = Parent:WaitForChild(Name, 5) if not Resource then warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName)) return Resource:WaitForChild(Name) end end end local function _getRepository(GetSubFolder) if RunService:IsServer() then local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore") if not RepositoryFolder then warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.") RepositoryFolder = Instance.new("Folder") RepositoryFolder.Name = "Nevermore" end return RepositoryFolder else return GetSubFolder("Modules") end end local function _getLibraryCache(RepositoryFolder) local LibraryCache = {} for _, Child in pairs(RepositoryFolder:GetDescendants()) do if Child:IsA("ModuleScript") then if LibraryCache[Child.Name] then error(("Error: Duplicate name of '%s' already exists"):format(Child.Name)) end LibraryCache[Child.Name] = Child end end return LibraryCache end local function _replicateRepository(ReplicationFolder, LibraryCache) for Name, Library in pairs(LibraryCache) do if not Name:lower():find("server") then Library.Parent = ReplicationFolder end end end local function _debugLoading(Function) local Count = 0 local RequestDepth = 0 return function(Module, ...) Count = Count + 1 local LibraryID = Count if DEBUG_MODE then print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module) RequestDepth = RequestDepth + 1 end local Result = Function(Module, ...) if DEBUG_MODE then RequestDepth = RequestDepth - 1 print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module) end return Result end end local function _getLibraryLoader(LibraryCache) --- Loads a library from Nevermore's library cache -- @param Module The name of the library or a module -- @return The library's value return function(Module) if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then return require(Module) elseif type(Module) == "string" then local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2) return require(ModuleScript) else error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module))) end end end local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources") local GetSubFolder = _retrieve(ResourceFolder, "Folder") local RepositoryFolder = _getRepository(GetSubFolder) local LibraryCache = _getLibraryCache(RepositoryFolder) if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode _replicateRepository(GetSubFolder("Modules"), LibraryCache) end local Nevermore = {} --- Load a library through Nevermore -- @function LoadLibrary -- @tparam string LibraryName Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache))) --- Get a remote event -- @function GetRemoteEvent -- @tparam string RemoteEventName -- @return RemoteEvent Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent")) --- Get a remote function -- @function GetRemoteFunction -- @tparam string RemoteFunctionName -- @return RemoteFunction Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction")) setmetatable(Nevermore, { __call = Nevermore.LoadLibrary; __index = function(self, Index) error(("'%s is not a valid member of Nevermore"):format(tostring(Index))) end; }) return Nevermore
--- Nevermore module loader. -- Used to simply resource loading and networking so a more unified server / client codebased can be used -- @module Nevermore local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ServerScriptService = game:GetService("ServerScriptService") assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage") --- Handles yielded operations by caching the retrieval process local function _handleRetrieving(Retrieving, Function, Argument) assert(type(Retrieving) == "table", "Error: Retrieving must be a table") assert(type(Function) == "function", "Error: Function must be a function") local Signal = Instance.new("BindableEvent") local Result Retrieving[Argument] = function() if Result ~= nil and Result then return Result end Signal.Event:Wait() return Result end Result = Function(Argument) assert(Result ~= nil, "Result cannot be nil") Retrieving[Argument] = nil Signal:Fire() Signal:Destroy() return Result end --- Caches single argument, single output only local function _asyncCache(Function) assert(type(Function) == "function", "Error: Function must be a userdata") local Cache = {} local Retrieving = {} return function(Argument) assert(Argument ~= nil, "Error: ARgument ") if Cache[Argument] ~= nil then return Cache[Argument] elseif Retrieving[Argument] then return Retrieving[Argument]() else Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument) return Cache[Argument] end end end --- Retrieves an instance from a parent local function _retrieve(Parent, ClassName) assert(type(ClassName) == "string", "Error: ClassName must be a string") assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent))) return RunService:IsServer() and function(Name) local Item = Parent:FindFirstChild(Name) if not Item then Item = Instance.new(ClassName) Item.Archivable = false Item.Name = Name Item.Parent = Parent end return Item end or function(Name) local Resource = Parent:WaitForChild(Name, 5) if Resource then return Resource end warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName)) return Parent:WaitForChild(Name) end end local function _getRepository(GetSubFolder) if RunService:IsServer() then local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore") if not RepositoryFolder then warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.") RepositoryFolder = Instance.new("Folder") RepositoryFolder.Name = "Nevermore" end return RepositoryFolder else return GetSubFolder("Modules") end end local function _getLibraryCache(RepositoryFolder) local LibraryCache = {} for _, Child in pairs(RepositoryFolder:GetDescendants()) do if Child:IsA("ModuleScript") then if LibraryCache[Child.Name] then error(("Error: Duplicate name of '%s' already exists"):format(Child.Name)) end LibraryCache[Child.Name] = Child end end return LibraryCache end local function _replicateRepository(ReplicationFolder, LibraryCache) for Name, Library in pairs(LibraryCache) do if not Name:lower():find("server") then Library.Parent = ReplicationFolder end end end local function _debugLoading(Function) local Count = 0 local RequestDepth = 0 return function(Module, ...) Count = Count + 1 local LibraryID = Count if DEBUG_MODE then print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module) RequestDepth = RequestDepth + 1 end local Result = Function(Module, ...) if DEBUG_MODE then RequestDepth = RequestDepth - 1 print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module) end return Result end end local function _getLibraryLoader(LibraryCache) --- Loads a library from Nevermore's library cache -- @param Module The name of the library or a module -- @return The library's value return function(Module) if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then return require(Module) elseif type(Module) == "string" then local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2) return require(ModuleScript) else error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module))) end end end local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources") local GetSubFolder = _retrieve(ResourceFolder, "Folder") local RepositoryFolder = _getRepository(GetSubFolder) local LibraryCache = _getLibraryCache(RepositoryFolder) if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode _replicateRepository(GetSubFolder("Modules"), LibraryCache) end local Nevermore = {} --- Load a library through Nevermore -- @function LoadLibrary -- @tparam string LibraryName Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache))) --- Get a remote event -- @function GetRemoteEvent -- @tparam string RemoteEventName -- @return RemoteEvent Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent")) --- Get a remote function -- @function GetRemoteFunction -- @tparam string RemoteFunctionName -- @return RemoteFunction Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction")) setmetatable(Nevermore, { __call = Nevermore.LoadLibrary; __index = function(self, Index) error(("'%s is not a valid member of Nevermore"):format(tostring(Index))) end; }) return Nevermore
FIx _retrieve implementation, this was a critical bug
FIx _retrieve implementation, this was a critical bug
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
28f235cbd8f872abf5f89a534ab6066fc3f3dfbe
ClassNLLCriterion.lua
ClassNLLCriterion.lua
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion') function ClassNLLCriterion:__init(weights) parent.__init(self) self.sizeAverage = true self.outputTensor = torch.Tensor(1) if weights then assert(weights:dim() == 1, "weights input should be 1-D Tensor") self.weights = weights end end function ClassNLLCriterion:updateOutput(input, target) if input:type() == 'torch.CudaTensor' and not self.weights then input.nn.ClassNLLCriterion_updateOutput(self, input, target) self.output = self.outputTensor[1] return self.output end if input:dim() == 1 then self.output = -input[target] if self.weights then self.output = self.output*self.weights[target] end elseif input:dim() == 2 then local output = 0 for i=1,target:size(1) do if self.weights then output = output - input[i][target[i]]*self.weights[target[i]] else output = output - input[i][target[i]] end end if self.sizeAverage then output = output / target:size(1) end self.output = output else error('matrix or vector expected') end return self.output end function ClassNLLCriterion:updateGradInput(input, target) self.gradInput:resizeAs(input) self.gradInput:zero() if input:type() == 'torch.CudaTensor' and not self.weights then input.nn.ClassNLLCriterion_updateGradInput(self, input, target) return self.gradInput end if input:dim() == 1 then self.gradInput[target] = -1 if self.weights then self.gradInput[target] = self.gradInput[target]*self.weights[target] end else local z = -1 if self.sizeAverage then z = z / target:size(1) end for i=1,target:size(1) do self.gradInput[i][target[i]] = z if self.weights then self.gradInput[i][target[i]] = self.gradInput[i][target[i]]*self.weights[target[i]] end end end return self.gradInput end
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion') function ClassNLLCriterion:__init(weights) parent.__init(self) self.sizeAverage = true self.outputTensor = torch.Tensor(1) if weights then assert(weights:dim() == 1, "weights input should be 1-D Tensor") self.weights = weights end end function ClassNLLCriterion:updateOutput(input, target) if input:type() == 'torch.CudaTensor' and not self.weights then self._target = self._target or input.new(1) self._target[1] = target input.nn.ClassNLLCriterion_updateOutput(self, input, self._target) self.output = self.outputTensor[1] return self.output end if input:dim() == 1 then self.output = -input[target] if self.weights then self.output = self.output*self.weights[target] end elseif input:dim() == 2 then local output = 0 for i=1,target:size(1) do if self.weights then output = output - input[i][target[i]]*self.weights[target[i]] else output = output - input[i][target[i]] end end if self.sizeAverage then output = output / target:size(1) end self.output = output else error('matrix or vector expected') end return self.output end function ClassNLLCriterion:updateGradInput(input, target) self.gradInput:resizeAs(input) self.gradInput:zero() if input:type() == 'torch.CudaTensor' and not self.weights then self._target = self._target or input.new(1) self._target[1] = target input.nn.ClassNLLCriterion_updateGradInput(self, input, self._target) return self.gradInput end if input:dim() == 1 then self.gradInput[target] = -1 if self.weights then self.gradInput[target] = self.gradInput[target]*self.weights[target] end else local z = -1 if self.sizeAverage then z = z / target:size(1) end for i=1,target:size(1) do self.gradInput[i][target[i]] = z if self.weights then self.gradInput[i][target[i]] = self.gradInput[i][target[i]]*self.weights[target[i]] end end end return self.gradInput end
fixing small cuda typing issue for ClassNLLCriterion
fixing small cuda typing issue for ClassNLLCriterion
Lua
bsd-3-clause
xianjiec/nn,colesbury/nn,andreaskoepf/nn,joeyhng/nn,zhangxiangxiao/nn,eulerreich/nn,PierrotLC/nn,zchengquan/nn,sbodenstein/nn,Djabbz/nn,hery/nn,eriche2016/nn,davidBelanger/nn,ominux/nn,GregSatre/nn,sagarwaghmare69/nn,LinusU/nn,mlosch/nn,Aysegul/nn,hughperkins/nn,forty-2/nn,adamlerer/nn,rickyHong/nn_lib_torch,clementfarabet/nn,nicholas-leonard/nn,jonathantompson/nn,Moodstocks/nn,bartvm/nn,lukasc-ch/nn,elbamos/nn,jhjin/nn,rotmanmi/nn,jzbontar/nn,Jeffyrao/nn,apaszke/nn,vgire/nn,PraveerSINGH/nn,diz-vara/nn,fmassa/nn,witgo/nn,noa/nn,boknilev/nn,mys007/nn,abeschneider/nn,karpathy/nn,aaiijmrtt/nn,kmul00/nn,EnjoyHacking/nn,lvdmaaten/nn,douwekiela/nn,caldweln/nn,szagoruyko/nn,ivendrov/nn
011a7f2c47c9241527106de3d7d4c2fd48ed4339
glove.lua
glove.lua
-- Glove is a compatibility layer -- So that you can write LOVE modules -- That work on 0.8.0, 0.9.0, and 0.9.1 -- -- The local functions are named after 0.8.0 local glove = {} -- Features local love9 = love._version == "0.9.0" or love._version == "0.9.1" local love8 = love._version == "0.8.0" require "love.filesystem" require "love.graphics" if love9 then require "love.window" require "love.system" end glove.system = {} glove.filesystem = {} glove.window = {} glove.graphics = {} glove.thread = {} -- https://love2d.org/wiki/love.system.getOS function getOS() if love8 then return love._os end return love.system.getOS() end glove._os = getOS() glove.system.getOS = getOS -- https://love2d.org/wiki/love.graphics.getFont function getFont() if love8 then return love.graphics.newFont(love.graphics.getFont()) end return love.graphics.getFont() end glove.graphics.getFont = getFont --http://www.love2d.org/wiki/love.graphics.newStencil local function newStencil (stencilFunction) if love.graphics.newStencil then return love.graphics.newStencil(stencilFunction) else return stencilFunction end end glove.graphics.newStencil = newStencil --http://www.love2d.org/wiki/love.graphics.setLine local function setLine (width, style) if love.graphics.setLine then love.graphics.setLine(width, style) else love.graphics.setLineWidth(width) love.graphics.setLineStyle(style) end end glove.graphics.setLine = setLine -- http://www.love2d.org/wiki/love.filesystem.enumerate local function enumerate(dir) if love.filesystem.enumerate then return love.filesystem.enumerate(dir) else return love.filesystem.getDirectoryItems(dir) end end glove.filesystem.enumerate = enumerate glove.filesystem.getDirectoryItems = enumerate -- http://www.love2d.org/wiki/love.filesystem.mkdir local function mkdir(name) if love.filesystem.mkdir then return love.filesystem.mkdir(name) else return love.filesystem.createDirectory(name) end end glove.filesystem.mkdir = mkdir glove.filesystem.createDirectory = mkdir function glove.filesystem.isFused() if love.filesystem.isFused then return love.filesystem.isFused() else local datadir = love.filesystem.getAppdataDirectory() local savedir = love.filesystem.getSaveDirectory() local fragment = savedir:sub(datadir:len() + 2) local start, stop = nil if love._os == "Linux" then start, stop = fragment:find("love/") else start, stop = fragment:find("LOVE/") end return (start ~= 1 and stop ~= 5) end end -- The NamedThread class provides the Love 0.8.0 -- thread interface in Love 0.9.0 local NamedThread = {} NamedThread.__index = NamedThread function NamedThread:init(name, filedata) self.thread = love.thread.newThread(filedata) self.name = name end function NamedThread:start() return self.thread:start() end function NamedThread:wait() return self.thread:wait() end function NamedThread:set(name, value) local channel = love.thread.getChannel(name) return channel:push(value) end function NamedThread:peek(name) local channel = love.thread.getChannel(name) return channel:peek() end function NamedThread:get(name) if name == "error" then return self.thread:getError() end local channel = love.thread.getChannel(name) return channel:pop() end function NamedThread:demand(name) local channel = love.thread.getChannel(name) return channel:demand() end local _threads = {} -- http://www.love2d.org/wiki/love.thread.newThread local function newThread(name, filedata) if love8 then return love.thread.newThread(name, filedata) end if _threads[name] then error("A thread with that name already exists.") end local thread = {} setmetatable(thread, NamedThread) thread:init(name, filedata) -- Mark this name as taken _threads[name] = true return thread end local function getThread() if love.thread.getThread then return love.thread.getThread() end local thread = {} setmetatable(thread, NamedThread) return thread end glove.thread.newThread = newThread glove.thread.getThread = getThread --glove.window.getDesktopDimension --glove.window.getFullscreen --glove.window.getFullscreenModes --glove.window.getIcon --glove.window.getMode local function getHeight() return love.graphics.getHeight() end local function getWidth() return love.graphics.getWidth() end glove.window.getHeight = getHeight glove.window.getWidth = getWidth glove.graphics.getHeight = getHeight glove.graphics.getWidth = getWidth local function getTitle() if love.window and love.window.getTitle then return love.window.getTitle() else return love.graphics.getCaption() end end glove.window.getTitle = getTitle glove.graphics.getCaption = getTitle local function setTitle(title) if love.window and love.window.setTitle then return love.window.setTitle(title) else return love.graphics.setCaption(title) end end glove.window.setTitle = setTitle glove.graphics.setCaption = setTitle local function getDimensions(title) if love.graphics.getDimensions then return love.graphics.getDimensions() else return love.graphics.getWidth(), love.graphics.getHeight() end end glove.window.getDimensions = getDimensions glove.graphics.getDimensions = getDimensions --glove.window.hasFocus --glove.window.hasMouseFocus --glove.window.isCreated --glove.window.isVisible --glove.window.setFullscreen --glove.window.setIcon --glove.window.setMode return glove
-- Glove is a compatibility layer -- So that you can write LOVE modules -- That work on 0.8.0, 0.9.0, and 0.9.1 -- -- The local functions are named after 0.8.0 local glove = {} -- Features local love9 = love._version == "0.9.0" or love._version == "0.9.1" local love8 = love._version == "0.8.0" require "love.filesystem" require "love.graphics" if love9 then require "love.window" require "love.system" end glove.system = {} glove.filesystem = {} glove.window = {} glove.graphics = {} glove.thread = {} -- https://love2d.org/wiki/love.system.getOS function getOS() if love8 then return love._os end return love.system.getOS() end glove._os = getOS() glove.system.getOS = getOS -- https://love2d.org/wiki/love.graphics.getFont function getFont() if love8 then return love.graphics.newFont(love.graphics.getFont()) end return love.graphics.getFont() end glove.graphics.getFont = getFont --http://www.love2d.org/wiki/love.graphics.newStencil local function newStencil (stencilFunction) if love.graphics.newStencil then return love.graphics.newStencil(stencilFunction) else return stencilFunction end end glove.graphics.newStencil = newStencil --http://www.love2d.org/wiki/love.graphics.setLine local function setLine (width, style) if love.graphics.setLine then love.graphics.setLine(width, style) else love.graphics.setLineWidth(width) love.graphics.setLineStyle(style) end end glove.graphics.setLine = setLine --http://www.love2d.org/wiki/love.graphics.setLine local function setPoint (size, style) if love.graphics.setPoint then love.graphics.setPoint(size, style) else love.graphics.setPointSize(size) love.graphics.setPointStyle(style) end end glove.graphics.setPoint = setPoint -- http://www.love2d.org/wiki/love.filesystem.enumerate local function enumerate(dir) if love.filesystem.enumerate then return love.filesystem.enumerate(dir) else return love.filesystem.getDirectoryItems(dir) end end glove.filesystem.enumerate = enumerate glove.filesystem.getDirectoryItems = enumerate -- http://www.love2d.org/wiki/love.filesystem.mkdir local function mkdir(name) if love.filesystem.mkdir then return love.filesystem.mkdir(name) else return love.filesystem.createDirectory(name) end end glove.filesystem.mkdir = mkdir glove.filesystem.createDirectory = mkdir function glove.filesystem.isFused() if love.filesystem.isFused then return love.filesystem.isFused() else local datadir = love.filesystem.getAppdataDirectory() local savedir = love.filesystem.getSaveDirectory() local fragment = savedir:sub(datadir:len() + 2) local start, stop = nil if love._os == "Linux" then start, stop = fragment:find("love/") else start, stop = fragment:find("LOVE/") end return (start ~= 1 and stop ~= 5) end end -- The NamedThread class provides the Love 0.8.0 -- thread interface in Love 0.9.0 local NamedThread = {} NamedThread.__index = NamedThread function NamedThread:init(name, filedata) self.thread = love.thread.newThread(filedata) self.name = name end function NamedThread:start() return self.thread:start() end function NamedThread:wait() return self.thread:wait() end function NamedThread:set(name, value) local channel = love.thread.getChannel(name) return channel:push(value) end function NamedThread:peek(name) local channel = love.thread.getChannel(name) return channel:peek() end function NamedThread:get(name) if name == "error" then return self.thread:getError() end local channel = love.thread.getChannel(name) return channel:pop() end function NamedThread:demand(name) local channel = love.thread.getChannel(name) return channel:demand() end local _threads = {} -- http://www.love2d.org/wiki/love.thread.newThread local function newThread(name, filedata) if love8 then return love.thread.newThread(name, filedata) end if _threads[name] then error("A thread with that name already exists.") end local thread = {} setmetatable(thread, NamedThread) thread:init(name, filedata) -- Mark this name as taken _threads[name] = true return thread end local function getThread() if love.thread.getThread then return love.thread.getThread() end local thread = {} setmetatable(thread, NamedThread) return thread end glove.thread.newThread = newThread glove.thread.getThread = getThread --glove.window.getDesktopDimension --glove.window.getFullscreen --glove.window.getFullscreenModes --glove.window.getIcon --glove.window.getMode local function getHeight() return love.graphics.getHeight() end local function getWidth() return love.graphics.getWidth() end glove.window.getHeight = getHeight glove.window.getWidth = getWidth glove.graphics.getHeight = getHeight glove.graphics.getWidth = getWidth local function getTitle() if love.window and love.window.getTitle then return love.window.getTitle() else return love.graphics.getCaption() end end glove.window.getTitle = getTitle glove.graphics.getCaption = getTitle local function setTitle(title) if love.window and love.window.setTitle then return love.window.setTitle(title) else return love.graphics.setCaption(title) end end glove.window.setTitle = setTitle glove.graphics.setCaption = setTitle local function getDimensions(title) if love.graphics.getDimensions then return love.graphics.getDimensions() else return love.graphics.getWidth(), love.graphics.getHeight() end end glove.window.getDimensions = getDimensions glove.graphics.getDimensions = getDimensions --glove.window.hasFocus --glove.window.hasMouseFocus --glove.window.isCreated --glove.window.isVisible --glove.window.setFullscreen --glove.window.setIcon --glove.window.setMode return glove
Added setPoint
Added setPoint This is the same fix as setLine really.
Lua
mit
stackmachine/glove
562055681c1ccf3b47857864d9363fb985ed7fac
packages/twoside/init.lua
packages/twoside/init.lua
local base = require("packages.base") local package = pl.class(base) package._name = "twoside" local _odd = true local mirrorMaster = function (_, existing, new) -- Frames in one master can't "see" frames in another, so we have to get creative -- XXX This knows altogether too much about the implementation of masters if not SILE.scratch.masters[new] then SILE.scratch.masters[new] = {frames={}} end if not SILE.scratch.masters[existing] then SU.error("Can't find master "..existing) end for name, frame in pairs(SILE.scratch.masters[existing].frames) do local newframe = pl.tablex.deepcopy(frame) if frame:isAbsoluteConstraint("right") then newframe.constraints.left = "100%pw-("..frame.constraints.right..")" end if frame:isAbsoluteConstraint("left") then newframe.constraints.right = "100%pw-("..frame.constraints.left..")" end SILE.scratch.masters[new].frames[name] = newframe if frame == SILE.scratch.masters[existing].firstContentFrame then SILE.scratch.masters[new].firstContentFrame = newframe end end end function package:oddPage () return _odd end local function switchPage (class) _odd = not class:oddPage() local nextmaster = _odd and class.oddPageMaster or class.evenPageMaster class:switchMaster(nextmaster) end local _deprecate = [[ Directly calling master switch handling functions is no longer necessary. All the SILE core classes and anything inheriting from them will take care of this automatically using hooks. Custom classes that override the class:newPage() function may need to handle this in other ways. By calling this hook directly you are likely causing it to run twice and duplicate entries. ]] function package:_init (options) base._init(self) if not SILE.scratch.masters then SU.error("Cannot load twoside package before masters.") end self:export("oddPage", self.oddPage) self:export("mirrorMaster", mirrorMaster) self:export("switchPage", function (class) SU.deprecated("class:switchPage", nil, "0.13.0", "0.15.0", _deprecate) return class:switchPage() end) self.class.oddPageMaster = options.oddPageMaster self.class.evenPageMaster = options.evenPageMaster self.class:registerPostinit(function (class) class:mirrorMaster(options.oddPageMaster, options.evenPageMaster) end) self.class:registerHook("newpage", switchPage) end function package:registerCommands () self:registerCommand("open-double-page", function() SILE.typesetter:leaveHmode() SILE.call("supereject") if self.class:oddPage() then SILE.typesetter:typeset("") SILE.typesetter:leaveHmode() SILE.call("supereject") end SILE.typesetter:leaveHmode() end) end package.documentation = [[ \begin{document} The \code{book} class described in chapter 4 sets up left and right mirrored page masters; the \autodoc:package{twoside} package is responsible for swapping between the two left and right frames, running headers and so on. It has no user-serviceable parts. \end{document} ]] return package
local base = require("packages.base") local package = pl.class(base) package._name = "twoside" local _odd = true local mirrorMaster = function (_, existing, new) -- Frames in one master can't "see" frames in another, so we have to get creative -- XXX This knows altogether too much about the implementation of masters if not SILE.scratch.masters[new] then SILE.scratch.masters[new] = {frames={}} end if not SILE.scratch.masters[existing] then SU.error("Can't find master "..existing) end for name, frame in pairs(SILE.scratch.masters[existing].frames) do local newframe = pl.tablex.deepcopy(frame) if frame:isAbsoluteConstraint("right") then newframe.constraints.left = "100%pw-("..frame.constraints.right..")" end if frame:isAbsoluteConstraint("left") then newframe.constraints.right = "100%pw-("..frame.constraints.left..")" end SILE.scratch.masters[new].frames[name] = newframe if frame == SILE.scratch.masters[existing].firstContentFrame then SILE.scratch.masters[new].firstContentFrame = newframe end end end function package.oddPage (_) return _odd end local function switchPage (class) _odd = not class:oddPage() local nextmaster = _odd and class.oddPageMaster or class.evenPageMaster class:switchMaster(nextmaster) end local _deprecate = [[ Directly calling master switch handling functions is no longer necessary. All the SILE core classes and anything inheriting from them will take care of this automatically using hooks. Custom classes that override the class:newPage() function may need to handle this in other ways. By calling this hook directly you are likely causing it to run twice and duplicate entries. ]] local spread_counter = 0 local spreadHook = function () spread_counter = spread_counter + 1 end function package:_init (options) base._init(self) if not SILE.scratch.masters then SU.error("Cannot load twoside package before masters.") end self:export("oddPage", self.oddPage) self:export("mirrorMaster", mirrorMaster) self:export("switchPage", function (class) SU.deprecated("class:switchPage", nil, "0.13.0", "0.15.0", _deprecate) return class:switchPage() end) self.class.oddPageMaster = options.oddPageMaster self.class.evenPageMaster = options.evenPageMaster self.class:registerPostinit(function (class) class:mirrorMaster(options.oddPageMaster, options.evenPageMaster) end) self.class:registerHook("newpage", spreadHook) self.class:registerHook("newpage", switchPage) end function package:registerCommands () self:registerCommand("open-double-page", function() spread_counter = 0 SILE.typesetter:leaveHmode() -- Output a box, then nuke it otherwise we can't prove what page new content will land on SILE.call("hbox"); SILE.typesetter:leaveHmode(); table.remove(SILE.typesetter.state.nodes) if spread_counter == 1 and self.class:oddPage() then SILE.typesetter.state.outputQueue = {} return end local startedattop = #SILE.typesetter.state.outputQueue == 2 and #SILE.typesetter.state.nodes == 0 local spread_counter_at_start = spread_counter repeat if spread_counter > 0 then SILE.call("hbox") SILE.typesetter:leaveHmode() end SILE.call("supereject") SILE.typesetter:leaveHmode() until self.class:oddPage() end) end package.documentation = [[ \begin{document} The \code{book} class described in chapter 4 sets up left and right mirrored page masters; the \autodoc:package{twoside} package is responsible for swapping between the two left and right frames, running headers and so on. It has no user-serviceable parts. \end{document} ]] return package
fix(packages): Fix over-aggressive eject in \open-double-page
fix(packages): Fix over-aggressive eject in \open-double-page The original implementation left hmode *AND* forces an eject before starting processing. In rare cases where this is called very close to a page being full it would actually result in two pages being emitted rather than one before starting to iterate for odd pages. This implementation borrowed from CaSILE's \open-spread function is more robust in catching that condition by considering whether the odd page requirement might be met after the first eject.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
2b11071fbe28af58ba237659b51a5b93ec6f1b12
Ace3.lua
Ace3.lua
-- This file is only there in standalone Ace3 and provides handy dev tool stuff I guess -- for now only /rl to reload your UI :) -- note the complete overkill use of AceAddon and console, ain't it cool? local gui = LibStub("AceGUI-3.0") local reg = LibStub("AceConfigRegistry-3.0") local dialog = LibStub("AceConfigDialog-3.0") Ace3 = LibStub("AceAddon-3.0"):NewAddon("Ace3", "AceConsole-3.0") local Ace3 = Ace3 local selectedgroup local frame local select local status = {} local configs = {} local function frameOnClose() gui:Release(frame) frame = nil end local function RefreshConfigs() for name in reg:IterateOptionsTables() do configs[name] = name end end local function ConfigSelected(widget, event, value) selectedgroup = value dialog:Open(value, widget) end function Ace3:Open() RefreshConfigs() if next(configs) == nil then self:Print("No Configs are Registered") return end frame = frame or gui:Create("Frame") frame:ReleaseChildren() frame:SetTitle("Ace3 Options") frame:SetLayout("FILL") frame:SetCallback("OnClose", frameOnClose) select = select or gui:Create("DropdownGroup") select:SetGroupList(configs) select:SetCallback("OnGroupSelected", ConfigSelected) if not selectedgroup then selectedgroup = next(configs) end select:SetGroup(selectedgroup) frame:AddChild(select) frame:Show() end function Ace3:PrintCmd(input) input = input:trim():match("^(.-);*$") local func, err = loadstring("LibStub(\"AceConsole-3.0\"):Print(" .. input .. ")") if not func then LibStub("AceConsole-3.0"):Print("Error: " .. err) else func() end end function Ace3:OnInitialize() self:RegisterChatCommand("ace3", function() self:Open() end ) self:RegisterChatCommand("rl", function() ReloadUI() end ) self:RegisterChatCommand("print", "PrintCmd") end
-- This file is only there in standalone Ace3 and provides handy dev tool stuff I guess -- for now only /rl to reload your UI :) -- note the complete overkill use of AceAddon and console, ain't it cool? local gui = LibStub("AceGUI-3.0") local reg = LibStub("AceConfigRegistry-3.0") local dialog = LibStub("AceConfigDialog-3.0") Ace3 = LibStub("AceAddon-3.0"):NewAddon("Ace3", "AceConsole-3.0") local Ace3 = Ace3 local selectedgroup local frame local select local status = {} local configs = {} local function frameOnClose() gui:Release(frame) frame = nil end local function RefreshConfigs() for name in reg:IterateOptionsTables() do configs[name] = name end end local function ConfigSelected(widget, event, value) selectedgroup = value dialog:Open(value, widget) end function Ace3:Open() RefreshConfigs() if next(configs) == nil then self:Print("No Configs are Registered") return end if not frame then frame = gui:Create("Frame") frame:ReleaseChildren() frame:SetTitle("Ace3 Options") frame:SetLayout("FILL") frame:SetCallback("OnClose", frameOnClose) select = gui:Create("DropdownGroup") select:SetGroupList(configs) select:SetCallback("OnGroupSelected", ConfigSelected) frame:AddChild(select) end if not selectedgroup then selectedgroup = next(configs) end select:SetGroup(selectedgroup) frame:Show() end function Ace3:PrintCmd(input) input = input:trim():match("^(.-);*$") local func, err = loadstring("LibStub(\"AceConsole-3.0\"):Print(" .. input .. ")") if not func then LibStub("AceConsole-3.0"):Print("Error: " .. err) else func() end end function Ace3:OnInitialize() self:RegisterChatCommand("ace3", function() self:Open() end ) self:RegisterChatCommand("rl", function() ReloadUI() end ) self:RegisterChatCommand("print", "PrintCmd") end
Ace3 - potential fix for the /ace3 command being able to be used more then once
Ace3 - potential fix for the /ace3 command being able to be used more then once git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@425 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
7773cbd86676cc0e29e90241647f36041c165d64
benchmark/set_sequential.lua
benchmark/set_sequential.lua
-- example dynamic request script which demonstrates changing -- the request path and a header for each request ------------------------------------------------------------- -- NOTE: each wrk thread has an independent Lua scripting -- context and thus there will be one counter per thread counter = 0 init = function(args) wrk.init(args) pipeline_length = tonumber(args[1]) or 1 local r = {} for i=1,pipeline_length do counter = counter + 1 h = { keyspace = "database", key = counter, value = counter } r[i] = wrk.format("PUT", "/", h) end req = table.concat(r) end request = function() return req end
-- example dynamic request script which demonstrates changing -- the request path and a header for each request ------------------------------------------------------------- -- NOTE: each wrk thread has an independent Lua scripting -- context and thus there will be one counter per thread counter = 0 init = function(args) wrk.init(args) pipeline_length = tonumber(args[1]) or 1 local r = {} for i=1,pipeline_length do counter = counter + 1 padded_value = string.format("%010d", counter) h = { keyspace = "database", key = padded_value, value = padded_value } r[i] = wrk.format("PUT", "/", h) end req = table.concat(r) end request = function() return req end
Fixed script to actually be sequential since it was actually random due to the integers being treated as strings.
Fixed script to actually be sequential since it was actually random due to the integers being treated as strings.
Lua
apache-2.0
kellabyte/hellcat,kellabyte/hellcat,kellabyte/hellcat
48610006d548421338e755c0c17a0313d3507c04
frontend/ui/networkmgr.lua
frontend/ui/networkmgr.lua
local InfoMessage = require("ui/widget/infomessage") local ConfirmBox = require("ui/widget/confirmbox") local UIManager = require("ui/uimanager") local Device = require("device") local DEBUG = require("dbg") local _ = require("gettext") local NetworkMgr = {} local function kindleEnableWifi(toggle) local lipc = require("liblipclua") local lipc_handle = nil if lipc then lipc_handle = lipc.init("com.github.koreader.networkmgr") end if lipc_handle then lipc_handle:set_int_property("com.lab126.cmd", "wirelessEnable", toggle) lipc_handle:close() end end local function koboEnableWifi(toggle) if toggle == 1 then local path = "/etc/wpa_supplicant/wpa_supplicant.conf" os.execute("insmod /drivers/ntx508/wifi/sdio_wifi_pwr.ko 2>/dev/null") os.execute("insmod /drivers/ntx508/wifi/dhd.ko") os.execute("sleep 1") os.execute("ifconfig eth0 up") os.execute("wlarm_le -i eth0 up") os.execute("wpa_supplicant -s -i eth0 -c "..path.." -C /var/run/wpa_supplicant -B") os.execute("udhcpc -S -i eth0 -s /etc/udhcpc.d/default.script -t15 -T10 -A3 -b -q >/dev/null 2>&1") else os.execute("killall udhcpc wpa_supplicant 2>/dev/null") os.execute("wlarm_le -i eth0 down") os.execute("ifconfig eth0 down") os.execute("rmmod -r dhd") os.execute("rmmod -r sdio_wifi_pwr") end end function NetworkMgr:turnOnWifi() if Device:isKindle() then kindleEnableWifi(1) elseif Device:isKobo() then koboEnableWifi(1) end end function NetworkMgr:turnOffWifi() if Device:isKindle() then kindleEnableWifi(0) elseif Device:isKobo() then koboEnableWifi(0) end end function NetworkMgr:promptWifiOn() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn on Wifi?"), ok_callback = function() self:turnOnWifi() end, }) end function NetworkMgr:promptWifiOff() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn off Wifi?"), ok_callback = function() self:turnOffWifi() end, }) end function NetworkMgr:getWifiStatus() local default_string = io.popen("ip r | grep default") local result = default_string:read() if result ~= nil then local gateway = string.match(result,"%d+.%d+.%d+.%d+") if os.execute("ping -q -c1 "..gateway) == 0 then return true end -- ping to gateway end -- test for empty string return false end function NetworkMgr:setHTTPProxy(proxy) local http = require("socket.http") http.PROXY = proxy if proxy then G_reader_settings:saveSetting("http_proxy", proxy) G_reader_settings:saveSetting("http_proxy_enabled", true) else G_reader_settings:saveSetting("http_proxy_enabled", false) end end function NetworkMgr:getWifiMenuTable() return { text = _("Wifi connection"), enabled_func = function() return Device:isKindle() or Device:isKobo() end, checked_func = function() return NetworkMgr:getWifiStatus() end, callback = function() if NetworkMgr:getWifiStatus() then NetworkMgr:promptWifiOff() else NetworkMgr:promptWifiOn() end end } end function NetworkMgr:getProxyMenuTable() local proxy_enabled = function() return G_reader_settings:readSetting("http_proxy_enabled") end local proxy = function() return G_reader_settings:readSetting("http_proxy") end return { text_func = function() return _("HTTP proxy ") .. (proxy_enabled() and proxy() or "") end, checked_func = function() return proxy_enabled() end, callback = function() if not proxy_enabled() and proxy() then NetworkMgr:setHTTPProxy(proxy()) elseif proxy_enabled() then NetworkMgr:setHTTPProxy(nil) end if not proxy() then UIManager:show(InfoMessage:new{ text = _("Tips:\nlong press on this menu entry to configure HTTP proxy."), }) end end, hold_input = { title = _("input proxy address"), type = "text", hint = proxy() or "", callback = function(input) if input ~= "" then NetworkMgr:setHTTPProxy(input) end end, } } end -- set network proxy if global variable NETWORK_PROXY is defined if NETWORK_PROXY then NetworkMgr:setHTTPProxy(NETWORK_PROXY) end return NetworkMgr
local InfoMessage = require("ui/widget/infomessage") local ConfirmBox = require("ui/widget/confirmbox") local UIManager = require("ui/uimanager") local Device = require("device") local DEBUG = require("dbg") local _ = require("gettext") local NetworkMgr = {} local function kindleEnableWifi(toggle) local lipc = require("liblipclua") local lipc_handle = nil if lipc then lipc_handle = lipc.init("com.github.koreader.networkmgr") end if lipc_handle then lipc_handle:set_int_property("com.lab126.cmd", "wirelessEnable", toggle) lipc_handle:close() end end local function koboEnableWifi(toggle) if toggle == 1 then local path = "/etc/wpa_supplicant/wpa_supplicant.conf" os.execute("insmod /drivers/ntx508/wifi/sdio_wifi_pwr.ko 2>/dev/null") os.execute("insmod /drivers/ntx508/wifi/dhd.ko") os.execute("sleep 1") os.execute("ifconfig eth0 up") os.execute("wlarm_le -i eth0 up") os.execute("wpa_supplicant -s -i eth0 -c "..path.." -C /var/run/wpa_supplicant -B") os.execute("udhcpc -S -i eth0 -s /etc/udhcpc.d/default.script -t15 -T10 -A3 -b -q >/dev/null 2>&1") else os.execute("killall udhcpc wpa_supplicant 2>/dev/null") os.execute("wlarm_le -i eth0 down") os.execute("ifconfig eth0 down") os.execute("rmmod -r dhd") os.execute("rmmod -r sdio_wifi_pwr") end end function NetworkMgr:turnOnWifi() if Device:isKindle() then kindleEnableWifi(1) elseif Device:isKobo() then koboEnableWifi(1) end end function NetworkMgr:turnOffWifi() if Device:isKindle() then kindleEnableWifi(0) elseif Device:isKobo() then koboEnableWifi(0) end end function NetworkMgr:promptWifiOn() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn on Wifi?"), ok_callback = function() self:turnOnWifi() end, }) end function NetworkMgr:promptWifiOff() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn off Wifi?"), ok_callback = function() self:turnOffWifi() end, }) end function NetworkMgr:getWifiStatus() local default_string = io.popen("ip r | grep default") if not default_string then return false end local result = default_string:read() default_string:close() if result ~= nil then local gateway = string.match(result,"%d+.%d+.%d+.%d+") if gateway and os.execute("ping -q -c1 "..gateway) == 0 then return true end -- ping to gateway end -- test for empty string return false end function NetworkMgr:setHTTPProxy(proxy) local http = require("socket.http") http.PROXY = proxy if proxy then G_reader_settings:saveSetting("http_proxy", proxy) G_reader_settings:saveSetting("http_proxy_enabled", true) else G_reader_settings:saveSetting("http_proxy_enabled", false) end end function NetworkMgr:getWifiMenuTable() return { text = _("Wifi connection"), enabled_func = function() return Device:isKindle() or Device:isKobo() end, checked_func = function() return NetworkMgr:getWifiStatus() end, callback = function() if NetworkMgr:getWifiStatus() then NetworkMgr:promptWifiOff() else NetworkMgr:promptWifiOn() end end } end function NetworkMgr:getProxyMenuTable() local proxy_enabled = function() return G_reader_settings:readSetting("http_proxy_enabled") end local proxy = function() return G_reader_settings:readSetting("http_proxy") end return { text_func = function() return _("HTTP proxy ") .. (proxy_enabled() and proxy() or "") end, checked_func = function() return proxy_enabled() end, callback = function() if not proxy_enabled() and proxy() then NetworkMgr:setHTTPProxy(proxy()) elseif proxy_enabled() then NetworkMgr:setHTTPProxy(nil) end if not proxy() then UIManager:show(InfoMessage:new{ text = _("Tips:\nlong press on this menu entry to configure HTTP proxy."), }) end end, hold_input = { title = _("input proxy address"), type = "text", hint = proxy() or "", callback = function(input) if input ~= "" then NetworkMgr:setHTTPProxy(input) end end, } } end -- set network proxy if global variable NETWORK_PROXY is defined if NETWORK_PROXY then NetworkMgr:setHTTPProxy(NETWORK_PROXY) end return NetworkMgr
fix a case when "ip r" command fails
fix a case when "ip r" command fails our network manager script isn't the beauty of the code base. However, this fixes a case where it would crash the reader when an external command fails. fixes #1279.
Lua
agpl-3.0
mwoz123/koreader,apletnev/koreader,lgeek/koreader,ashhher3/koreader,chihyang/koreader,houqp/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,NickSavage/koreader,robert00s/koreader,pazos/koreader,mihailim/koreader,chrox/koreader,ashang/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,Hzj-jie/koreader,noname007/koreader,frankyifei/koreader,Frenzie/koreader,poire-z/koreader,Markismus/koreader
1613ec16e8141f07b8cd5757d165a59001a84ff4
SVUI_Skins/components/blizzard/worldmap.lua
SVUI_Skins/components/blizzard/worldmap.lua
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## HELPERS ########################################################## ]]-- local function AdjustMapLevel() if InCombatLockdown()then return end local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame:SetFrameStrata("HIGH"); WorldMapTooltip:SetFrameStrata("TOOLTIP"); WorldMapFrame:SetFrameLevel(1) QuestScrollFrame.DetailFrame:SetFrameLevel(2) end local function WorldMap_SmallView() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.Panel:ClearAllPoints() WorldMapFrame.Panel:WrapPoints(WorldMapFrame, 4, 4) if(SVUI_WorldMapCoords) then SVUI_WorldMapCoords:SetPoint("BOTTOMLEFT", WorldMapFrame, "BOTTOMLEFT", 5, 5) end end local function WorldMap_FullView() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.Panel:ClearAllPoints() local w, h = WorldMapDetailFrame:GetSize() WorldMapFrame.Panel:SetSize(w + 24, h + 98) WorldMapFrame.Panel:SetPoint("TOP", WorldMapFrame, "TOP", 0, 0) if(SVUI_WorldMapCoords) then SVUI_WorldMapCoords:SetPoint("BOTTOMLEFT", WorldMapFrame, "BOTTOMLEFT", 5, 5) end end local function StripQuestMapFrame() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.BorderFrame:RemoveTextures(true); WorldMapFrame.NavBar:RemoveTextures(true); WorldMapFrame.NavBar.overlay:RemoveTextures(true); QuestMapFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame.CompleteQuestFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame.CompleteQuestFrame.CompleteButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.BackButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.AbandonButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.ShareButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.TrackButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.RewardsFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame:SetStyle("Frame", "Paper") QuestMapFrame.DetailsFrame.CompleteQuestFrame.CompleteButton:SetStyle("Button") QuestMapFrame.DetailsFrame.BackButton:SetStyle("Button") QuestMapFrame.DetailsFrame.AbandonButton:SetStyle("Button") QuestMapFrame.DetailsFrame.ShareButton:SetStyle("Button") QuestMapFrame.DetailsFrame.TrackButton:SetStyle("Button") SV.API:Set("ScrollBar", QuestMapDetailsScrollFrame) SV.API:Set("Skin", QuestMapFrame.DetailsFrame.RewardsFrame, 0, -10, 0, 0) local detailWidth = QuestMapFrame.DetailsFrame.RewardsFrame:GetWidth() QuestMapFrame.DetailsFrame:ClearAllPoints() QuestMapFrame.DetailsFrame:SetPoint("BOTTOMRIGHT", QuestMapFrame, "BOTTOMRIGHT", 4, -50) QuestMapFrame.DetailsFrame:SetWidth(detailWidth) end --[[ ########################################################## WORLDMAP MODR ########################################################## ]]-- local function WorldMapStyle() --print('test WorldMapStyle') if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.worldmap ~= true then return end SV.API:Set("Window", WorldMapFrame, true, true) SV.API:Set("ScrollBar", QuestScrollFrame) SV.API:Set("ScrollBar", WorldMapQuestScrollFrame) SV.API:Set("ScrollBar", WorldMapQuestDetailScrollFrame, 4) SV.API:Set("ScrollBar", WorldMapQuestRewardScrollFrame, 4) QuestScrollFrame.DetailFrame:SetStyle("Frame", "Blackout") WorldMapFrameCloseButton:SetFrameLevel(999) SV.API:Set("CloseButton", WorldMapFrameCloseButton) SV.API:Set("DropDown", WorldMapLevelDropDown) SV.API:Set("DropDown", WorldMapZoneMinimapDropDown) SV.API:Set("DropDown", WorldMapContinentDropDown) SV.API:Set("DropDown", WorldMapZoneDropDown) SV.API:Set("DropDown", WorldMapShowDropDown) --print('test WorldMapStyle 3') StripQuestMapFrame() -- Movable Window WorldMapFrame:SetMovable(true) WorldMapFrame:EnableMouse(true) WorldMapFrame:RegisterForDrag("LeftButton") WorldMapFrame:SetScript("OnDragStart", WorldMapFrame.StartMoving) WorldMapFrame:SetScript("OnDragStop", WorldMapFrame.StopMovingOrSizing) end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveCustomStyle("WORLDMAP", WorldMapStyle)
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## HELPERS ########################################################## ]]-- local function AdjustMapLevel() if InCombatLockdown()then return end local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame:SetFrameStrata("HIGH"); WorldMapTooltip:SetFrameStrata("TOOLTIP"); WorldMapFrame:SetFrameLevel(1) QuestScrollFrame.DetailFrame:SetFrameLevel(2) end local function WorldMap_SmallView() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.Panel:ClearAllPoints() WorldMapFrame.Panel:WrapPoints(WorldMapFrame, 4, 4) if(SVUI_WorldMapCoords) then SVUI_WorldMapCoords:SetPoint("BOTTOMLEFT", WorldMapFrame, "BOTTOMLEFT", 5, 5) end end local function WorldMap_FullView() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.Panel:ClearAllPoints() local w, h = WorldMapDetailFrame:GetSize() WorldMapFrame.Panel:SetSize(w + 24, h + 98) WorldMapFrame.Panel:SetPoint("TOP", WorldMapFrame, "TOP", 0, 0) if(SVUI_WorldMapCoords) then SVUI_WorldMapCoords:SetPoint("BOTTOMLEFT", WorldMapFrame, "BOTTOMLEFT", 5, 5) end end local function StripQuestMapFrame() local WorldMapFrame = _G.WorldMapFrame; WorldMapFrame.BorderFrame:RemoveTextures(true); WorldMapFrame.NavBar:RemoveTextures(true); WorldMapFrame.NavBar.overlay:RemoveTextures(true); QuestMapFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame.CompleteQuestFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame.CompleteQuestFrame.CompleteButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.BackButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.AbandonButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.ShareButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.TrackButton:RemoveTextures(true) QuestMapFrame.DetailsFrame.RewardsFrame:RemoveTextures(true) QuestMapFrame.DetailsFrame:SetStyle("Frame", "Paper") QuestMapFrame.DetailsFrame.CompleteQuestFrame.CompleteButton:SetStyle("Button") QuestMapFrame.DetailsFrame.BackButton:SetStyle("Button") QuestMapFrame.DetailsFrame.AbandonButton:SetStyle("Button") QuestMapFrame.DetailsFrame.ShareButton:SetStyle("Button") QuestMapFrame.DetailsFrame.TrackButton:SetStyle("Button") SV.API:Set("ScrollBar", QuestMapDetailsScrollFrame) SV.API:Set("Skin", QuestMapFrame.DetailsFrame.RewardsFrame, 0, -10, 0, 0) local detailWidth = QuestMapFrame.DetailsFrame.RewardsFrame:GetWidth() QuestMapFrame.DetailsFrame:ClearAllPoints() QuestMapFrame.DetailsFrame:SetPoint("BOTTOMRIGHT", QuestMapFrame, "BOTTOMRIGHT", 4, -50) QuestMapFrame.DetailsFrame:SetWidth(detailWidth) end --[[ ########################################################## WORLDMAP MODR ########################################################## ]]-- local function WorldMapStyle() --print('test WorldMapStyle') if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.worldmap ~= true then return end SV.API:Set("Window", WorldMapFrame, true, true) SV.API:Set("ScrollBar", QuestScrollFrame) SV.API:Set("ScrollBar", WorldMapQuestScrollFrame) SV.API:Set("ScrollBar", WorldMapQuestDetailScrollFrame, 4) SV.API:Set("ScrollBar", WorldMapQuestRewardScrollFrame, 4) QuestScrollFrame.DetailFrame:SetStyle("Frame", "Blackout") WorldMapFrame.BorderFrame.NineSlice:RemoveTextures(true); WorldMapFrameCloseButton:SetFrameLevel(999) SV.API:Set("CloseButton", WorldMapFrameCloseButton) SV.API:Set("DropDown", WorldMapLevelDropDown) SV.API:Set("DropDown", WorldMapZoneMinimapDropDown) SV.API:Set("DropDown", WorldMapContinentDropDown) SV.API:Set("DropDown", WorldMapZoneDropDown) SV.API:Set("DropDown", WorldMapShowDropDown) --print('test WorldMapStyle 3') StripQuestMapFrame() -- Movable Window WorldMapFrame:SetMovable(true) WorldMapFrame:EnableMouse(true) WorldMapFrame:RegisterForDrag("LeftButton") WorldMapFrame:SetScript("OnDragStart", WorldMapFrame.StartMoving) WorldMapFrame:SetScript("OnDragStop", WorldMapFrame.StopMovingOrSizing) end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveCustomStyle("WORLDMAP", WorldMapStyle)
WorldMapFrame fix...
WorldMapFrame fix... Of course the worldmapframe is different...
Lua
mit
FailcoderAddons/supervillain-ui
9456f71e9c925b0cb3ff0cc80ba37844a0b44fb5
init.lua
init.lua
-- WAD SPRINTING minetest (https://minetest.net) mod (https://dev.minetest.net/Intro) -- @link https://github.com/aa6/minetest_wadsprint minetest_wadsprint = { players = {}, } dofile(minetest.get_modpath(minetest.get_current_modname()).."/config.lua") dofile(minetest.get_modpath(minetest.get_current_modname()).."/init_hudbars.lua") function minetest_wadsprint.update_player_properties(player) if player.is_sprinting then player.stamina = player.stamina - (minetest_wadsprint.STAMINA_MAX_VALUE * minetest_wadsprint.SPRINT_STAMINA_DECREASE_PER_UPDATE_PERIOD_COEFFICIENT) if player.stamina < 0 then player.stamina = 0 minetest_wadsprint.disable_sprinting(player) end elseif player.stamina < minetest_wadsprint.STAMINA_MAX_VALUE then player.stamina = player.stamina + (minetest_wadsprint.STAMINA_MAX_VALUE * minetest_wadsprint.SPRINT_STAMINA_INCREASE_PER_UPDATE_PERIOD_COEFFICIENT) end minetest_wadsprint.hudbar_update_stamina(player) end function minetest_wadsprint.enable_sprinting(player) if not player.is_sprinting then player.is_sprinting = true player.obj:set_physics_override( { jump = minetest_wadsprint.SPRINT_JUMP_HEIGHT_MODIFIER_COEFFICIENT, speed = minetest_wadsprint.SPRINT_SPEED_MODIFIER_COEFFICIENT, }) minetest_wadsprint.hudbar_update_ready_to_sprint(player) minetest_wadsprint.hudbar_update_stamina(player) end end function minetest_wadsprint.disable_sprinting(player) if player.is_sprinting then player.is_sprinting = false player.obj:set_physics_override( { jump = 1.0, speed = 1.0, }) minetest_wadsprint.hudbar_update_ready_to_sprint(player) minetest_wadsprint.hudbar_update_stamina(player) end end function minetest_wadsprint.set_ready_to_sprint(player,is_ready_to_sprint) if player.is_ready_to_sprint ~= is_ready_to_sprint then player.is_ready_to_sprint = is_ready_to_sprint minetest_wadsprint.hudbar_update_ready_to_sprint(player) else player.is_ready_to_sprint = is_ready_to_sprint end end function minetest_wadsprint.scan_player_controls(player) local control = player.obj:get_player_control() if not control["up"] then minetest_wadsprint.disable_sprinting(player) end if control["left"] and control["right"] then minetest_wadsprint.set_ready_to_sprint(player,true) if control["up"] then minetest_wadsprint.enable_sprinting(player) end else minetest_wadsprint.set_ready_to_sprint(player,false) end end minetest.register_on_joinplayer(function(player_obj) minetest_wadsprint.players[player_obj:get_player_name()] = { obj = player_obj, stamina = minetest_wadsprint.STAMINA_MAX_VALUE, is_sprinting = false, is_ready_to_sprint = false, } minetest_wadsprint.initialize_hudbar(minetest_wadsprint.players[player_obj:get_player_name()]) end) minetest.register_on_leaveplayer(function(player_obj) minetest_wadsprint.players[player_obj:get_player_name()] = nil end) -- Register hudbar call for compatibility with some hudbar mods. if minetest_wadsprint.register_hudbar ~= nil then minetest_wadsprint.register_hudbar() end -- Main cycle. local timer_controls_check = 0 local timer_properties_update = 0 minetest.register_globalstep(function(dtime) timer_controls_check = timer_controls_check + dtime timer_properties_update = timer_properties_update + dtime if timer_controls_check > minetest_wadsprint.PLAYER_CONTROLS_CHECK_PERIOD_SECONDS then timer_controls_check = 0 for player_name,player in pairs(minetest_wadsprint.players) do minetest_wadsprint.scan_player_controls(player) end end if timer_properties_update > minetest_wadsprint.PLAYER_STATS_UPDATE_PERIOD_SECONDS then timer_properties_update = 0 for player_name,player in pairs(minetest_wadsprint.players) do minetest_wadsprint.update_player_properties(player) end end end)
-- WAD SPRINTING minetest (https://minetest.net) mod (https://dev.minetest.net/Intro) -- @link https://github.com/aa6/minetest_wadsprint minetest_wadsprint = { players = {}, } dofile(minetest.get_modpath(minetest.get_current_modname()).."/config.lua") dofile(minetest.get_modpath(minetest.get_current_modname()).."/init_hudbars.lua") function minetest_wadsprint.update_player_properties(player) if player.is_sprinting then player.stamina = player.stamina - (minetest_wadsprint.STAMINA_MAX_VALUE * minetest_wadsprint.SPRINT_STAMINA_DECREASE_PER_UPDATE_PERIOD_COEFFICIENT) if player.stamina < 0 then player.stamina = 0 minetest_wadsprint.disable_sprinting(player) end elseif player.stamina < minetest_wadsprint.STAMINA_MAX_VALUE then player.stamina = player.stamina + (minetest_wadsprint.STAMINA_MAX_VALUE * minetest_wadsprint.SPRINT_STAMINA_INCREASE_PER_UPDATE_PERIOD_COEFFICIENT) if player.stamina > minetest_wadsprint.STAMINA_MAX_VALUE then player.stamina = minetest_wadsprint.STAMINA_MAX_VALUE end end minetest_wadsprint.hudbar_update_stamina(player) end function minetest_wadsprint.enable_sprinting(player) if not player.is_sprinting then player.is_sprinting = true player.obj:set_physics_override( { jump = minetest_wadsprint.SPRINT_JUMP_HEIGHT_MODIFIER_COEFFICIENT, speed = minetest_wadsprint.SPRINT_SPEED_MODIFIER_COEFFICIENT, }) minetest_wadsprint.hudbar_update_ready_to_sprint(player) minetest_wadsprint.hudbar_update_stamina(player) end end function minetest_wadsprint.disable_sprinting(player) if player.is_sprinting then player.is_sprinting = false player.obj:set_physics_override( { jump = 1.0, speed = 1.0, }) minetest_wadsprint.hudbar_update_ready_to_sprint(player) minetest_wadsprint.hudbar_update_stamina(player) end end function minetest_wadsprint.set_ready_to_sprint(player,is_ready_to_sprint) if player.is_ready_to_sprint ~= is_ready_to_sprint then player.is_ready_to_sprint = is_ready_to_sprint minetest_wadsprint.hudbar_update_ready_to_sprint(player) else player.is_ready_to_sprint = is_ready_to_sprint end end function minetest_wadsprint.scan_player_controls(player) local control = player.obj:get_player_control() if not control["up"] then minetest_wadsprint.disable_sprinting(player) end if control["left"] and control["right"] then minetest_wadsprint.set_ready_to_sprint(player,true) if control["up"] then minetest_wadsprint.enable_sprinting(player) end else minetest_wadsprint.set_ready_to_sprint(player,false) end end minetest.register_on_joinplayer(function(player_obj) minetest_wadsprint.players[player_obj:get_player_name()] = { obj = player_obj, stamina = minetest_wadsprint.STAMINA_MAX_VALUE, is_sprinting = false, is_ready_to_sprint = false, } minetest_wadsprint.initialize_hudbar(minetest_wadsprint.players[player_obj:get_player_name()]) end) minetest.register_on_leaveplayer(function(player_obj) minetest_wadsprint.players[player_obj:get_player_name()] = nil end) -- Register hudbar call for compatibility with some hudbar mods. if minetest_wadsprint.register_hudbar ~= nil then minetest_wadsprint.register_hudbar() end -- Main cycle. local timer_controls_check = 0 local timer_properties_update = 0 minetest.register_globalstep(function(dtime) timer_controls_check = timer_controls_check + dtime timer_properties_update = timer_properties_update + dtime if timer_controls_check > minetest_wadsprint.PLAYER_CONTROLS_CHECK_PERIOD_SECONDS then timer_controls_check = 0 for player_name,player in pairs(minetest_wadsprint.players) do minetest_wadsprint.scan_player_controls(player) end end if timer_properties_update > minetest_wadsprint.PLAYER_STATS_UPDATE_PERIOD_SECONDS then timer_properties_update = 0 for player_name,player in pairs(minetest_wadsprint.players) do minetest_wadsprint.update_player_properties(player) end end end)
Player stamina could be greater than max value fix
Player stamina could be greater than max value fix
Lua
agpl-3.0
aa6/minetest_wadsprint
2f4a5022655a2dc5c4b35181efbbb30ab2092707
main.lua
main.lua
io.stdout:setvbuf("no") local reboot, events = false --Internal Callbacks-- function love.load(args) love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run(arg) while true do events = require("Engine.events") events:register("love:reboot",function(args) --events:trigger("love:rebooting",args) reboot = args or {} end) if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(reboot or arg) end reboot = false -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v and v[1] then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end if reboot then for k,v in pairs(package.loaded) do package.loaded[k] = nil end --Reset the required packages events = nil --Must undefine this. break --Break our game loop end end end end
io.stdout:setvbuf("no") local reboot, events = false --Internal Callbacks-- function love.load(args) love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run(arg) while true do events = require("Engine.events") events:register("love:reboot",function(args) --events:trigger("love:rebooting",args) reboot = args or {} end) if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(reboot or arg) end reboot = false -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v and v[1] then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end if reboot then for k,v in pairs(package.loaded) do if k ~= "bit" then package.loaded[k] = nil end end--Reset the required packages events = nil --Must undefine this. break --Break our game loop end end end end
Bugfix for bitop on soft rebooting
Bugfix for bitop on soft rebooting
Lua
mit
RamiLego4Game/LIKO-12