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
|
|---|---|---|---|---|---|---|---|---|---|
e1ad94566cad1f276d88db9f55fc79777ba402f2
|
editor/lib/lua/editor/edit/EditorCanvasScene.lua
|
editor/lib/lua/editor/edit/EditorCanvasScene.lua
|
local Scene = require("scenes.Scene")
local InputDevice = require("input.InputDevice")
---------------------------------------------------------------------------------
--
-- @type EditorCanvasScene
--
---------------------------------------------------------------------------------
local EditorCanvasScene = Class( Scene, "EditorCanvasScene" )
function EditorCanvasScene:init( option )
Scene.init(self, option)
end
function EditorCanvasScene:setEnv( env )
self.env = env
self.contextName = env.contextName
end
function EditorCanvasScene:getEnv()
return self.env
end
function EditorCanvasScene:getContextName()
return self.contextName
end
function EditorCanvasScene:getCanvasSize()
local s = self.env.getCanvasSize()
return s[0], s[1]
end
function EditorCanvasScene:hideCursor()
return self.env.hideCursor()
end
function EditorCanvasScene:setCursor( id )
return self.env.setCursor( id )
end
function EditorCanvasScene:showCursor()
return self.env.showCursor()
end
function EditorCanvasScene:setCursorPos( x, y )
return self.env.setCursorPos( x, y )
end
function EditorCanvasScene:startUpdateTimer( fps )
return self.env.startUpdateTimer( fps )
end
function EditorCanvasScene:stopUpdateTimer()
return self.env.stopUpdateTimer()
end
---------------------------------------------------------------------------------
--
-- @type create methods
--
---------------------------------------------------------------------------------
function createEditorCanvasInputDevice( env )
local env = env or getfenv(2)
local inputDevice = InputDevice( assert(env.contextName), env )
function env.onMouseDown( btn, x, y )
inputDevice:sendMouseEvent( 'down', x, y, btn )
end
function env.onMouseUp( btn, x, y )
inputDevice:sendMouseEvent( 'up', x, y, btn )
end
function env.onMouseMove( x, y )
inputDevice:sendMouseEvent( 'move', x, y, false )
end
function env.onMouseScroll( dx, dy, x, y )
inputDevice:sendMouseEvent( 'scroll', dx, dy, false )
end
function env.onMouseEnter()
inputDevice:sendMouseEvent( 'enter' )
end
function env.onMouseLeave()
inputDevice:sendMouseEvent( 'leave' )
end
function env.onKeyDown( key )
inputDevice:sendKeyEvent( key, true )
end
function env.onKeyUp( key )
inputDevice:sendKeyEvent( key, false )
end
env._delegate:updateHooks()
return inputDevice
end
---------------------------------------------------------------------
function createEditorCanvasScene()
local env = getfenv( 2 )
local scene = EditorCanvasScene()
scene:setEnv( env )
-- FIXME
-- function env.onResize( w, h )
-- scene:resize( w, h )
-- scene.cameraCom:setScreenSize( w, h )
-- end
function env.onLoad()
end
local inputDevice = createEditorCanvasInputDevice( env )
scene.inputDevice = inputDevice
-- function env.EditorInputScript()
-- return mock.InputScript{ device = inputDevice }
-- end
return scene
end
|
local Scene = require("scenes.Scene")
local InputDevice = require("input.InputDevice")
---------------------------------------------------------------------------------
--
-- @type EditorCanvasScene
--
---------------------------------------------------------------------------------
local EditorCanvasScene = Class( Scene, "EditorCanvasScene" )
function EditorCanvasScene:init( option )
Scene.init(self, option)
end
function EditorCanvasScene:setEnv( env )
self.env = env
self.contextName = env.contextName
end
function EditorCanvasScene:getEnv()
return self.env
end
function EditorCanvasScene:getContextName()
return self.contextName
end
function EditorCanvasScene:getCanvasSize()
local s = self.env.getCanvasSize()
return s[0], s[1]
end
function EditorCanvasScene:hideCursor()
return self.env.hideCursor()
end
function EditorCanvasScene:setCursor( id )
return self.env.setCursor( id )
end
function EditorCanvasScene:showCursor()
return self.env.showCursor()
end
function EditorCanvasScene:setCursorPos( x, y )
return self.env.setCursorPos( x, y )
end
function EditorCanvasScene:startUpdateTimer( fps )
return self.env.startUpdateTimer( fps )
end
function EditorCanvasScene:stopUpdateTimer()
return self.env.stopUpdateTimer()
end
---------------------------------------------------------------------------------
--
-- @type create methods
--
---------------------------------------------------------------------------------
function createEditorCanvasInputDevice( env )
local env = env or getfenv(2)
local inputDevice = InputDevice( assert(env.contextName), env )
function env.onMouseDown( btn, x, y )
inputDevice:sendMouseEvent( 'down', x, y, btn )
end
function env.onMouseUp( btn, x, y )
inputDevice:sendMouseEvent( 'up', x, y, btn )
end
function env.onMouseMove( x, y )
inputDevice:sendMouseEvent( 'move', x, y, false )
end
function env.onMouseScroll( dx, dy, x, y )
inputDevice:sendMouseEvent( 'scroll', dx, dy, false )
end
function env.onMouseEnter()
inputDevice:sendMouseEvent( 'enter' )
end
function env.onMouseLeave()
inputDevice:sendMouseEvent( 'leave' )
end
function env.onKeyDown( key )
inputDevice:sendKeyEvent( key, true )
end
function env.onKeyUp( key )
inputDevice:sendKeyEvent( key, false )
end
env._delegate:updateHooks()
return inputDevice
end
---------------------------------------------------------------------
function createEditorCanvasScene()
local env = getfenv( 2 )
local scene = EditorCanvasScene( { viewport = MOAIViewport.new() } )
scene:setEnv( env )
-- FIXME
-- function env.onResize( w, h )
-- scene:resize( w, h )
-- -- scene.cameraCom:setScreenSize( w, h )
-- end
function env.onLoad()
end
local inputDevice = createEditorCanvasInputDevice( env )
scene.inputDevice = inputDevice
-- function env.EditorInputScript()
-- return mock.InputScript{ device = inputDevice }
-- end
return scene
end
|
canvas fix
|
canvas fix
|
Lua
|
mit
|
RazielSun/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,cloudteampro/juma-editor,cloudteampro/juma-editor
|
4b19c625027033d009884c63112fe2e58143ee42
|
spec/plugins/logging_spec.lua
|
spec/plugins/logging_spec.lua
|
local IO = require "kong.tools.io"
local uuid = require "uuid"
local cjson = require "cjson"
local stringy = require "stringy"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
-- This is important to seed the UUID generator
uuid.seed()
local STUB_GET_URL = spec_helper.STUB_GET_URL
local TCP_PORT = 20777
local UDP_PORT = 20778
local HTTP_PORT = 20779
local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log"
local function create_mock_bin()
local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" })
assert.are.equal(201, status)
return res:sub(2, res:len() - 1)
end
local mock_bin = create_mock_bin()
describe("Logging Plugins", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_PORT },
{ name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" },
{ name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" },
{ name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 },
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 },
{ name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 },
{ name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT }, __api = 4 },
{ name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 },
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should log to TCP", function()
local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log proper latencies", function()
local http_thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.truthy(log_message.latencies.proxy < 3000)
assert.truthy(log_message.latencies.kong < 20)
assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
it("should log to UDP", function()
local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTP", function()
local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
assert.are.same("POST / HTTP/1.1", res[1])
local log_message = cjson.decode(res[7])
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTPs", function()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" })
assert.are.equal(200, status)
local res, status, body
repeat
res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" })
assert.are.equal(200, status)
body = cjson.decode(res)
os.execute("sleep 0.2")
until(#body.log.entries > 0)
assert.are.equal(1, #body.log.entries)
local log_message = cjson.decode(body.log.entries[1].request.postData.text)
-- Making sure it's alright
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to file", function()
os.remove(FILE_LOG_PATH)
local uuid = string.gsub(uuid(), "-", "")
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{ host = "file_logging.com", file_log_uuid = uuid }
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("127.0.0.1", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
local IO = require "kong.tools.io"
local uuid = require "uuid"
local cjson = require "cjson"
local stringy = require "stringy"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
-- This is important to seed the UUID generator
uuid.seed()
local STUB_GET_URL = spec_helper.STUB_GET_URL
local TCP_PORT = 20777
local UDP_PORT = 20778
local HTTP_PORT = 20779
local HTTP_DELAY_PORT = 20780
local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log"
local function create_mock_bin()
local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" })
assert.are.equal(201, status)
return res:sub(2, res:len() - 1)
end
local mock_bin = create_mock_bin()
describe("Logging Plugins", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_DELAY_PORT },
{ name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" },
{ name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" },
{ name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 },
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 },
{ name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 },
{ name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT }, __api = 4 },
{ name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 },
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should log to TCP", function()
local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log proper latencies", function()
local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server
local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.truthy(log_message.latencies.proxy < 3000)
assert.truthy(log_message.latencies.kong < 100)
assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
it("should log to UDP", function()
local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTP", function()
local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
assert.are.same("POST / HTTP/1.1", res[1])
local log_message = cjson.decode(res[7])
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTPs", function()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" })
assert.are.equal(200, status)
local res, status, body
repeat
res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" })
assert.are.equal(200, status)
body = cjson.decode(res)
os.execute("sleep 0.2")
until(#body.log.entries > 0)
assert.are.equal(1, #body.log.entries)
local log_message = cjson.decode(body.log.entries[1].request.postData.text)
-- Making sure it's alright
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to file", function()
os.remove(FILE_LOG_PATH)
local uuid = string.gsub(uuid(), "-", "")
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{ host = "file_logging.com", file_log_uuid = uuid }
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("127.0.0.1", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
Fixing tests
|
Fixing tests
|
Lua
|
mit
|
paritoshmmmec/kong,vmercierfr/kong,wakermahmud/kong,bbalu/kong,chourobin/kong,AnsonSmith/kong,peterayeni/kong,skynet/kong,sbuettner/kong,Skyscanner/kong,ChristopherBiscardi/kong
|
4836018fda5aea2d4b54bb5cff58d191b2c602c0
|
agents/monitoring/default/protocol/request.lua
|
agents/monitoring/default/protocol/request.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 table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local stream = fs.createWriteStream(self.download)
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
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 table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local ok, stream = pcall(function()
return fs.createWriteStream(self.download)
end)
if not ok then
-- can't make the file because the dir doens't exist
if stream.code and stream.code == "ENOENT" then
return self.callback(stream)
end
return self:_ensure_retries(err, res)
end
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
return exports
|
Fix request.lua to handle trying to open a stupid file
|
Fix request.lua to handle trying to open a stupid file
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
b7b4a1558418d5999b9149f3e4dfdff27a6fa773
|
utils.lua
|
utils.lua
|
nn.utils = {}
function nn.utils.recursiveType(param, type_str)
if torch.type(param) == 'table' then
for k, v in pairs(param) do
param[k] = nn.utils.recursiveType(v, type_str)
end
elseif torch.isTypeOf(param, 'nn.Module') or
torch.isTypeOf(param, 'nn.Criterion') then
param:type(type_str)
elseif torch.isTensor(param) then
param = param:type(type_str)
end
return param
end
function nn.utils.recursiveResizeAs(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = nn.utils.recursiveResizeAs(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = torch.isTensor(t1) and t1 or t2.new()
t1:resizeAs(t2)
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function nn.utils.recursiveFill(t2, val)
if torch.type(t2) == 'table' then
for key,_ in pairs(t2) do
t2[key] = nn.utils.recursiveFill(t2[key], val)
end
elseif torch.isTensor(t2) then
t2:fill(val)
else
error("expecting tensor or table thereof. Got "
..torch.type(t2).." instead")
end
return t2
end
function nn.utils.recursiveAdd(t1, val, t2)
if not t2 then
assert(val, "expecting at least two arguments")
t2 = val
val = 1
end
val = val or 1
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = nn.utils.recursiveAdd(t1[key], val, t2[key])
end
elseif torch.isTensor(t2) and torch.isTensor(t2) then
t1:add(val, t2)
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function nn.utils.addSingletonDimension(t, dim)
assert(torch.isTensor(t), "input tensor expected")
local dim = dim or 1
assert(dim > 0 and dim <= t:dim(), "invalid dimension: " .. dim)
local view = t.new()
local size = torch.LongStorage(t:dim() + 1)
local stride = torch.LongStorage(t:dim() + 1)
for d = 1, dim - 1 do
size[d] = t:size(d)
stride[d] = t:stride(d)
end
size[dim] = 1
stride[dim] = 1
for d = dim + 1, t:dim() + 1 do
size[d] = t:size(d - 1)
stride[d] = t:stride(d - 1)
end
view:set(t:storage(), t:storageOffset(), size, stride)
return view
end
table.unpack = table.unpack or unpack
|
nn.utils = {}
function nn.utils.recursiveType(param, type_str)
if torch.type(param) == 'table' then
for k, v in pairs(param) do
param[k] = nn.utils.recursiveType(v, type_str)
end
elseif torch.isTypeOf(param, 'nn.Module') or
torch.isTypeOf(param, 'nn.Criterion') then
param:type(type_str)
elseif torch.isTensor(param) then
param = param:type(type_str)
end
return param
end
function nn.utils.recursiveResizeAs(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = nn.utils.recursiveResizeAs(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = torch.isTensor(t1) and t1 or t2.new()
t1:resizeAs(t2)
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function nn.utils.recursiveFill(t2, val)
if torch.type(t2) == 'table' then
for key,_ in pairs(t2) do
t2[key] = nn.utils.recursiveFill(t2[key], val)
end
elseif torch.isTensor(t2) then
t2:fill(val)
else
error("expecting tensor or table thereof. Got "
..torch.type(t2).." instead")
end
return t2
end
function nn.utils.recursiveAdd(t1, val, t2)
if not t2 then
assert(val, "expecting at least two arguments")
t2 = val
val = 1
end
val = val or 1
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = nn.utils.recursiveAdd(t1[key], val, t2[key])
end
elseif torch.isTensor(t2) and torch.isTensor(t2) then
t1:add(val, t2)
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function nn.utils.addSingletonDimension(t, dim)
assert(torch.isTensor(t), "input tensor expected")
local dim = dim or 1
assert(dim > 0 and dim <= (t:dim() + 1), "invalid dimension: " .. dim
.. '. Tensor is of ' .. t:dim() .. ' dimensions.')
local view = t.new()
local size = torch.LongStorage(t:dim() + 1)
local stride = torch.LongStorage(t:dim() + 1)
for d = 1, dim - 1 do
size[d] = t:size(d)
stride[d] = t:stride(d)
end
size[dim] = 1
stride[dim] = 1
for d = dim + 1, t:dim() + 1 do
size[d] = t:size(d - 1)
stride[d] = t:stride(d - 1)
end
view:set(t:storage(), t:storageOffset(), size, stride)
return view
end
table.unpack = table.unpack or unpack
|
fixing corner-case of last dimension in addSingletonDimension
|
fixing corner-case of last dimension in addSingletonDimension
|
Lua
|
bsd-3-clause
|
andreaskoepf/nn,sbodenstein/nn,lukasc-ch/nn,rotmanmi/nn,forty-2/nn,LinusU/nn,witgo/nn,GregSatre/nn,adamlerer/nn,PierrotLC/nn,colesbury/nn,Aysegul/nn,kmul00/nn,jzbontar/nn,mlosch/nn,xianjiec/nn,jonathantompson/nn,Djabbz/nn,nicholas-leonard/nn,eulerreich/nn,noa/nn,Jeffyrao/nn,diz-vara/nn,PraveerSINGH/nn,apaszke/nn,clementfarabet/nn,aaiijmrtt/nn,eriche2016/nn,EnjoyHacking/nn,davidBelanger/nn,ominux/nn,Moodstocks/nn,zhangxiangxiao/nn,joeyhng/nn,caldweln/nn,jhjin/nn,elbamos/nn,bartvm/nn,vgire/nn,ivendrov/nn,abeschneider/nn,douwekiela/nn,lvdmaaten/nn,sagarwaghmare69/nn,hughperkins/nn
|
1e491924ccad666ad42e30d30e2031662bc1d3d0
|
xmake/rules/utils/inherit_links/inherit_links.lua
|
xmake/rules/utils/inherit_links/inherit_links.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file inherit_links.lua
--
-- add values from target options
function _add_values_from_targetopts(values, target, name)
for _, opt in ipairs(target:orderopts()) do
table.join2(values, table.wrap(opt:get(name)))
end
end
-- add values from target packages
function _add_values_from_targetpkgs(values, target, name)
for _, pkg in ipairs(target:orderpkgs()) do
-- uses them instead of the builtin configs if exists extra package config
-- e.g. `add_packages("xxx", {links = "xxx"})`
local configinfo = target:pkgconfig(pkg:name())
if configinfo and configinfo[name] then
table.join2(values, configinfo[name])
else
-- uses the builtin package configs
table.join2(values, pkg:get(name))
end
end
end
-- get values from target
function _get_values_from_target(target, name)
local values = table.wrap(target:get(name))
_add_values_from_targetopts(values, target, name)
_add_values_from_targetpkgs(values, target, name)
return values
end
-- main entry
function main(target)
-- disable inherit.links for `add_deps()`?
if target:data("inherit.links") == false then
return
end
-- export links and linkdirs
local targetkind = target:targetkind()
local targetfile = target:targetfile()
if targetkind == "shared" or targetkind == "static" then
target:add("links", target:basename(), {interface = true})
target:add("linkdirs", path.directory(targetfile), {interface = true})
for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do
local values = _get_values_from_target(target, name)
if values and #values > 0 then
target:add(name, unpack(values), {interface = true})
end
end
end
-- export rpathdirs for all shared library
if targetkind == "binary" then
for _, dep in ipairs(target:orderdeps()) do
local rpathdir = "@loader_path"
local subdir = path.relative(path.directory(dep:targetfile()), path.directory(targetfile))
if subdir and subdir ~= '.' then
rpathdir = path.join(rpathdir, subdir)
end
target:add("rpathdirs", rpathdir)
end
end
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file inherit_links.lua
--
-- add values from target options
function _add_values_from_targetopts(values, target, name)
for _, opt in ipairs(target:orderopts()) do
table.join2(values, table.wrap(opt:get(name)))
end
end
-- add values from target packages
function _add_values_from_targetpkgs(values, target, name)
for _, pkg in ipairs(target:orderpkgs()) do
-- uses them instead of the builtin configs if exists extra package config
-- e.g. `add_packages("xxx", {links = "xxx"})`
local configinfo = target:pkgconfig(pkg:name())
if configinfo and configinfo[name] then
table.join2(values, configinfo[name])
else
-- uses the builtin package configs
table.join2(values, pkg:get(name))
end
end
end
-- get values from target
function _get_values_from_target(target, name)
local values = table.wrap(target:get(name))
_add_values_from_targetopts(values, target, name)
_add_values_from_targetpkgs(values, target, name)
return values
end
-- main entry
function main(target)
-- disable inherit.links for `add_deps()`?
if target:data("inherit.links") == false then
return
end
-- export links and linkdirs
local targetkind = target:targetkind()
if targetkind == "shared" or targetkind == "static" then
local targetfile = target:targetfile()
target:add("links", target:basename(), {interface = true})
target:add("linkdirs", path.directory(targetfile), {interface = true})
for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do
local values = _get_values_from_target(target, name)
if values and #values > 0 then
target:add(name, unpack(values), {interface = true})
end
end
end
-- export rpathdirs for all shared library
if targetkind == "binary" then
local targetdir = target:targetdir()
for _, dep in ipairs(target:orderdeps()) do
local rpathdir = "@loader_path"
local subdir = path.relative(path.directory(dep:targetfile()), targetdir)
if subdir and subdir ~= '.' then
rpathdir = path.join(rpathdir, subdir)
end
target:add("rpathdirs", rpathdir)
end
end
end
|
fix inherit_links rule
|
fix inherit_links rule
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
79e24ca71bef1f3d5b2f9e978bbef1bb8a5a5b03
|
packages/pdf.lua
|
packages/pdf.lua
|
if SILE.outputter ~= SILE.outputters.libtexpdf then
SU.error("pdf package requires libtexpdf backend")
end
local pdf = require("justenoughlibtexpdf")
SILE.registerCommand("pdf:destination", function (options, _)
local name = SU.required(options, "name", "pdf:bookmark")
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
SILE.outputters.libtexpdf._init()
local state = typesetter.frame.state
local y = SILE.documentState.paperSize[2] - state.cursorY
pdf.destination(name, state.cursorX:tonumber(), y:tonumber())
end
})
end)
SILE.registerCommand("pdf:bookmark", function (options, _)
local dest = SU.required(options, "dest", "pdf:bookmark")
local title = SU.required(options, "title", "pdf:bookmark")
local level = options.level or 1
-- Added UTF8 to UTF16-BE conversion
-- For annotations and bookmarks, text strings must be encoded using
-- either PDFDocEncoding or UTF16-BE with a leading byte-order marker.
-- As PDFDocEncoding supports only limited character repertoire for
-- European languages, we use UTF-16BE for internationalization.
local ustr = SU.utf8_to_utf16be_hexencoded(title)
SILE.typesetter:pushHbox({
value = nil, height = 0, width = 0, depth = 0,
outputYourself = function ()
local d = "<</Title<" .. ustr .. ">/A<</S/GoTo/D(" .. dest .. ")>>>>"
SILE.outputters.libtexpdf._init()
pdf.bookmark(d, level)
end
})
end)
if SILE.Commands.tocentry then
SILE.scratch.pdf = { dests = {}, dc = 1 }
local oldtoc = SILE.Commands.tocentry
SILE.Commands.tocentry = function (options, content)
SILE.call("pdf:destination", { name = "dest" .. SILE.scratch.pdf.dc } )
local title = SU.contentToString(content)
SILE.call("pdf:bookmark", { title = title, dest = "dest" .. SILE.scratch.pdf.dc, level = options.level })
oldtoc(options, content)
SILE.scratch.pdf.dc = SILE.scratch.pdf.dc + 1
end
end
SILE.registerCommand("pdf:literal", function (_, content)
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (_, _, _)
SILE.outputters.libtexpdf._init()
pdf.add_content(content[1])
end
})
end)
SILE.registerCommand("pdf:link", function (options, content)
local dest = SU.required(options, "dest", "pdf:link")
local target = options.external and "/Type/Action/S/URI/URI" or "/S/GoTo/D"
local llx, lly
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (_, typesetter, _)
llx = typesetter.frame.state.cursorX
lly = SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY
SILE.outputters.libtexpdf._init()
pdf.begin_annotation()
end
})
local hbox = SILE.call("hbox", {}, content) -- hack
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (_, typesetter, _)
local d = "<</Type/Annot/Subtype/Link/C [ 1 0 0 ]/A<<" .. target .. "(" .. dest .. ")>>>>"
pdf.end_annotation(d, llx, lly, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] -typesetter.frame.state.cursorY + hbox.height)
end
})
end)
SILE.registerCommand("pdf:metadata", function (options, _)
local key = SU.required(options, "key", "pdf:metadata")
local val = SU.required(options, "val", "pdf:metadata")
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (_, _, _)
SILE.outputter._init()
pdf.metadata(key, val)
end
})
end)
return { documentation = [[\begin{document}
The \code{pdf} package enables (basic) support for PDF links and table-of-contents
entries. It provides the four commands \command{\\pdf:destination}, \command{\\pdf:link},
\command{\\pdf:bookmark}, and \command{\\pdf:metadata}.
The \command{\\pdf:destination} parameter creates a link target; it expects a
parameter called \code{name} to uniquely identify the target. To create a link to
that location in the document, use \code{\\pdf:link[dest=\goodbreak{}name]\{link content\}}.
To set arbitrary key-value metadata, use something like \code{\\pdf:metadata[key=Author,
value=J. Smith]}. The PDF metadata field names are case-sensitive. Common keys include
\code{Title}, \code{Author}, \code{Subject}, \code{Keywords}, \code{CreationDate}, and
\code{ModDate}.
If the \code{pdf} package is loaded after the \code{tableofcontents} package (e.g.
in a document with the \code{book} class), then a PDF document outline will be generated.
\end{document}]] }
|
if SILE.outputter ~= SILE.outputters.libtexpdf then
SU.error("pdf package requires libtexpdf backend")
end
local pdf = require("justenoughlibtexpdf")
SILE.registerCommand("pdf:destination", function (options, _)
local name = SU.required(options, "name", "pdf:bookmark")
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
SILE.outputters.libtexpdf._init()
local state = typesetter.frame.state
local y = SILE.documentState.paperSize[2] - state.cursorY
pdf.destination(name, state.cursorX:tonumber(), y:tonumber())
end
})
end)
SILE.registerCommand("pdf:bookmark", function (options, _)
local dest = SU.required(options, "dest", "pdf:bookmark")
local title = SU.required(options, "title", "pdf:bookmark")
local level = options.level or 1
-- Added UTF8 to UTF16-BE conversion
-- For annotations and bookmarks, text strings must be encoded using
-- either PDFDocEncoding or UTF16-BE with a leading byte-order marker.
-- As PDFDocEncoding supports only limited character repertoire for
-- European languages, we use UTF-16BE for internationalization.
local ustr = SU.utf8_to_utf16be_hexencoded(title)
SILE.typesetter:pushHbox({
value = nil,
height = SILE.measurement(0),
width = SILE.measurement(0),
depth = SILE.measurement(0),
outputYourself = function ()
local d = "<</Title<" .. ustr .. ">/A<</S/GoTo/D(" .. dest .. ")>>>>"
SILE.outputters.libtexpdf._init()
pdf.bookmark(d, level)
end
})
end)
if SILE.Commands.tocentry then
SILE.scratch.pdf = { dests = {}, dc = 1 }
local oldtoc = SILE.Commands.tocentry
SILE.Commands.tocentry = function (options, content)
SILE.call("pdf:destination", { name = "dest" .. SILE.scratch.pdf.dc } )
local title = SU.contentToString(content)
SILE.call("pdf:bookmark", { title = title, dest = "dest" .. SILE.scratch.pdf.dc, level = options.level })
oldtoc(options, content)
SILE.scratch.pdf.dc = SILE.scratch.pdf.dc + 1
end
end
SILE.registerCommand("pdf:literal", function (_, content)
SILE.typesetter:pushHbox({
value = nil,
height = SILE.measurement(0),
width = SILE.measurement(0),
depth = SILE.measurement(0),
outputYourself = function (_, _, _)
SILE.outputters.libtexpdf._init()
pdf.add_content(content[1])
end
})
end)
SILE.registerCommand("pdf:link", function (options, content)
local dest = SU.required(options, "dest", "pdf:link")
local target = options.external and "/Type/Action/S/URI/URI" or "/S/GoTo/D"
local llx, lly
SILE.typesetter:pushHbox({
value = nil,
height = SILE.measurement(0),
width = SILE.measurement(0),
depth = SILE.measurement(0),
outputYourself = function (_, typesetter, _)
llx = typesetter.frame.state.cursorX:tonumber()
lly = (SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY):tonumber()
SILE.outputters.libtexpdf._init()
pdf.begin_annotation()
end
})
local hbox = SILE.call("hbox", {}, content) -- hack
SILE.typesetter:pushHbox({
value = nil,
height = SILE.measurement(0),
width = SILE.measurement(0),
depth = SILE.measurement(0),
outputYourself = function (_, typesetter, _)
local d = "<</Type/Annot/Subtype/Link/C [ 1 0 0 ]/A<<" .. target .. "(" .. dest .. ")>>>>"
local x = typesetter.frame.state.cursorX:tonumber()
local y = (SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY + hbox.height):tonumber()
pdf.end_annotation(d, llx, lly, x, y)
end
})
end)
SILE.registerCommand("pdf:metadata", function (options, _)
local key = SU.required(options, "key", "pdf:metadata")
local val = SU.required(options, "val", "pdf:metadata")
SILE.typesetter:pushHbox({
value = nil,
height = SILE.measurement(0),
width = SILE.measurement(0),
depth = SILE.measurement(0),
outputYourself = function (_, _, _)
SILE.outputter._init()
pdf.metadata(key, val)
end
})
end)
return { documentation = [[\begin{document}
The \code{pdf} package enables (basic) support for PDF links and table-of-contents
entries. It provides the four commands \command{\\pdf:destination}, \command{\\pdf:link},
\command{\\pdf:bookmark}, and \command{\\pdf:metadata}.
The \command{\\pdf:destination} parameter creates a link target; it expects a
parameter called \code{name} to uniquely identify the target. To create a link to
that location in the document, use \code{\\pdf:link[dest=\goodbreak{}name]\{link content\}}.
To set arbitrary key-value metadata, use something like \code{\\pdf:metadata[key=Author,
value=J. Smith]}. The PDF metadata field names are case-sensitive. Common keys include
\code{Title}, \code{Author}, \code{Subject}, \code{Keywords}, \code{CreationDate}, and
\code{ModDate}.
If the \code{pdf} package is loaded after the \code{tableofcontents} package (e.g.
in a document with the \code{book} class), then a PDF document outline will be generated.
\end{document}]] }
|
fix(packages): Update PDF package to use correct measurement types
|
fix(packages): Update PDF package to use correct measurement types
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
a2321b06efb7a8755893d5417a924a827c72258a
|
naca-airfoil/structured-trapezoid-naca-airfoil.lua
|
naca-airfoil/structured-trapezoid-naca-airfoil.lua
|
--[[
The MIT License (MIT)
Copyright (c) 2020 Loïc Fejoz
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local implicit_precision = 0.1
function trapezoid_symmetrical_naca_airfoil(cfg)
if cfg.thickness == nil then
cfg.thickness = cfg.t * cfg.chord_length
end
if cfg.t == nil then
cfg.t = cfg.thickness / cfg.chord_length
end
local p = math.floor(cfg.t * 100)
cfg.naca_serie = '00' .. p
if p < 10 then
cfg.naca_serie = '0' .. cfg.naca_serie
end
local airfoil = implicit_solid(
v(0, -cfg.thickness/2, 0),
v(cfg.sweep + cfg.length, cfg.thickness/2, cfg.height),
implicit_precision,
[[
uniform highp float t = 0.12;
uniform highp float chord_length = 40.0;
uniform highp float sweep_coeff = 0.0;
uniform highp float chord_coeff = 0.0;
uniform highp float wall_thickness = 0.35;
uniform highp float dist = 15.0;
highp float solid(vec3 p) {
highp float c = chord_length - chord_coeff*p.z;
highp float x = p.x - sweep_coeff * p.z;
// This avoid some numerical instabilities
if (x < 0 || x > c) {
return 1;
}
highp float xc = x / c;
highp float sdf = t / 0.2 *(0.2969 * sqrt(xc) - 0.1260 * xc - 0.3516 * pow(xc, 2) + 0.2843 * pow(xc, 3) - 0.1015 * pow(xc, 4));
sdf = abs(p.y) - sdf;
highp float profile_sdf = abs(sdf + wall_thickness) - wall_thickness;
// Now compute structures
highp float s1 = mod(p.x + p.z, dist) - wall_thickness;
highp float s2 = mod(-p.x + p.z, dist) - wall_thickness;
highp float s = min(s1, s2);
//vec3 q = mod(p+0.5*dist, dist/2)-0.5*dist;
vec3 q;
q.y = mod(p.y+0.25*dist,dist/2)-0.25*dist;
q.x = mod(p.x+0.5*dist,dist/2)-0.25*dist;
q.z = mod(p.z+0.5*dist,dist/2)-0.25*dist;
highp float void_structures = length(q)- dist/5;
s = max(-void_structures,max(sdf, s)); // void structures
return min(max(sdf, s), profile_sdf);
}
]])
set_uniform_scalar(airfoil, 'wall_thickness', cfg.wall_thickness)
set_uniform_scalar(airfoil, 't', cfg.thickness)
set_uniform_scalar(airfoil, 'chord_length', cfg.root_chord)
set_uniform_scalar(airfoil, 'sweep_coeff', cfg.sweep/cfg.height)
set_uniform_scalar(airfoil, 'chord_coeff', (cfg.root_chord - cfg.tip_chord)/cfg.height)
return airfoil
end
local chord_length = ui_number('chord length (mm)', 50, 10, 200)
local root_chord = ui_number('root chord (mm)', 58, 10, 200)
local sweep = ui_number('sweep (mm)', 81, 0, 200)
local tip_chord = ui_number('tip chord (mm)', 30, 0, 200)
local thickness = ui_scalar('max thickness (mm)', 10, 0, 10)
local fin_height = ui_number('height (mm)', 38, 1, 100)
local wall_thickness = ui_scalar('wall thickness (mm/100)', 35, 0, 40) / 100
local cfg = {
chord_length = chord_length,
fin_count = 1,
cant_angle = 0.017453292519943295,
fillet_radius = 0.0,
cross_section = 'AIRFOIL',
tab_points = {},
root_points = {v(0.0, 0.0, 0.0),v(57.99999999999999, 0.0, 0.0),},
body_radius = 0,
length = 58.000000000000014,
position = v(0.0, 0.0, 0.0),
axial_offset = 0.0,
tip_chord = tip_chord,
sweep = sweep,
height = fin_height,
root_chord = root_chord,
position = v(0.0, 0.0, 0.0),
thickness = thickness,
wall_thickness = wall_thickness,
fin_points = {
v(0.0, 0.0, 0.0),
v(sweep, fin_height, 0.0),
v(sweep+tip_chord, fin_height, 0.0),
v(root_chord, 0.0, 0.0),
},
}
emit(trapezoid_symmetrical_naca_airfoil(cfg))
print("NACA Profile " .. cfg.naca_serie)
function TrapezoidFinSet(cfg)
fins = {}
for i=1,cfg.fin_count do
local a_fin = translate(0, cfg.body_radius, -cfg.thickness/2) * linear_extrude(v(0, 0, cfg.thickness), cfg.fin_points)
table.insert(fins, rotate((i * 360)/cfg.fin_count, 0, 0) * a_fin)
end
return translate(cfg.position) * union(fins)
end
local do_display_ref = ui_number('do display square fin', 0, 0, 1)
if do_display_ref > 0.5 then
emit(rotate(90, 0, 0) * TrapezoidFinSet(cfg), 2)
end
|
--[[
The MIT License (MIT)
Copyright (c) 2020 Loïc Fejoz
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local implicit_precision = 0.1
function trapezoid_symmetrical_naca_airfoil(cfg)
if cfg.thickness == nil then
cfg.thickness = cfg.t * cfg.chord_length
end
if cfg.t == nil then
cfg.t = cfg.thickness / cfg.chord_length
end
local p = math.floor(cfg.t * 100)
cfg.naca_serie = '00' .. p
if p < 10 then
cfg.naca_serie = '0' .. cfg.naca_serie
end
local airfoil = implicit_solid(
v(0, -cfg.thickness/2, 0),
v(cfg.sweep + cfg.length, cfg.thickness/2, cfg.height),
implicit_precision,
[[
uniform highp float t = 0.12;
uniform highp float chord_length = 40.0;
uniform highp float sweep_coeff = 0.0;
uniform highp float chord_coeff = 0.0;
uniform highp float wall_thickness = 0.35;
uniform highp float dist = 15.0;
highp float solid(vec3 p) {
highp float c = chord_length - chord_coeff*p.z;
highp float x = p.x - sweep_coeff * p.z;
// This avoid some numerical instabilities
if (x < 0 || x > c) {
return 1;
}
highp float xc = x / c;
highp float profile_radius = t / 0.2 *(0.2969 * sqrt(xc) - 0.1260 * xc - 0.3516 * pow(xc, 2) + 0.2843 * pow(xc, 3) - 0.1015 * pow(xc, 4));
highp float sdf = abs(p.y) - profile_radius;
highp float profile_sdf = abs(sdf + wall_thickness) - wall_thickness;
// Now compute structures
highp float s1 = mod(p.x + p.z, dist) - wall_thickness;
highp float s2 = mod(-p.x + p.z, dist) - wall_thickness;
highp float s = min(s1, s2);
//vec3 q = mod(p+0.5*dist, dist/2)-0.25*dist;
vec3 q;
q.xz = mod(p.xz+0.5*dist,dist/2)-0.25*dist;
q.y = mod(p.y+0.25*dist,dist)-0.25*dist;
highp float void_structures = length(q)- 0.8*profile_radius;
s = max(-void_structures,max(sdf, s)); // void structures
//return s;
return min(max(sdf, s), profile_sdf);
}
]])
set_uniform_scalar(airfoil, 'wall_thickness', cfg.wall_thickness)
set_uniform_scalar(airfoil, 't', cfg.thickness)
set_uniform_scalar(airfoil, 'chord_length', cfg.root_chord)
set_uniform_scalar(airfoil, 'sweep_coeff', cfg.sweep/cfg.height)
set_uniform_scalar(airfoil, 'chord_coeff', (cfg.root_chord - cfg.tip_chord)/cfg.height)
return airfoil
end
local chord_length = ui_number('chord length (mm)', 50, 10, 200)
local root_chord = ui_number('root chord (mm)', 58, 10, 200)
local sweep = ui_number('sweep (mm)', 81, 0, 200)
local tip_chord = ui_number('tip chord (mm)', 30, 0, 200)
local thickness = ui_scalar('max thickness (mm)', 10, 0, 10)
local fin_height = ui_number('height (mm)', 38, 1, 100)
local wall_thickness = ui_scalar('wall thickness (mm/100)', 35, 0, 40) / 100
local cfg = {
chord_length = chord_length,
fin_count = 1,
cant_angle = 0.017453292519943295,
fillet_radius = 0.0,
cross_section = 'AIRFOIL',
tab_points = {},
root_points = {v(0.0, 0.0, 0.0),v(57.99999999999999, 0.0, 0.0),},
body_radius = 0,
length = 58.000000000000014,
position = v(0.0, 0.0, 0.0),
axial_offset = 0.0,
tip_chord = tip_chord,
sweep = sweep,
height = fin_height,
root_chord = root_chord,
position = v(0.0, 0.0, 0.0),
thickness = thickness,
wall_thickness = wall_thickness,
fin_points = {
v(0.0, 0.0, 0.0),
v(sweep, fin_height, 0.0),
v(sweep+tip_chord, fin_height, 0.0),
v(root_chord, 0.0, 0.0),
},
}
emit(trapezoid_symmetrical_naca_airfoil(cfg))
print("NACA Profile " .. cfg.naca_serie)
function TrapezoidFinSet(cfg)
fins = {}
for i=1,cfg.fin_count do
local a_fin = translate(0, cfg.body_radius, -cfg.thickness/2) * linear_extrude(v(0, 0, cfg.thickness), cfg.fin_points)
table.insert(fins, rotate((i * 360)/cfg.fin_count, 0, 0) * a_fin)
end
return translate(cfg.position) * union(fins)
end
local do_display_ref = ui_number('do display square fin', 0, 0, 1)
if do_display_ref > 0.5 then
emit(rotate(90, 0, 0) * TrapezoidFinSet(cfg), 2)
end
|
fix(naca-airfoil): more adjusted holes
|
fix(naca-airfoil): more adjusted holes
|
Lua
|
mit
|
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
|
0355cefa2456658ccb7008798197ba4e5499ae5f
|
scripts/genie.lua
|
scripts/genie.lua
|
solution "UtilsCollection"
location (path.join("../.project/", _ACTION))
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
objdir ("../.build/".._ACTION)
defines { "_CRT_SECURE_NO_WARNINGS" }
project "ResourceEmbedder"
uuid "fecff87e-9cc0-4134-a2b5-6ef0e73969b4"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../ResourceEmbedder/**.cpp",
"../ResourceEmbedder/**.h",
"../externals/lz4/lib/lz4.c",
"../externals/lz4/lib/lz4.h",
"../externals/lz4/lib/lz4hc.c",
"../externals/lz4/lib/lz4hc.h",
"../externals/zstd/lib/zstd.h",
"../externals/zstd/lib/common/**.c",
"../externals/zstd/lib/common/**.h",
"../externals/zstd/lib/compress/**.c",
"../externals/zstd/lib/compress/**.h"
}
includedirs {
"../externals/lz4/lib",
"../externals/zstd/lib/",
"../externals/zstd/lib/common",
"../externals/zstd/lib/compress"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
platforms{}
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "U8toX"
uuid "83220d0c-8a77-4acb-af45-aedaad4df6b5"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../u8tox/**.cpp",
"../u8tox/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "BooleanExpression"
uuid "16b264fc-24cc-487b-840d-24070a7d461b"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../BooleanExpression/**.cpp",
"../BooleanExpression/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "StringUtils"
uuid "618ee57a-e754-46cf-9f9b-7923e531d970"
kind "StaticLib"
targetdir "../.output/"
files {
"../StringUtils/**.cpp",
"../StringUtils/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
|
function SetupPrefix()
configuration { "x32", "Debug" }
targetsuffix "_d"
configuration { "x32", "Release" }
targetsuffix ""
configuration { "x64", "Debug" }
targetsuffix "_x64_d"
configuration { "x64", "Release" }
targetsuffix "_x64"
configuration()
end
solution "UtilsCollection"
location (path.join("../.project/", _ACTION))
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
objdir ("../.build/".._ACTION)
defines { "_CRT_SECURE_NO_WARNINGS" }
project "ResourceEmbedder"
uuid "fecff87e-9cc0-4134-a2b5-6ef0e73969b4"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../ResourceEmbedder/**.cpp",
"../ResourceEmbedder/**.h",
"../externals/lz4/lib/lz4.c",
"../externals/lz4/lib/lz4.h",
"../externals/lz4/lib/lz4hc.c",
"../externals/lz4/lib/lz4hc.h",
"../externals/zstd/lib/zstd.h",
"../externals/zstd/lib/common/**.c",
"../externals/zstd/lib/common/**.h",
"../externals/zstd/lib/compress/**.c",
"../externals/zstd/lib/compress/**.h"
}
includedirs {
"../externals/lz4/lib",
"../externals/zstd/lib/",
"../externals/zstd/lib/common",
"../externals/zstd/lib/compress"
}
configuration()
configuration "Debug"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
SetupPrefix()
project "U8toX"
uuid "83220d0c-8a77-4acb-af45-aedaad4df6b5"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../u8tox/**.cpp",
"../u8tox/**.h"
}
configuration()
configuration "Debug"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
SetupPrefix()
project "BooleanExpression"
uuid "16b264fc-24cc-487b-840d-24070a7d461b"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../BooleanExpression/**.cpp",
"../BooleanExpression/**.h"
}
configuration()
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
SetupPrefix()
project "StringUtils"
uuid "618ee57a-e754-46cf-9f9b-7923e531d970"
kind "StaticLib"
targetdir "../.output/"
files {
"../StringUtils/**.cpp",
"../StringUtils/**.h"
}
configuration()
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
SetupPrefix()
|
Fix previous commit (prefix for filenames in 64 bits)
|
Fix previous commit (prefix for filenames in 64 bits)
|
Lua
|
mit
|
thennequin/UtilsCollection,thennequin/UtilsCollection
|
8274dfe069762b150e83ef843eca231f4b647f12
|
kong/resolver/access.lua
|
kong/resolver/access.lua
|
local url = require "socket.url"
local cache = require "kong.tools.database_cache"
local constants = require "kong.constants"
local responses = require "kong.tools.responses"
local _M = {}
local function get_backend_url(api)
local result = api.target_url
-- Checking if the target url ends with a final slash
local len = string.len(result)
if string.sub(result, len, len) == "/" then
-- Remove one slash to avoid having a double slash
-- Because ngx.var.request_uri always starts with a slash
result = string.sub(result, 0, len - 1)
end
return result
end
local function get_host_from_url(val)
local parsed_url = url.parse(val)
local port
if parsed_url.port then
port = parsed_url.port
elseif parsed_url.scheme == "https" then
port = 443
end
return parsed_url.host..(port and ":"..port or "")
end
-- Find an API from a request made to nginx. Either from one of the Host or X-Host-Override headers
-- matching the API's `public_dns`, either from the `request_uri` matching the API's `path`.
--
-- To perform this, we need to query _ALL_ APIs in memory. It is the only way to compare the `request_uri`
-- as a regex to the values set in DB. We keep APIs in the database cache for a longer time than usual.
-- @see https://github.com/Mashape/kong/issues/15 for an improvement on this.
--
-- @param `request_uri` The URI for this request.
-- @return `err` Any error encountered during the retrieval.
-- @return `api` The retrieved API, if any.
-- @return `hosts` The list of headers values found in Host and X-Host-Override.
-- @return `request_uri` The URI for this request.
-- @return `by_path` If the API was retrieved by path, will be true, false if by Host.
local function find_api(request_uri)
local retrieved_api
-- retrieve all APIs
local apis_dics, err = cache.get_or_set("ALL_APIS_BY_DIC", function()
local apis, err = dao.apis:find_all()
if err then
return nil, err
end
-- build dictionnaries of public_dns:api and path:apis for efficient lookup.
local dns_dic, path_dic = {}, {}
for _, api in ipairs(apis) do
if api.public_dns then
dns_dic[api.public_dns] = api
end
if api.path then
path_dic[api.path] = api
end
end
return {dns = dns_dic, path = path_dic}
end, 60) -- 60 seconds cache
if err then
return err
end
-- find by Host header
local all_hosts = {}
for _, header_name in ipairs({"Host", constants.HEADERS.HOST_OVERRIDE}) do
local hosts = ngx.req.get_headers()[header_name]
if hosts then
if type(hosts) == "string" then
hosts = {hosts}
end
-- for all values of this header, try to find an API using the apis_by_dns dictionnary
for _, host in ipairs(hosts) do
table.insert(all_hosts, host)
if apis_dics.dns[host] then
retrieved_api = apis_dics.dns[host]
break
end
end
end
end
-- If it was found by Host, return.
if retrieved_api then
return nil, retrieved_api, all_hosts
end
-- Otherwise, we look for it by path. We have to loop over all APIs and compare the requested URI.
for path, api in pairs(apis_dics.path) do
local m, err = ngx.re.match(request_uri, "^"..path)
if err then
ngx.log(ngx.ERR, "[resolver] error matching requested path: "..err)
elseif m then
retrieved_api = api
end
end
-- Return the retrieved_api or nil
return nil, retrieved_api, all_hosts, true
end
-- Retrieve the API from the Host that has been requested
function _M.execute(conf)
local request_uri = ngx.var.request_uri
local err, api, hosts, by_path = find_api(request_uri)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif not api then
return responses.send_HTTP_NOT_FOUND {
message = "API not found with these values",
public_dns = hosts,
path = request_uri
}
end
-- If API was retrieved by path
if by_path and api.strip_path then
-- All paths are '/path', so let's replace it with a single '/'
request_uri = string.gsub(request_uri, api.path, "/")
end
-- Setting the backend URL for the proxy_pass directive
ngx.var.backend_url = get_backend_url(api)..request_uri
ngx.req.set_header("Host", get_host_from_url(ngx.var.backend_url))
ngx.ctx.api = api
end
return _M
|
local url = require "socket.url"
local cache = require "kong.tools.database_cache"
local constants = require "kong.constants"
local responses = require "kong.tools.responses"
local _M = {}
local function get_backend_url(api)
local result = api.target_url
-- Checking if the target url ends with a final slash
local len = string.len(result)
if string.sub(result, len, len) == "/" then
-- Remove one slash to avoid having a double slash
-- Because ngx.var.request_uri always starts with a slash
result = string.sub(result, 0, len - 1)
end
return result
end
local function get_host_from_url(val)
local parsed_url = url.parse(val)
local port
if parsed_url.port then
port = parsed_url.port
elseif parsed_url.scheme == "https" then
port = 443
end
return parsed_url.host..(port and ":"..port or "")
end
-- Find an API from a request made to nginx. Either from one of the Host or X-Host-Override headers
-- matching the API's `public_dns`, either from the `request_uri` matching the API's `path`.
--
-- To perform this, we need to query _ALL_ APIs in memory. It is the only way to compare the `request_uri`
-- as a regex to the values set in DB. We keep APIs in the database cache for a longer time than usual.
-- @see https://github.com/Mashape/kong/issues/15 for an improvement on this.
--
-- @param `request_uri` The URI for this request.
-- @return `err` Any error encountered during the retrieval.
-- @return `api` The retrieved API, if any.
-- @return `hosts` The list of headers values found in Host and X-Host-Override.
-- @return `request_uri` The URI for this request.
-- @return `by_path` If the API was retrieved by path, will be true, false if by Host.
local function find_api(request_uri)
local retrieved_api
-- retrieve all APIs
local apis_dics, err = cache.get_or_set("ALL_APIS_BY_DIC", function()
local apis, err = dao.apis:find_all()
if err then
return nil, err
end
-- build dictionnaries of public_dns:api and path:apis for efficient lookup.
local dns_dic, path_dic = {}, {}
for _, api in ipairs(apis) do
if api.public_dns then
dns_dic[api.public_dns] = api
end
if api.path then
path_dic[api.path] = api
end
end
return {dns = dns_dic, path = path_dic}
end, 60) -- 60 seconds cache
if err then
return err
end
-- find by Host header
local all_hosts = {}
for _, header_name in ipairs({"Host", constants.HEADERS.HOST_OVERRIDE}) do
local hosts = ngx.req.get_headers()[header_name]
if hosts then
if type(hosts) == "string" then
hosts = {hosts}
end
-- for all values of this header, try to find an API using the apis_by_dns dictionnary
for _, host in ipairs(hosts) do
table.insert(all_hosts, host)
if apis_dics.dns[host] then
retrieved_api = apis_dics.dns[host]
break
end
end
end
end
-- If it was found by Host, return.
if retrieved_api then
return nil, retrieved_api, all_hosts
end
-- Otherwise, we look for it by path. We have to loop over all APIs and compare the requested URI.
for path, api in pairs(apis_dics.path) do
local m, err = ngx.re.match(request_uri, "^"..path)
if err then
ngx.log(ngx.ERR, "[resolver] error matching requested path: "..err)
elseif m then
retrieved_api = api
end
end
-- Return the retrieved_api or nil
return nil, retrieved_api, all_hosts, true
end
-- Retrieve the API from the Host that has been requested
function _M.execute(conf)
local request_uri = ngx.var.request_uri
local err, api, hosts, by_path = find_api(request_uri)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif not api then
return responses.send_HTTP_NOT_FOUND {
message = "API not found with these values",
public_dns = hosts,
path = request_uri
}
end
-- If API was retrieved by path
if by_path and api.strip_path then
-- Replace `/path` with `path`, and then prefix with a `/`
-- Or replace `/path/foo` with `/foo`, and then do not prefix with `/`.
request_uri = string.gsub(request_uri, api.path, "")
if string.sub(request_uri, 0, 1) ~= "/" then
request_uri = "/"..request_uri
end
end
-- Setting the backend URL for the proxy_pass directive
ngx.var.backend_url = get_backend_url(api)..request_uri
ngx.req.set_header("Host", get_host_from_url(ngx.var.backend_url))
ngx.ctx.api = api
end
return _M
|
fix(resolver) handling edgecase resulting in wrong URI
|
fix(resolver) handling edgecase resulting in wrong URI
- If querying `/path/foo` with `strip_path=true`, then the resolver
would replace the URI with `//foo`.
Former-commit-id: 3c766fc0ad270ee23fd52e3350b2ae3bd4d195e8
|
Lua
|
apache-2.0
|
salazar/kong,ejoncas/kong,ajayk/kong,Kong/kong,shiprabehera/kong,ind9/kong,jerizm/kong,streamdataio/kong,vzaramel/kong,beauli/kong,kyroskoh/kong,li-wl/kong,streamdataio/kong,rafael/kong,isdom/kong,Vermeille/kong,xvaara/kong,jebenexer/kong,Kong/kong,ind9/kong,rafael/kong,Mashape/kong,akh00/kong,icyxp/kong,isdom/kong,kyroskoh/kong,Kong/kong,vzaramel/kong,smanolache/kong,ejoncas/kong,ccyphers/kong
|
fa9a4480e619c3d0b969225bbdc2a88e3c6072b6
|
resources/prosody-plugins/util.lib.lua
|
resources/prosody-plugins/util.lib.lua
|
local jid = require "util.jid";
local runner, waiter = require "util.async".runner, require "util.async".waiter;
local muc_domain_prefix
= module:get_option_string("muc_mapper_domain_prefix", "conference");
-- defaults to module.host, the module that uses the utility
local muc_domain_base
= module:get_option_string("muc_mapper_domain_base", module.host);
-- The "real" MUC domain that we are proxying to
local muc_domain = module:get_option_string(
"muc_mapper_domain", muc_domain_prefix.."."..muc_domain_base);
local escaped_muc_domain_base = muc_domain_base:gsub("%p", "%%%1");
local escaped_muc_domain_prefix = muc_domain_prefix:gsub("%p", "%%%1");
-- The pattern used to extract the target subdomain
-- (e.g. extract 'foo' from 'foo.muc.example.com')
local target_subdomain_pattern
= "^"..escaped_muc_domain_prefix..".([^%.]+)%."..escaped_muc_domain_base;
--- Utility function to check and convert a room JID from
-- virtual [email protected] to real [foo][email protected]
-- @param room_jid the room jid to match and rewrite if needed
-- @return returns room jid [foo][email protected] when it has subdomain
-- otherwise [email protected](the room_jid value untouched)
local function room_jid_match_rewrite(room_jid)
local node, host, resource = jid.split(room_jid);
local target_subdomain = host and host:match(target_subdomain_pattern);
if not target_subdomain then
module:log("debug", "No need to rewrite out 'to' %s", room_jid);
return room_jid;
end
-- Ok, rewrite room_jid address to new format
local new_node, new_host, new_resource
= "["..target_subdomain.."]"..node, muc_domain, resource;
room_jid = jid.join(new_node, new_host, new_resource);
module:log("debug", "Rewrote to %s", room_jid);
return room_jid
end
--- Finds and returns room by its jid
-- @param room_jid the room jid to search in the muc component
-- @return returns room if found or nil
function get_room_from_jid(room_jid)
local _, host = jid.split(room_jid);
local component = hosts[host];
if component then
local muc = component.modules.muc
if muc and rawget(muc,"rooms") then
-- We're running 0.9.x or 0.10 (old MUC API)
return muc.rooms[room_jid];
elseif muc and rawget(muc,"get_room_from_jid") then
-- We're running >0.10 (new MUC API)
return muc.get_room_from_jid(room_jid);
else
return
end
end
end
function wrap_async_run(event,handler)
local result;
local async_func = runner(function (event)
local wait, done = waiter();
result=handler(event);
done();
return result;
end)
async_func:run(event)
return result;
end
--- Updates presence stanza, by adding identity node
-- @param stanza the presence stanza
-- @param user the user to which presence we are updating identity
-- @param group the group of the user to which presence we are updating identity
-- @param creator_user the user who created the user which presence we
-- are updating (this is the poltergeist case, where a user creates
-- a poltergeist), optional.
-- @param creator_group the group of the user who created the user which
-- presence we are updating (this is the poltergeist case, where a user creates
-- a poltergeist), optional.
function update_presence_identity(
stanza, user, group, creator_user, creator_group)
-- First remove any 'identity' element if it already
-- exists, so it cannot be spoofed by a client
stanza:maptags(
function(tag)
for k, v in pairs(tag) do
if k == "name" and v == "identity" then
return nil
end
end
return tag
end
)
module:log("debug",
"Presence after previous identity stripped: %s", tostring(stanza));
stanza:tag("identity"):tag("user");
for k, v in pairs(user) do
stanza:tag(k):text(v):up();
end
stanza:up();
-- Add the group information if it is present
if group then
stanza:tag("group"):text(group):up();
end
-- Add the creator user information if it is present
if creator_user then
stanza:tag("creator_user");
for k, v in pairs(creator_user) do
stanza:tag(k):text(v):up();
end
stanza:up();
-- Add the creator group information if it is present
if creator_group then
stanza:tag("creator_group"):text(creator_group):up();
end
stanza:up();
end
module:log("debug",
"Presence with identity inserted %s", tostring(stanza))
end
return {
get_room_from_jid = get_room_from_jid;
wrap_async_run = wrap_async_run;
room_jid_match_rewrite = room_jid_match_rewrite;
update_presence_identity = update_presence_identity;
};
|
local jid = require "util.jid";
local runner, waiter = require "util.async".runner, require "util.async".waiter;
local muc_domain_prefix
= module:get_option_string("muc_mapper_domain_prefix", "conference");
-- defaults to module.host, the module that uses the utility
local muc_domain_base
= module:get_option_string("muc_mapper_domain_base", module.host);
-- The "real" MUC domain that we are proxying to
local muc_domain = module:get_option_string(
"muc_mapper_domain", muc_domain_prefix.."."..muc_domain_base);
local escaped_muc_domain_base = muc_domain_base:gsub("%p", "%%%1");
local escaped_muc_domain_prefix = muc_domain_prefix:gsub("%p", "%%%1");
-- The pattern used to extract the target subdomain
-- (e.g. extract 'foo' from 'foo.muc.example.com')
local target_subdomain_pattern
= "^"..escaped_muc_domain_prefix..".([^%.]+)%."..escaped_muc_domain_base;
--- Utility function to check and convert a room JID from
-- virtual [email protected] to real [foo][email protected]
-- @param room_jid the room jid to match and rewrite if needed
-- @return returns room jid [foo][email protected] when it has subdomain
-- otherwise [email protected](the room_jid value untouched)
local function room_jid_match_rewrite(room_jid)
local node, host, resource = jid.split(room_jid);
local target_subdomain = host and host:match(target_subdomain_pattern);
if not target_subdomain then
module:log("debug", "No need to rewrite out 'to' %s", room_jid);
return room_jid;
end
-- Ok, rewrite room_jid address to new format
local new_node, new_host, new_resource
= "["..target_subdomain.."]"..node, muc_domain, resource;
room_jid = jid.join(new_node, new_host, new_resource);
module:log("debug", "Rewrote to %s", room_jid);
return room_jid
end
--- Finds and returns room by its jid
-- @param room_jid the room jid to search in the muc component
-- @return returns room if found or nil
function get_room_from_jid(room_jid)
local _, host = jid.split(room_jid);
local component = hosts[host];
if component then
local muc = component.modules.muc
if muc and rawget(muc,"rooms") then
-- We're running 0.9.x or 0.10 (old MUC API)
return muc.rooms[room_jid];
elseif muc and rawget(muc,"get_room_from_jid") then
-- We're running >0.10 (new MUC API)
return muc.get_room_from_jid(room_jid);
else
return
end
end
end
function wrap_async_run(event,handler)
-- Grab a local response so that we can send the http response when
-- the handler is done.
local response = event.response;
local async_func = runner(function (event)
response.status_code = handler(event);
-- Send the response to the waiting http client.
response:send();
end)
async_func:run(event)
-- return true to keep the client http connection open.
return true;
end
--- Updates presence stanza, by adding identity node
-- @param stanza the presence stanza
-- @param user the user to which presence we are updating identity
-- @param group the group of the user to which presence we are updating identity
-- @param creator_user the user who created the user which presence we
-- are updating (this is the poltergeist case, where a user creates
-- a poltergeist), optional.
-- @param creator_group the group of the user who created the user which
-- presence we are updating (this is the poltergeist case, where a user creates
-- a poltergeist), optional.
function update_presence_identity(
stanza, user, group, creator_user, creator_group)
-- First remove any 'identity' element if it already
-- exists, so it cannot be spoofed by a client
stanza:maptags(
function(tag)
for k, v in pairs(tag) do
if k == "name" and v == "identity" then
return nil
end
end
return tag
end
)
module:log("debug",
"Presence after previous identity stripped: %s", tostring(stanza));
stanza:tag("identity"):tag("user");
for k, v in pairs(user) do
stanza:tag(k):text(v):up();
end
stanza:up();
-- Add the group information if it is present
if group then
stanza:tag("group"):text(group):up();
end
-- Add the creator user information if it is present
if creator_user then
stanza:tag("creator_user");
for k, v in pairs(creator_user) do
stanza:tag(k):text(v):up();
end
stanza:up();
-- Add the creator group information if it is present
if creator_group then
stanza:tag("creator_group"):text(creator_group):up();
end
stanza:up();
end
module:log("debug",
"Presence with identity inserted %s", tostring(stanza))
end
return {
get_room_from_jid = get_room_from_jid;
wrap_async_run = wrap_async_run;
room_jid_match_rewrite = room_jid_match_rewrite;
update_presence_identity = update_presence_identity;
};
|
Fixing an issue with asnyc http request handlers.
|
Fixing an issue with asnyc http request handlers.
The current poltergeist http api immediately returns
and does not wait for async work in the handler to finish. This
mostly occurs when a public asap key needs to be fetched due
to a cache miss. The fix implements the strategy described at
https://prosody.im/doc/developers/http.html
|
Lua
|
apache-2.0
|
gpolitis/jitsi-meet,bgrozev/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
|
5d3c6ca14abbd8d5a54bbb5752d84252ae4aee42
|
nyagos.d/catalog/subcomplete.lua
|
nyagos.d/catalog/subcomplete.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share.maincmds = {}
-- git
local githelp=io.popen("git help -a 2>nul","r")
if githelp then
local gitcmds={}
for line in githelp:lines() do
if string.match(line,"^ %S") then
for word in string.gmatch(line,"%S+") do
gitcmds[ #gitcmds+1 ] = word
end
end
end
githelp:close()
if #gitcmds > 1 then
local maincmds = share.maincmds
maincmds["git"] = gitcmds
maincmds["git.exe"] = gitcmds
share.maincmds = maincmds
end
end
-- Subversion
local svnhelp=io.popen("svn help 2>nul","r")
if svnhelp then
local svncmds={}
for line in svnhelp:lines() do
local m=string.match(line,"^ ([a-z]+)")
if m then
svncmds[ #svncmds+1 ] = m
end
end
svnhelp:close()
if #svncmds > 1 then
local maincmds = share.maincmds
maincmds["svn"] = svncmds
maincmds["svn.exe"] = svncmds
share.maincmds = maincmds
end
end
-- Mercurial
local hghelp=io.popen("hg debugcomplete 2>nul","r")
if hghelp then
local hgcmds={}
for line in hghelp:lines() do
for word in string.gmatch(line,"[a-z]+") do
hgcmds[#hgcmds+1] = word
end
end
hghelp:close()
if #hgcmds > 1 then
local maincmds=share.maincmds
maincmds["hg"] = hgcmds
maincmds["hg.exe"] = hgcmds
share.maincmds = maincmds
end
end
-- Rclone
local rclonehelp=io.popen("rclone --help 2>nul","r")
if rclonehelp then
local rclonecmds={}
local startflag = false
local flagsfound=false
for line in rclonehelp:lines() do
if not flagsfound then
if string.match(line,"Available Commands:") then
startflag = true
end
if string.match(line,"Flags:") then
flagsfound = true
end
if startflag then
local m=string.match(line,"^%s+([a-z]+)")
if m then
rclonecmds[ #rclonecmds+1 ] = m
end
end
end
end
rclonehelp:close()
if #rclonecmds > 1 then
local maincmds=share.maincmds
maincmds["rclone"] = rclonecmds
maincmds["rclone.exe"] = rclonecmds
share.maincmds = maincmds
end
end
if next(share.maincmds) then
nyagos.completion_hook = function(c)
if c.pos <= 1 then
return nil
end
local cmdname = string.match(c.text,"^%S+")
if not cmdname then
return nil
end
--[[
2nd command completion like :git bisect go[od]
user define-able
local subcommands={"good", "bad"}
local maincmds=share.maincmds
maincmds["git bisect"] = subcommands
share.maincmds = maincmds
--]]
local cmd2nd = string.match(c.text,"^%S+%s+%S+")
if share.maincmds[cmd2nd] then
cmdname = cmd2nd
end
local subcmds = {}
local subcmdData = share.maincmds[cmdname]
if not subcmdData then
return nil
end
local subcmdType = type(subcmdData)
if "table" == subcmdType then
subcmds = subcmdData
elseif "function" == subcmdType then
subcmds = subcmdData()
end
for i=1,#subcmds do
table.insert(c.list,subcmds[i])
end
return c.list
end
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share.maincmds = {}
-- git
local githelp=io.popen("git help -a 2>nul","r")
if githelp then
local gitcmds={}
for line in githelp:lines() do
local word = string.match(line,"^ +(%S+)")
if nil ~= word then
gitcmds[ #gitcmds+1 ] = word
end
end
githelp:close()
if #gitcmds > 1 then
local maincmds = share.maincmds
maincmds["git"] = gitcmds
maincmds["git.exe"] = gitcmds
share.maincmds = maincmds
end
end
-- Subversion
local svnhelp=io.popen("svn help 2>nul","r")
if svnhelp then
local svncmds={}
for line in svnhelp:lines() do
local m=string.match(line,"^ +([a-z]+)")
if m then
svncmds[ #svncmds+1 ] = m
end
end
svnhelp:close()
if #svncmds > 1 then
local maincmds = share.maincmds
maincmds["svn"] = svncmds
maincmds["svn.exe"] = svncmds
share.maincmds = maincmds
end
end
-- Mercurial
local hghelp=io.popen("hg debugcomplete 2>nul","r")
if hghelp then
local hgcmds={}
for line in hghelp:lines() do
for word in string.gmatch(line,"[a-z]+") do
hgcmds[#hgcmds+1] = word
end
end
hghelp:close()
if #hgcmds > 1 then
local maincmds=share.maincmds
maincmds["hg"] = hgcmds
maincmds["hg.exe"] = hgcmds
share.maincmds = maincmds
end
end
-- Rclone
local rclonehelp=io.popen("rclone --help 2>nul","r")
if rclonehelp then
local rclonecmds={}
local startflag = false
local flagsfound=false
for line in rclonehelp:lines() do
if not flagsfound then
if string.match(line,"Available Commands:") then
startflag = true
end
if string.match(line,"Flags:") then
flagsfound = true
end
if startflag then
local m=string.match(line,"^%s+([a-z]+)")
if m then
rclonecmds[ #rclonecmds+1 ] = m
end
end
end
end
rclonehelp:close()
if #rclonecmds > 1 then
local maincmds=share.maincmds
maincmds["rclone"] = rclonecmds
maincmds["rclone.exe"] = rclonecmds
share.maincmds = maincmds
end
end
if next(share.maincmds) then
nyagos.completion_hook = function(c)
if c.pos <= 1 then
return nil
end
local cmdname = string.match(c.text,"^%S+")
if not cmdname then
return nil
end
--[[
2nd command completion like :git bisect go[od]
user define-able
local subcommands={"good", "bad"}
local maincmds=share.maincmds
maincmds["git bisect"] = subcommands
share.maincmds = maincmds
--]]
local cmd2nd = string.match(c.text,"^%S+%s+%S+")
if share.maincmds[cmd2nd] then
cmdname = cmd2nd
end
local subcmds = {}
local subcmdData = share.maincmds[cmdname]
if not subcmdData then
return nil
end
local subcmdType = type(subcmdData)
if "table" == subcmdType then
subcmds = subcmdData
elseif "function" == subcmdType then
subcmds = subcmdData()
end
for i=1,#subcmds do
table.insert(c.list,subcmds[i])
end
return c.list
end
end
|
fix git completion
|
fix git completion
|
Lua
|
bsd-3-clause
|
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos
|
b8c0c3cde9db4baff3d8483af08fc5569e58b1cb
|
lib/response.lua
|
lib/response.lua
|
local user_meta = require('utils').user_meta
local tcp_meta = require('tcp').meta
local os_date = require('os').date
local table_concat = require('table').concat
local string_format = require('string').format
local Response = {}
local status_codes_table = {
[100] = 'Continue',
[101] = 'Switching Protocols',
[102] = 'Processing', -- RFC 2518, obsoleted by RFC 4918
[200] = 'OK',
[201] = 'Created',
[202] = 'Accepted',
[203] = 'Non-Authoritative Information',
[204] = 'No Content',
[205] = 'Reset Content',
[206] = 'Partial Content',
[207] = 'Multi-Status', -- RFC 4918
[300] = 'Multiple Choices',
[301] = 'Moved Permanently',
[302] = 'Moved Temporarily',
[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',
[418] = 'I\'m a teapot', -- RFC 2324
[422] = 'Unprocessable Entity', -- RFC 4918
[423] = 'Locked', -- RFC 4918
[424] = 'Failed Dependency', -- RFC 4918
[425] = 'Unordered Collection', -- RFC 4918
[426] = 'Upgrade Required', -- RFC 2817
[500] = 'Internal Server Error',
[501] = 'Not Implemented',
[502] = 'Bad Gateway',
[503] = 'Service Unavailable',
[504] = 'Gateway Time-out',
[505] = 'HTTP Version not supported',
[506] = 'Variant Also Negotiates', -- RFC 2295
[507] = 'Insufficient Storage', -- RFC 4918
[509] = 'Bandwidth Limit Exceeded',
[510] = 'Not Extended' -- RFC 2774
}
Response.prototype = {}
setmetatable(Response.prototype, tcp_meta)
function Response.new(client)
local response = {
code = 200,
headers = {},
headers_names = {},
headers_sent = false,
userdata = client.userdata,
prototype = Response.prototype
}
setmetatable(response, user_meta)
return response
end
Response.prototype.auto_date = true
Response.prototype.auto_server = "Luvit"
Response.prototype.auto_chunked = true
function Response.prototype:set_code(code)
if self.headers_sent then error("Headers already sent") end
self.code = code
end
-- This sets a header, replacing any header with the same name (case insensitive)
function Response.prototype:set_header(name, value)
if self.headers_sent then error("Headers already sent") end
local lower = name:lower()
local old_name = self.header_names[lower]
if old_name then
headers[old_name] = nil
end
self.header_names[lower] = name
self.headers[name] = value
return name
end
-- Adds a header line. This does not replace any header by the same name and
-- allows duplicate headers. Returns the index it was inserted at
function Response.prototype:add_header(name, value)
if self.headers_sent then error("Headers already sent") end
self.headers[#self.headers + 1] = name .. ": " .. value
return #self.headers
end
-- Removes a set header. Cannot remove headers added with :add_header
function Response.prototype:unset_header(name)
if self.headers_sent then error("Headers already sent") end
local lower = name:lower()
local name = self.header_names[lower]
if not name then return end
self.headers[name] = nil
self.header_names[lower] = nil
end
function Response.prototype:flush_head(callback)
if self.headers_sent then error("Headers already sent") end
local reason = status_codes_table[self.code]
if not reason then error("Invalid response code " .. tostring(self.code)) end
local head = {"HTTP/1.1 " .. self.code .. " " .. reason .. "\r\n"}
local length = 1
local has_server, has_content_length, has_date
for field, value in pairs(self.headers) do
if type(field) == "number" then
field, value = value:match("^ *([^ :]+): *([^ ]+) *$")
end
local lower = field:lower()
if lower == "server" then has_server = true
elseif lower == "content-length" then has_content_length = true
elseif lower == "date" then has_date = true
elseif lower == "transfer-encoding" and value:lower() == "chunked" then self.chunked = true
end
length = length + 1
head[length] = field .. ": " .. value .. "\r\n"
end
-- Implement auto headers so people's http server are more spec compliant
if not has_server and self.auto_server then
length = length + 1
head[length] = "Server: " .. self.auto_server .. "\r\n"
end
if not has_content_length and self.auto_chunked then
length = length + 1
self.chunked = true
head[length] = "Transfer-Encoding: chunked\r\n"
end
if not has_date and self.auto_date then
-- This should be RFC 1123 date format
-- IE: Tue, 15 Nov 1994 08:12:31 GMT
length = length + 1
head[length] = os_date("!Date: %a, %d %b %Y %H:%M:%S GMT\r\n")
end
head = table_concat(head, "") .. "\r\n"
self.userdata:write(head, callback)
self.headers_sent = true
end
function Response.prototype:write_head(code, headers, callback)
if self.headers_sent then error("Headers already sent") end
self.code = code
for field, value in pairs(headers) do
self.headers[field] = value
end
self:flush_head(callback)
end
function Response.prototype:write_continue(callback)
self.userdata:write('HTTP/1.1 100 Continue\r\n\r\n', callback)
end
function Response.prototype:write(chunk, callback)
if not self.headers_sent then self:flush_head() end
local userdata = self.userdata
if self.chunked then
userdata:write(string_format("%x\r\n", #chunk))
userdata:write(chunk)
return userdata:write("\r\n", callback)
end
return userdata:write(chunk, callback)
end
function Response.prototype:finish(chunk, callback)
if not self.headers_sent then self:flush_head() end
if type(chunk) == "function" and callback == nil then
callback = chunk
chunk = nil
end
if chunk then
self:write(chunk)
end
if self.chunked then
self.userdata:write('0\r\n\r\n')
end
self:close()
if callback then
self:on("closed", callback)
end
end
return Response
|
local user_meta = require('utils').user_meta
local tcp_meta = require('tcp').meta
local os_date = require('os').date
local table_concat = require('table').concat
local string_format = require('string').format
local Response = {}
local status_codes_table = {
[100] = 'Continue',
[101] = 'Switching Protocols',
[102] = 'Processing', -- RFC 2518, obsoleted by RFC 4918
[200] = 'OK',
[201] = 'Created',
[202] = 'Accepted',
[203] = 'Non-Authoritative Information',
[204] = 'No Content',
[205] = 'Reset Content',
[206] = 'Partial Content',
[207] = 'Multi-Status', -- RFC 4918
[300] = 'Multiple Choices',
[301] = 'Moved Permanently',
[302] = 'Moved Temporarily',
[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',
[418] = 'I\'m a teapot', -- RFC 2324
[422] = 'Unprocessable Entity', -- RFC 4918
[423] = 'Locked', -- RFC 4918
[424] = 'Failed Dependency', -- RFC 4918
[425] = 'Unordered Collection', -- RFC 4918
[426] = 'Upgrade Required', -- RFC 2817
[500] = 'Internal Server Error',
[501] = 'Not Implemented',
[502] = 'Bad Gateway',
[503] = 'Service Unavailable',
[504] = 'Gateway Time-out',
[505] = 'HTTP Version not supported',
[506] = 'Variant Also Negotiates', -- RFC 2295
[507] = 'Insufficient Storage', -- RFC 4918
[509] = 'Bandwidth Limit Exceeded',
[510] = 'Not Extended' -- RFC 2774
}
Response.prototype = {}
setmetatable(Response.prototype, tcp_meta)
function Response.new(client)
local response = {
code = 200,
headers = {},
header_names = {},
headers_sent = false,
userdata = client.userdata,
prototype = Response.prototype
}
setmetatable(response, user_meta)
return response
end
Response.prototype.auto_date = true
Response.prototype.auto_server = "Luvit"
Response.prototype.auto_chunked = true
Response.prototype.auto_content_type = "text/html"
function Response.prototype:set_code(code)
if self.headers_sent then error("Headers already sent") end
self.code = code
end
-- This sets a header, replacing any header with the same name (case insensitive)
function Response.prototype:set_header(name, value)
if self.headers_sent then error("Headers already sent") end
local lower = name:lower()
local old_name = self.header_names[lower]
if old_name then
headers[old_name] = nil
end
self.header_names[lower] = name
self.headers[name] = value
return name
end
-- Adds a header line. This does not replace any header by the same name and
-- allows duplicate headers. Returns the index it was inserted at
function Response.prototype:add_header(name, value)
if self.headers_sent then error("Headers already sent") end
self.headers[#self.headers + 1] = name .. ": " .. value
return #self.headers
end
-- Removes a set header. Cannot remove headers added with :add_header
function Response.prototype:unset_header(name)
if self.headers_sent then error("Headers already sent") end
local lower = name:lower()
local name = self.header_names[lower]
if not name then return end
self.headers[name] = nil
self.header_names[lower] = nil
end
function Response.prototype:flush_head(callback)
if self.headers_sent then error("Headers already sent") end
local reason = status_codes_table[self.code]
if not reason then error("Invalid response code " .. tostring(self.code)) end
local head = {"HTTP/1.1 " .. self.code .. " " .. reason .. "\r\n"}
local length = 1
local has_server, has_content_length, has_date, has_content_type
for field, value in pairs(self.headers) do
if type(field) == "number" then
field, value = value:match("^ *([^ :]+): *([^ ]+) *$")
end
local lower = field:lower()
if lower == "server" then has_server = true
elseif lower == "content-length" then has_content_length = true
elseif lower == "content-type" then has_content_type = true
elseif lower == "date" then has_date = true
elseif lower == "transfer-encoding" and value:lower() == "chunked" then self.chunked = true
end
length = length + 1
head[length] = field .. ": " .. value .. "\r\n"
end
-- Implement auto headers so people's http server are more spec compliant
if not has_server and self.auto_server then
length = length + 1
head[length] = "Server: " .. self.auto_server .. "\r\n"
end
if not has_content_type and self.auto_content_type then
length = length + 1
head[length] = "Content-Type: " .. self.auto_content_type .. "\r\n"
end
if not has_content_length and self.auto_chunked then
length = length + 1
self.chunked = true
head[length] = "Transfer-Encoding: chunked\r\n"
end
if not has_date and self.auto_date then
-- This should be RFC 1123 date format
-- IE: Tue, 15 Nov 1994 08:12:31 GMT
length = length + 1
head[length] = os_date("!Date: %a, %d %b %Y %H:%M:%S GMT\r\n")
end
head = table_concat(head, "") .. "\r\n"
self.userdata:write(head, callback)
self.headers_sent = true
end
function Response.prototype:write_head(code, headers, callback)
if self.headers_sent then error("Headers already sent") end
self.code = code
for field, value in pairs(headers) do
if type(field) == "number" then
field = #self.headers + 1
end
self.headers[field] = value
end
self:flush_head(callback)
end
function Response.prototype:write_continue(callback)
self.userdata:write('HTTP/1.1 100 Continue\r\n\r\n', callback)
end
function Response.prototype:write(chunk, callback)
if not self.headers_sent then self:flush_head() end
local userdata = self.userdata
if self.chunked then
userdata:write(string_format("%x\r\n", #chunk))
userdata:write(chunk)
return userdata:write("\r\n", callback)
end
return userdata:write(chunk, callback)
end
function Response.prototype:finish(chunk, callback)
if not self.headers_sent then self:flush_head() end
if type(chunk) == "function" and callback == nil then
callback = chunk
chunk = nil
end
if chunk then
self:write(chunk)
end
if self.chunked then
self.userdata:write('0\r\n\r\n')
end
self:close()
if callback then
self:on("closed", callback)
end
end
return Response
|
Fix a couple response bugs and add auto content-type
|
Fix a couple response bugs and add auto content-type
Change-Id: I0b283f10610387c53f31b4188d5ac02f54fe37a9
|
Lua
|
mit
|
brimworks/luvit,boundary/luvit,zhaozg/luvit,sousoux/luvit,connectFree/lev,sousoux/luvit,DBarney/luvit,AndrewTsao/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,AndrewTsao/luvit,connectFree/lev,boundary/luvit,kaustavha/luvit,DBarney/luvit,boundary/luvit,kaustavha/luvit,sousoux/luvit,DBarney/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,bsn069/luvit,DBarney/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,sousoux/luvit,AndrewTsao/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,luvit/luvit,kaustavha/luvit,luvit/luvit,bsn069/luvit
|
34e875b3d35fa1d4dde0a3ec662868213b710c55
|
applications/luci-app-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
applications/luci-app-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2010-2011 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
members of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2010-2011 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
members of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
function name.validate(self, value)
-- fw3 defines 14 as the maximum length of zone name
if #value > 14 then
return nil, translate("Zone name is too long")
else
return value
end
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
firewall: validate max length of zone name
|
firewall: validate max length of zone name
fw3 sets the maximum length of the zone name to 14 and
ignores zone definitions with too long names.
http://nbd.name/gitweb.cgi?p=firewall3.git;a=blob;f=zones.h;hb=HEAD#l25
http://nbd.name/gitweb.cgi?p=firewall3.git;a=blob;f=zones.c;hb=HEAD#l195
Add a simple validation to ensure that the new zone name is short enough.
This should fix issue #345
Signed-off-by: Hannu Nyman <[email protected]>
|
Lua
|
apache-2.0
|
tobiaswaldvogel/luci,dwmw2/luci,artynet/luci,artynet/luci,marcel-sch/luci,daofeng2015/luci,wongsyrone/luci-1,obsy/luci,schidler/ionic-luci,aa65535/luci,kuoruan/luci,schidler/ionic-luci,MinFu/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,LuttyYang/luci,wongsyrone/luci-1,cappiewu/luci,openwrt/luci,cappiewu/luci,mumuqz/luci,openwrt/luci,LuttyYang/luci,daofeng2015/luci,urueedi/luci,jorgifumi/luci,thess/OpenWrt-luci,bittorf/luci,kuoruan/lede-luci,marcel-sch/luci,kuoruan/luci,chris5560/openwrt-luci,thess/OpenWrt-luci,teslamint/luci,thesabbir/luci,rogerpueyo/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,hnyman/luci,chris5560/openwrt-luci,LuttyYang/luci,Noltari/luci,ollie27/openwrt_luci,teslamint/luci,taiha/luci,oneru/luci,cshore/luci,openwrt-es/openwrt-luci,Wedmer/luci,jchuang1977/luci-1,artynet/luci,Noltari/luci,Noltari/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,forward619/luci,cshore-firmware/openwrt-luci,dwmw2/luci,bittorf/luci,oneru/luci,forward619/luci,taiha/luci,aa65535/luci,artynet/luci,bright-things/ionic-luci,thesabbir/luci,jlopenwrtluci/luci,Hostle/luci,nmav/luci,remakeelectric/luci,oneru/luci,kuoruan/lede-luci,bittorf/luci,jchuang1977/luci-1,ollie27/openwrt_luci,bittorf/luci,bright-things/ionic-luci,urueedi/luci,thess/OpenWrt-luci,oyido/luci,mumuqz/luci,NeoRaider/luci,kuoruan/lede-luci,jlopenwrtluci/luci,rogerpueyo/luci,kuoruan/luci,obsy/luci,daofeng2015/luci,NeoRaider/luci,rogerpueyo/luci,openwrt/luci,aa65535/luci,dwmw2/luci,marcel-sch/luci,Hostle/luci,remakeelectric/luci,maxrio/luci981213,nmav/luci,artynet/luci,NeoRaider/luci,dwmw2/luci,tobiaswaldvogel/luci,bittorf/luci,openwrt/luci,urueedi/luci,marcel-sch/luci,981213/luci-1,oyido/luci,cshore-firmware/openwrt-luci,mumuqz/luci,openwrt-es/openwrt-luci,marcel-sch/luci,Hostle/luci,urueedi/luci,marcel-sch/luci,jchuang1977/luci-1,maxrio/luci981213,jorgifumi/luci,cshore/luci,thesabbir/luci,cshore-firmware/openwrt-luci,taiha/luci,wongsyrone/luci-1,chris5560/openwrt-luci,cshore/luci,NeoRaider/luci,wongsyrone/luci-1,bright-things/ionic-luci,981213/luci-1,cshore-firmware/openwrt-luci,Noltari/luci,aa65535/luci,teslamint/luci,oneru/luci,nmav/luci,nmav/luci,lbthomsen/openwrt-luci,daofeng2015/luci,MinFu/luci,openwrt-es/openwrt-luci,daofeng2015/luci,oyido/luci,Noltari/luci,cshore-firmware/openwrt-luci,urueedi/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,oyido/luci,thesabbir/luci,oyido/luci,Wedmer/luci,jchuang1977/luci-1,obsy/luci,thess/OpenWrt-luci,taiha/luci,taiha/luci,LuttyYang/luci,981213/luci-1,nmav/luci,Wedmer/luci,nmav/luci,NeoRaider/luci,teslamint/luci,oneru/luci,LuttyYang/luci,remakeelectric/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,Wedmer/luci,teslamint/luci,ollie27/openwrt_luci,LuttyYang/luci,cshore-firmware/openwrt-luci,forward619/luci,forward619/luci,jlopenwrtluci/luci,981213/luci-1,oneru/luci,remakeelectric/luci,bright-things/ionic-luci,LuttyYang/luci,hnyman/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,rogerpueyo/luci,remakeelectric/luci,remakeelectric/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,thesabbir/luci,wongsyrone/luci-1,urueedi/luci,remakeelectric/luci,MinFu/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,aa65535/luci,Noltari/luci,mumuqz/luci,Wedmer/luci,981213/luci-1,aa65535/luci,oyido/luci,hnyman/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,openwrt/luci,jorgifumi/luci,Hostle/luci,maxrio/luci981213,shangjiyu/luci-with-extra,cappiewu/luci,aa65535/luci,kuoruan/luci,obsy/luci,remakeelectric/luci,981213/luci-1,jlopenwrtluci/luci,Hostle/luci,Hostle/luci,chris5560/openwrt-luci,oyido/luci,openwrt/luci,cappiewu/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,nmav/luci,MinFu/luci,chris5560/openwrt-luci,urueedi/luci,maxrio/luci981213,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,thesabbir/luci,Noltari/luci,kuoruan/lede-luci,bittorf/luci,thesabbir/luci,dwmw2/luci,schidler/ionic-luci,MinFu/luci,rogerpueyo/luci,mumuqz/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,jchuang1977/luci-1,NeoRaider/luci,lbthomsen/openwrt-luci,oneru/luci,jorgifumi/luci,hnyman/luci,mumuqz/luci,rogerpueyo/luci,dwmw2/luci,jlopenwrtluci/luci,thess/OpenWrt-luci,maxrio/luci981213,cshore/luci,Wedmer/luci,schidler/ionic-luci,MinFu/luci,kuoruan/luci,chris5560/openwrt-luci,thesabbir/luci,lbthomsen/openwrt-luci,Hostle/luci,wongsyrone/luci-1,teslamint/luci,taiha/luci,openwrt-es/openwrt-luci,artynet/luci,ollie27/openwrt_luci,jorgifumi/luci,cappiewu/luci,taiha/luci,lbthomsen/openwrt-luci,cshore/luci,Noltari/luci,wongsyrone/luci-1,MinFu/luci,cappiewu/luci,wongsyrone/luci-1,maxrio/luci981213,daofeng2015/luci,NeoRaider/luci,taiha/luci,schidler/ionic-luci,ollie27/openwrt_luci,bright-things/ionic-luci,dwmw2/luci,obsy/luci,LuttyYang/luci,bright-things/ionic-luci,marcel-sch/luci,bittorf/luci,jchuang1977/luci-1,nmav/luci,nmav/luci,schidler/ionic-luci,rogerpueyo/luci,jorgifumi/luci,hnyman/luci,Wedmer/luci,bittorf/luci,ollie27/openwrt_luci,aa65535/luci,cshore/luci,daofeng2015/luci,tobiaswaldvogel/luci,NeoRaider/luci,shangjiyu/luci-with-extra,oyido/luci,forward619/luci,mumuqz/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,MinFu/luci,rogerpueyo/luci,hnyman/luci,Noltari/luci,kuoruan/luci,maxrio/luci981213,teslamint/luci,openwrt/luci,kuoruan/lede-luci,thess/OpenWrt-luci,hnyman/luci,daofeng2015/luci,jorgifumi/luci,urueedi/luci,obsy/luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,tobiaswaldvogel/luci,jorgifumi/luci,artynet/luci,obsy/luci,openwrt/luci,artynet/luci,obsy/luci,forward619/luci,cshore/luci,hnyman/luci,forward619/luci,schidler/ionic-luci,981213/luci-1,cshore/luci,artynet/luci,jlopenwrtluci/luci,forward619/luci,kuoruan/luci,cappiewu/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,teslamint/luci,mumuqz/luci,marcel-sch/luci,oneru/luci,Wedmer/luci,kuoruan/luci,kuoruan/lede-luci,cappiewu/luci,tobiaswaldvogel/luci,Hostle/luci,openwrt-es/openwrt-luci,dwmw2/luci,thess/OpenWrt-luci
|
746934c72018b53216f6b394c6da47b8c9532f15
|
modulefiles/Core/SitePackage.lua
|
modulefiles/Core/SitePackage.lua
|
require("strict")
local hook = require("Hook")
local http = require("socket.http")
http.TIMEOUT = 30
function url_quote(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
function get_project(str)
local project = nil
if (str) then
for match in string.gmatch(str, "ProjectName%s+=%s+\"(.-)\"") do
project = match
end
end
return project
end
function get_username(str)
local username = nil
if (str) then
for match in string.gmatch(str, "Owner%s+=%s+\"(.-)@.-\"") do
username = match
end
end
return username
end
function get_site(str)
local site = nil
if (str) then
for match in string.gmatch(str, "JOBGLIDEIN_ResourceName%s+=%s+\"(.-)\"") do
site = match
end
end
return site
end
-- By using the hook.register function, this function "load_hook" is called
-- ever time a module is loaded with the file name and the module name.
function load_hook(t)
-- the arg t is a table:
-- t.modFullName: the module full name: (i.e: gcc/4.7.2)
-- t.fn: The file name: (i.e /apps/modulefiles/Core/gcc/4.7.2.lua)
-- Your site can use this any way that suits. Here are some possibilities:
-- a) Write this information into a file in your users directory (say ~/.lmod.d/.save).
-- Then once a month collect this data.
-- b) have this function call syslogd to register that this module was loaded by this
-- user
-- c) Write the same information directly to some database.
-- This is the directory in which this script resides, and it pulls the rest
-- of the required scripts and config from this same directory. (It would
-- be better to compute this, but my lua skills are lacking.)
local dirname = os.getenv("LMOD_PACKAGE_PATH")
local username = os.getenv("OSGVO_SUBMITTER")
if username == nil then
username = 'UNAVAILABLE'
end
local project = os.getenv("OSGVO_PROJECT_NAME")
if project == nil then
project = 'UNAVAILABLE'
end
local site = os.getenv("OSG_SITE_NAME")
if site == nil then
site = 'UNAVAILABLE'
end
local fhandle = io.popen('/bin/hostname -f', 'r')
local host = fhandle:read()
fhandle:close()
if host == nil then
host = 'UNAVAILABLE'
end
local condor_classad_file = os.getenv('_CONDOR_JOB_AD')
local f = io.open(condor_classad_file, 'r')
local classads = f:read("*all")
if classads ~= nil then
username = get_username(classads)
if site == 'UNAVAILABLE' then
site = get_site(classads)
end
if project == 'UNAVAILABLE' then
project = get_project(classads)
end
end
if dirname ~= '' and username ~= '' and t.modFullName ~= '' then
-- We don't want failure to log to block jobs or give errors. Make an
-- effort to log things, but ignore anything that goes wrong. Also do
-- not wait on the subprocess.
local uri = 'http://modules.ci-connect.net/register_module.wsgi?'
uri = uri .. 'user=' .. url_quote(username)
uri = uri .. '&project=' .. url_quote(project)
uri = uri .. '&module=' .. url_quote(t.modFullName)
uri = uri .. '&site=' .. url_quote(site)
uri = uri .. '&host=' .. url_quote(host)
http.request(uri)
end
end
hook.register("load",load_hook)
|
require("strict")
local hook = require("Hook")
local http = require("socket.http")
http.TIMEOUT = 30
function url_quote(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
function get_project(str)
local project = nil
if (str) then
for match in string.gmatch(str, "ProjectName%s+=%s+\"(.-)\"") do
project = match
end
end
return project
end
function get_username(str)
local username = nil
if (str) then
for match in string.gmatch(str, "Owner%s+=%s+\"(.-)@.-\"") do
username = match
end
end
return username
end
function get_site(str)
local site = nil
if (str) then
for match in string.gmatch(str, "JOBGLIDEIN_ResourceName%s+=%s+\"(.-)\"") do
site = match
end
end
return site
end
-- By using the hook.register function, this function "load_hook" is called
-- ever time a module is loaded with the file name and the module name.
function load_hook(t)
-- the arg t is a table:
-- t.modFullName: the module full name: (i.e: gcc/4.7.2)
-- t.fn: The file name: (i.e /apps/modulefiles/Core/gcc/4.7.2.lua)
-- Your site can use this any way that suits. Here are some possibilities:
-- a) Write this information into a file in your users directory (say ~/.lmod.d/.save).
-- Then once a month collect this data.
-- b) have this function call syslogd to register that this module was loaded by this
-- user
-- c) Write the same information directly to some database.
-- This is the directory in which this script resides, and it pulls the rest
-- of the required scripts and config from this same directory. (It would
-- be better to compute this, but my lua skills are lacking.)
local dirname = os.getenv("LMOD_PACKAGE_PATH")
local username = os.getenv("OSGVO_SUBMITTER")
if username == nil then
username = 'UNAVAILABLE'
end
local project = os.getenv("OSGVO_PROJECT_NAME")
if project == nil then
project = 'UNAVAILABLE'
end
local site = os.getenv("OSG_SITE_NAME")
if site == nil then
site = 'UNAVAILABLE'
end
local fhandle = io.popen('/bin/hostname -f', 'r')
local host = fhandle:read()
fhandle:close()
if host == nil then
host = 'UNAVAILABLE'
end
local condor_classad_file = os.getenv('_CONDOR_JOB_AD')
if condor_classad_file ~= nil then
local f = io.open(condor_classad_file, 'r')
local classads = f:read("*all")
if classads ~= nil then
username = get_username(classads)
if site == 'UNAVAILABLE' then
site = get_site(classads)
end
if project == 'UNAVAILABLE' then
project = get_project(classads)
end
end
end
if dirname ~= '' and username ~= '' and t.modFullName ~= '' then
-- We don't want failure to log to block jobs or give errors. Make an
-- effort to log things, but ignore anything that goes wrong. Also do
-- not wait on the subprocess.
local uri = 'http://modules.ci-connect.net/register_module.wsgi?'
uri = uri .. 'user=' .. url_quote(username)
uri = uri .. '&project=' .. url_quote(project)
uri = uri .. '&module=' .. url_quote(t.modFullName)
uri = uri .. '&site=' .. url_quote(site)
uri = uri .. '&host=' .. url_quote(host)
http.request(uri)
end
end
hook.register("load",load_hook)
|
Fix loading classads when not in a condor job environment
|
Fix loading classads when not in a condor job environment
|
Lua
|
apache-2.0
|
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
|
48f4bd22f68b11f5c77c6a4f8510893d8859a4d4
|
src/python.lua
|
src/python.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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.
--
-- @endcond
--]]
Python = newclass "Python"
function Python:init(loader)
self.loader = loader
end
function Python:yaml2json(yaml)
os.executef("dir %s", zpm.env.getSrcDirectory())
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml))
end
function Python:prettifyJSON(json)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json))
end
function Python:update()
self:conda("config --set always_yes yes --set changeps1 no")
self:conda("update --all --yes")
end
function Python:__call(command)
return os.outputoff("%s %s", self:_getPythonExe(), command)
end
function Python:conda(command)
self:_execute("%s %s", zpm.util.getExecutable("conda"), command)
end
function Python:pip(command)
self:_execute("%s %s", zpm.util.getExecutable("pip"), command)
end
function Python:_getBinDirectory()
return path.join(self:_getDirectory(), iif(os.is("windows"), "Scripts", "bin"))
end
function Python:_getDirectory()
return path.join(zpm.env.getDataDirectory(), "conda")
end
function Python:_execute(command)
os.executef("%s/activate && %s", self:_getDirectory(), command)
end
function Python:_getPythonExe()
return zpm.util.getExecutable(iif(os.is("windows"), "python", "python3"))
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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.
--
-- @endcond
--]]
Python = newclass "Python"
function Python:init(loader)
self.loader = loader
end
function Python:yaml2json(yaml)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml))
end
function Python:prettifyJSON(json)
return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json))
end
function Python:update()
self:conda("config --set always_yes yes --set changeps1 no")
self:conda("update --all --yes")
end
function Python:__call(command)
return self:_outputof("%s %s", self:_getPythonExe(), command)
end
function Python:conda(command)
self:_executef("%s %s", zpm.util.getExecutable("conda"), command)
end
function Python:pip(command)
self:_executef("%s %s", zpm.util.getExecutable("pip"), command)
end
function Python:_getBinDirectory()
return path.join(self:_getDirectory(), iif(os.is("windows"), "Scripts", "bin"))
end
function Python:_getDirectory()
return path.join(zpm.env.getDataDirectory(), "conda")
end
function Python:_execute(...)
os.executef("%s/%s", self:_getBinDirectory(), string.format(...))
end
function Python:_outputof(...)
return os.outputoff("%s/%s", self:_getDirectory(), string.format(...))
end
function Python:_getPythonExe()
return zpm.util.getExecutable(iif(os.is("windows"), "python", "python3"))
end
|
Fix directories
|
Fix directories
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
bd8370a70eb3ed7e299416b160430df3de30f043
|
test/luatest.lua
|
test/luatest.lua
|
-- See Copyright Notice in the file LICENSE
module (..., package.seeall)
-- arrays: deep comparison
function eq (t1, t2, lut)
if t1 == t2 then return true end
if type(t1) ~= "table" or type(t2) ~= "table" or #t1 ~= #t2 then
return false
end
lut = lut or {} -- look-up table: are these 2 arrays already compared?
lut[t1] = lut[t1] or {}
if lut[t1][t2] then return true end
lut[t2] = lut[t2] or {}
lut[t1][t2], lut[t2][t1] = true, true
for k,v in ipairs (t1) do
if not eq (t2[k], v, lut) then return false end -- recursion
end
return true
end
NT = {} -- a unique "nil table", to be used instead of nils in datasets
-- pack vararg in table, replacing nils with "NT" table
local function packNT (...)
local t = {}
for i=1, select ("#", ...) do
local v = select (i, ...)
t[i] = (v == nil) and NT or v
end
return t
end
-- unpack table into vararg, replacing "NT" items with nils
local function unpackNT (t)
local len = #t
local function unpack_from (i)
local v = t[i]
if v == NT then v = nil end
if i == len then return v end
return v, unpack_from (i+1)
end
if len > 0 then return unpack_from (1) end
end
-- print results (deep into arrays)
function print_results (val, indent, lut)
indent = indent or ""
lut = lut or {} -- look-up table
local str = tostring (val)
if type (val) == "table" then
if val == NT then
print (indent .. "nil")
elseif lut[val] then
print (indent .. str)
else
lut[val] = true
print (indent .. str)
for i,v in ipairs (val) do
print_results (v, " " .. indent, lut) -- recursion
end
end
else
print (indent .. str)
end
end
-- returns:
-- 1) true, if success; false, if failure
-- 2) test results table or error_message
function test_function (test, func)
local res
local t = packNT (pcall (func, unpackNT (test[1])))
if t[1] then
table.remove (t, 1)
res = t
else
res = t[2] --> error_message
end
local how = (type (res) == type (test[2])) and
(type (res) == "string" or eq (res, test[2])) -- allow error messages to differ
return how, res
end
-- returns:
-- 1) true, if success; false, if failure
-- 2) test results table or error_message
-- 3) test results table or error_message
function test_method (test, constructor, name)
local res1, res2
local ok, r = pcall (constructor, unpackNT (test[1]))
if ok then
local t = packNT (pcall (r[name], r, unpackNT (test[2])))
if t[1] then
table.remove (t, 1)
res1, res2 = t
else
res1, res2 = 2, t[2] --> 2, error_message
end
else
res1, res2 = 1, r --> 1, error_message
end
return eq (res1, test[3]), res1, res2
end
-- returns: a list of failed tests
function test_set (set, lib)
local list = {}
if type (set.Func) == "function" then
local func = set.Func
for i,test in ipairs (set) do
local ok, res = test_function (test, func)
if not ok then
table.insert (list, {i=i, res})
end
end
elseif type (set.Method) == "string" then
for i,test in ipairs (set) do
local ok, res1, res2 = test_method (test, lib.new, set.Method)
if not ok then
table.insert (list, {i=i, res1, res2})
end
end
else
error ("neither set.Func nor set.Method is valid")
end
return list
end
|
-- See Copyright Notice in the file LICENSE
local P = {}
-- arrays: deep comparison
function P.eq (t1, t2, lut)
if t1 == t2 then return true end
if type(t1) ~= "table" or type(t2) ~= "table" or #t1 ~= #t2 then
return false
end
lut = lut or {} -- look-up table: are these 2 arrays already compared?
lut[t1] = lut[t1] or {}
if lut[t1][t2] then return true end
lut[t2] = lut[t2] or {}
lut[t1][t2], lut[t2][t1] = true, true
for k,v in ipairs (t1) do
if not P.eq (t2[k], v, lut) then return false end -- recursion
end
return true
end
-- a "nil GUID", to be used instead of nils in datasets
P.NT = "b5f74fe5-46f4-483a-8321-e58ba2fa0e17"
-- pack vararg in table, replacing nils with "NT" items
local function packNT (...)
local t = {}
for i=1, select ("#", ...) do
local v = select (i, ...)
t[i] = (v == nil) and P.NT or v
end
return t
end
-- unpack table into vararg, replacing "NT" items with nils
local function unpackNT (t)
local len = #t
local function unpack_from (i)
local v = t[i]
if v == P.NT then v = nil end
if i == len then return v end
return v, unpack_from (i+1)
end
if len > 0 then return unpack_from (1) end
end
-- print results (deep into arrays)
function P.print_results (val, indent, lut)
indent = indent or ""
lut = lut or {} -- look-up table
local str = tostring (val)
if type (val) == "table" then
if val == P.NT then
print (indent .. "nil")
elseif lut[val] then
print (indent .. str)
else
lut[val] = true
print (indent .. str)
for i,v in ipairs (val) do
P.print_results (v, " " .. indent, lut) -- recursion
end
end
else
print (indent .. str)
end
end
-- returns:
-- 1) true, if success; false, if failure
-- 2) test results table or error_message
function P.test_function (test, func)
local res
local t = packNT (pcall (func, unpackNT (test[1])))
if t[1] then
table.remove (t, 1)
res = t
else
res = t[2] --> error_message
end
local how = (type (res) == type (test[2])) and
(type (res) == "string" or P.eq (res, test[2])) -- allow error messages to differ
return how, res
end
-- returns:
-- 1) true, if success; false, if failure
-- 2) test results table or error_message
-- 3) test results table or error_message
function P.test_method (test, constructor, name)
local res1, res2
local ok, r = pcall (constructor, unpackNT (test[1]))
if ok then
local t = packNT (pcall (r[name], r, unpackNT (test[2])))
if t[1] then
table.remove (t, 1)
res1, res2 = t
else
res1, res2 = 2, t[2] --> 2, error_message
end
else
res1, res2 = 1, r --> 1, error_message
end
return P.eq (res1, test[3]), res1, res2
end
-- returns: a list of failed tests
function P.test_set (set, lib)
local list = {}
if type (set.Func) == "function" then
local func = set.Func
for i,test in ipairs (set) do
local ok, res = P.test_function (test, func)
if not ok then
table.insert (list, {i=i, res})
end
end
elseif type (set.Method) == "string" then
for i,test in ipairs (set) do
local ok, res1, res2 = P.test_method (test, lib.new, set.Method)
if not ok then
table.insert (list, {i=i, res1, res2})
end
end
else
error ("neither set.Func nor set.Method is valid")
end
return list
end
return P
|
luatest.lua: 1) bugfix; 2) don't use `module' function;
|
luatest.lua: 1) bugfix; 2) don't use `module' function;
|
Lua
|
mit
|
LuaDist/lrexlib-pcre,LuaDist/lrexlib-gnu,LuaDist/lrexlib-posix,StoneDot/lrexlib,LuaDist/lrexlib-oniguruma,LuaDist/lrexlib-oniguruma,LuaDist/lrexlib-gnu,LuaDist/lrexlib-posix,LuaDist/lrexlib-pcre,LuaDist/lrexlib-tre,LuaDist/lrexlib-tre,StoneDot/lrexlib
|
4e04e353fe91107d27046f93d63aa9aa92418ce8
|
modules/admin-full/luasrc/model/cbi/admin_network/hosts.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/hosts.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.util")
m = Map("dhcp", translate("Hostnames"))
s = m:section(TypedSection, "domain", translate("Host entries"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
hn = s:option(Value, "name", translate("Hostname"))
hn.datatype = "hostname"
hn.rmempty = true
ip = s:option(Value, "ip", translate("IP address"))
ip.datatype = "ipaddr"
ip.rmempty = true
for i, dataset in ipairs(luci.sys.net.arptable()) do
ip:value(
dataset["IP address"],
"%s (%s)" %{ dataset["IP address"], dataset["HW address"] }
)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.util")
m = Map("dhcp", translate("Hostnames"))
s = m:section(TypedSection, "domain", translate("Host entries"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
hn = s:option(Value, "name", translate("Hostname"))
hn.datatype = "hostname"
hn.rmempty = true
ip = s:option(Value, "ip", translate("IP address"))
ip.datatype = "ipaddr"
ip.rmempty = true
local arptable = luci.sys.net.arptable() or {}
for i, dataset in ipairs(arptable) do
ip:value(
dataset["IP address"],
"%s (%s)" %{ dataset["IP address"], dataset["HW address"] }
)
end
return m
|
admin-full/network/hosts: Fix problem when arptable is empty, #482
|
admin-full/network/hosts: Fix problem when arptable is empty, #482
|
Lua
|
apache-2.0
|
teslamint/luci,openwrt/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,mumuqz/luci,cshore/luci,oneru/luci,sujeet14108/luci,Hostle/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,kuoruan/luci,bittorf/luci,taiha/luci,Kyklas/luci-proto-hso,joaofvieira/luci,daofeng2015/luci,fkooman/luci,981213/luci-1,remakeelectric/luci,marcel-sch/luci,obsy/luci,remakeelectric/luci,palmettos/test,nmav/luci,harveyhu2012/luci,tobiaswaldvogel/luci,joaofvieira/luci,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,aa65535/luci,981213/luci-1,lbthomsen/openwrt-luci,thess/OpenWrt-luci,jlopenwrtluci/luci,artynet/luci,keyidadi/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,male-puppies/luci,mumuqz/luci,dwmw2/luci,openwrt/luci,kuoruan/luci,male-puppies/luci,tcatm/luci,RuiChen1113/luci,palmettos/test,openwrt-es/openwrt-luci,openwrt/luci,LuttyYang/luci,marcel-sch/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,rogerpueyo/luci,shangjiyu/luci-with-extra,cappiewu/luci,sujeet14108/luci,daofeng2015/luci,hnyman/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,opentechinstitute/luci,981213/luci-1,Hostle/openwrt-luci-multi-user,Hostle/luci,openwrt/luci,cappiewu/luci,keyidadi/luci,dismantl/luci-0.12,tcatm/luci,dismantl/luci-0.12,981213/luci-1,daofeng2015/luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,LuttyYang/luci,kuoruan/lede-luci,cshore/luci,cshore/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,wongsyrone/luci-1,jorgifumi/luci,forward619/luci,urueedi/luci,dwmw2/luci,MinFu/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,cappiewu/luci,palmettos/test,cshore-firmware/openwrt-luci,Noltari/luci,remakeelectric/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,981213/luci-1,kuoruan/luci,palmettos/cnLuCI,harveyhu2012/luci,cshore/luci,hnyman/luci,ollie27/openwrt_luci,Wedmer/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,oneru/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,artynet/luci,palmettos/cnLuCI,forward619/luci,daofeng2015/luci,male-puppies/luci,lcf258/openwrtcn,maxrio/luci981213,cshore/luci,nmav/luci,ff94315/luci-1,ollie27/openwrt_luci,thesabbir/luci,artynet/luci,kuoruan/luci,deepak78/new-luci,openwrt/luci,forward619/luci,harveyhu2012/luci,rogerpueyo/luci,981213/luci-1,maxrio/luci981213,opentechinstitute/luci,nwf/openwrt-luci,ff94315/luci-1,teslamint/luci,lcf258/openwrtcn,palmettos/cnLuCI,nwf/openwrt-luci,ff94315/luci-1,tcatm/luci,MinFu/luci,taiha/luci,aa65535/luci,Hostle/luci,hnyman/luci,tcatm/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,oyido/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,ollie27/openwrt_luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,oneru/luci,rogerpueyo/luci,jchuang1977/luci-1,jlopenwrtluci/luci,slayerrensky/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,thesabbir/luci,Noltari/luci,shangjiyu/luci-with-extra,artynet/luci,cappiewu/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,oneru/luci,thesabbir/luci,bittorf/luci,schidler/ionic-luci,chris5560/openwrt-luci,lcf258/openwrtcn,sujeet14108/luci,shangjiyu/luci-with-extra,artynet/luci,forward619/luci,thesabbir/luci,Hostle/luci,nmav/luci,lbthomsen/openwrt-luci,981213/luci-1,cappiewu/luci,daofeng2015/luci,oneru/luci,jchuang1977/luci-1,db260179/openwrt-bpi-r1-luci,hnyman/luci,david-xiao/luci,teslamint/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,opentechinstitute/luci,jchuang1977/luci-1,jorgifumi/luci,thess/OpenWrt-luci,thesabbir/luci,jorgifumi/luci,Noltari/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,urueedi/luci,nmav/luci,Wedmer/luci,jorgifumi/luci,thess/OpenWrt-luci,deepak78/new-luci,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,palmettos/test,oyido/luci,thesabbir/luci,thesabbir/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,marcel-sch/luci,keyidadi/luci,NeoRaider/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,dismantl/luci-0.12,bright-things/ionic-luci,Noltari/luci,nmav/luci,Noltari/luci,bittorf/luci,lcf258/openwrtcn,remakeelectric/luci,ollie27/openwrt_luci,aa65535/luci,ff94315/luci-1,keyidadi/luci,oyido/luci,kuoruan/lede-luci,hnyman/luci,slayerrensky/luci,cappiewu/luci,male-puppies/luci,marcel-sch/luci,LuttyYang/luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,MinFu/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,oyido/luci,florian-shellfire/luci,tobiaswaldvogel/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,Hostle/luci,chris5560/openwrt-luci,obsy/luci,remakeelectric/luci,taiha/luci,remakeelectric/luci,Hostle/luci,dismantl/luci-0.12,rogerpueyo/luci,ollie27/openwrt_luci,lcf258/openwrtcn,NeoRaider/luci,joaofvieira/luci,sujeet14108/luci,fkooman/luci,urueedi/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,zhaoxx063/luci,aa65535/luci,harveyhu2012/luci,maxrio/luci981213,hnyman/luci,obsy/luci,lbthomsen/openwrt-luci,jchuang1977/luci-1,oyido/luci,openwrt/luci,david-xiao/luci,dismantl/luci-0.12,RuiChen1113/luci,hnyman/luci,nwf/openwrt-luci,obsy/luci,joaofvieira/luci,nwf/openwrt-luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,deepak78/new-luci,wongsyrone/luci-1,MinFu/luci,oneru/luci,mumuqz/luci,kuoruan/luci,LuttyYang/luci,dwmw2/luci,aa65535/luci,LuttyYang/luci,harveyhu2012/luci,joaofvieira/luci,palmettos/test,Sakura-Winkey/LuCI,jlopenwrtluci/luci,NeoRaider/luci,jlopenwrtluci/luci,teslamint/luci,MinFu/luci,keyidadi/luci,cshore/luci,deepak78/new-luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,kuoruan/luci,Noltari/luci,schidler/ionic-luci,Noltari/luci,lcf258/openwrtcn,artynet/luci,Hostle/luci,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,fkooman/luci,bright-things/ionic-luci,dwmw2/luci,NeoRaider/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,fkooman/luci,Noltari/luci,RuiChen1113/luci,schidler/ionic-luci,ollie27/openwrt_luci,LuttyYang/luci,zhaoxx063/luci,florian-shellfire/luci,fkooman/luci,aa65535/luci,oyido/luci,maxrio/luci981213,zhaoxx063/luci,tcatm/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,jorgifumi/luci,maxrio/luci981213,kuoruan/lede-luci,teslamint/luci,keyidadi/luci,taiha/luci,palmettos/cnLuCI,thesabbir/luci,taiha/luci,nmav/luci,nwf/openwrt-luci,sujeet14108/luci,slayerrensky/luci,florian-shellfire/luci,palmettos/cnLuCI,wongsyrone/luci-1,forward619/luci,fkooman/luci,mumuqz/luci,bittorf/luci,palmettos/cnLuCI,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,Wedmer/luci,Wedmer/luci,florian-shellfire/luci,chris5560/openwrt-luci,ff94315/luci-1,bittorf/luci,MinFu/luci,lcf258/openwrtcn,florian-shellfire/luci,taiha/luci,zhaoxx063/luci,marcel-sch/luci,palmettos/cnLuCI,kuoruan/lede-luci,obsy/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,ff94315/luci-1,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,nmav/luci,mumuqz/luci,cappiewu/luci,slayerrensky/luci,oneru/luci,RuiChen1113/luci,aa65535/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,tcatm/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,palmettos/test,schidler/ionic-luci,schidler/ionic-luci,artynet/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,Wedmer/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,jlopenwrtluci/luci,openwrt/luci,nmav/luci,daofeng2015/luci,tcatm/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,obsy/luci,thess/OpenWrt-luci,david-xiao/luci,cshore/luci,forward619/luci,jorgifumi/luci,harveyhu2012/luci,chris5560/openwrt-luci,forward619/luci,jlopenwrtluci/luci,rogerpueyo/luci,david-xiao/luci,kuoruan/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,NeoRaider/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,MinFu/luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,deepak78/new-luci,NeoRaider/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,oneru/luci,urueedi/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,kuoruan/luci,urueedi/luci,jorgifumi/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,Wedmer/luci,palmettos/test,bright-things/ionic-luci,dwmw2/luci,joaofvieira/luci,sujeet14108/luci,florian-shellfire/luci,jorgifumi/luci,slayerrensky/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,Wedmer/luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,obsy/luci,remakeelectric/luci,dwmw2/luci,oyido/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,urueedi/luci,urueedi/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,forward619/luci,slayerrensky/luci,nwf/openwrt-luci,cshore/luci,teslamint/luci,aa65535/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,wongsyrone/luci-1,bright-things/ionic-luci,bittorf/luci,keyidadi/luci,ollie27/openwrt_luci,male-puppies/luci,cappiewu/luci,nmav/luci,RuiChen1113/luci,teslamint/luci,keyidadi/luci,rogerpueyo/luci,oyido/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,joaofvieira/luci,deepak78/new-luci,sujeet14108/luci,artynet/luci,jchuang1977/luci-1,RuiChen1113/luci,wongsyrone/luci-1,daofeng2015/luci,rogerpueyo/luci,schidler/ionic-luci,ollie27/openwrt_luci,david-xiao/luci,harveyhu2012/luci,tobiaswaldvogel/luci,male-puppies/luci,openwrt-es/openwrt-luci,male-puppies/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,bright-things/ionic-luci,deepak78/new-luci,taiha/luci,artynet/luci,Kyklas/luci-proto-hso,mumuqz/luci,nwf/openwrt-luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,tobiaswaldvogel/luci,Noltari/luci,maxrio/luci981213,lcf258/openwrtcn,zhaoxx063/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,openwrt-es/openwrt-luci,remakeelectric/luci
|
f213f02b85405e770f22c36ed72ced7e8b58fb35
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local table = require('table')
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local table = require('table')
local http = require("http")
local url = require('url')
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
set_option(opts, "listen_ip", '127.0.0.1')
set_option(opts, "perform_client_disconnect", 'true')
set_option(opts, "rate_limit", 3000)
set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
local destroy = false
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
-- Handle rate limit logic
client.rate_limit = client.rate_limit - 1
if client.rate_limit <= 0 then
response = JSON.parse(fixtures['rate-limiting']['rate-limit-error'])
destroy = true
end
response.target = payload.source
response.source = payload.target
response.id = payload.id
log("Sending response:")
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
if destroy == true then
client:destroy()
end
return destroy
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function clear_timers(timer_ids)
for k, v in pairs(timer_ids) do
if v._closed ~= true then
timer.clearTimer(v)
end
end
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
local server = tls.createServer(options, function (client)
local lineEmitter = LineEmitter:new()
local destroyed = false
local timers = {}
client.rate_limit = opts.rate_limit
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
destroyed = respond(log, client, payload)
if destroyed == true then
clear_timers(timers)
end
end)
-- Reset rate limit counter
timer.setTimeout(opts.rate_limit_reset, function()
client.rate_limit = opts.rate_limit
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
table.insert(timers,
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
if opts.perform_client_disconnect == 'true' then
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end
end):listen(port, opts.listen_ip)
return server
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local table = require('table')
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local table = require('table')
local http = require("http")
local url = require('url')
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
set_option(opts, "listen_ip", '127.0.0.1')
set_option(opts, "perform_client_disconnect", 'true')
set_option(opts, "rate_limit", 3000)
set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
local destroy = false
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
-- Handle rate limit logic
client.rate_limit = client.rate_limit - 1
if client.rate_limit <= 0 then
response = JSON.parse(fixtures['rate-limiting']['rate-limit-error'])
destroy = true
end
response.target = payload.source
response.source = payload.target
response.id = payload.id
-- Print the payload. The p() is intentional, Ryan :D
log("Sending response:")
p(response)
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
if destroy == true then
client:destroy()
end
return destroy
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function clear_timers(timer_ids)
for k, v in pairs(timer_ids) do
if v._closed ~= true then
timer.clearTimer(v)
end
end
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
local server = tls.createServer(options, function (client)
local lineEmitter = LineEmitter:new()
local destroyed = false
local timers = {}
client.rate_limit = opts.rate_limit
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
destroyed = respond(log, client, payload)
if destroyed == true then
clear_timers(timers)
end
end)
-- Reset rate limit counter
timer.setTimeout(opts.rate_limit_reset, function()
client.rate_limit = opts.rate_limit
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
table.insert(timers,
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
if opts.perform_client_disconnect == 'true' then
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end
end):listen(port, opts.listen_ip)
return server
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
monitoring: tests: fixtures: server re-add print
|
monitoring: tests: fixtures: server re-add print
re-add the print that Ryan removed accidently with a comment.
|
Lua
|
apache-2.0
|
cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent
|
f7a657b41522de421b2ba84546188ecb390e57f5
|
util/timer.lua
|
util/timer.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local event = require "net.server".event;
local get_time = os.time;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local _add_task;
if not event then
function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else
func();
end
end
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in pairs(new_data) do
t_insert(data, d);
end
new_data = {};
end
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
data[i] = nil;
local r = func(current_time);
if type(r) == "number" then _add_task(r, func); end
end
end
end);
else
local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
function _add_task(delay, func)
event.base:addevent(nil, event.EV_TIMEOUT, function ()
local ret = func();
if ret then
_add_task(ret, func);
else
return EVENT_LEAVE;
end
end
, delay);
end
end
add_task = _add_task;
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local event = require "net.server".event;
local event_base = require "net.server".event_base;
local get_time = os.time;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local _add_task;
if not event then
function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else
func();
end
end
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in pairs(new_data) do
t_insert(data, d);
end
new_data = {};
end
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
data[i] = nil;
local r = func(current_time);
if type(r) == "number" then _add_task(r, func); end
end
end
end);
else
local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
function _add_task(delay, func)
event_base:addevent(nil, event.EV_TIMEOUT, function ()
local ret = func();
if ret then
_add_task(ret, func);
else
return EVENT_LEAVE;
end
end
, delay);
end
end
add_task = _add_task;
return _M;
|
util.timer: Fix libevent timers (event.base doesn't exist...)
|
util.timer: Fix libevent timers (event.base doesn't exist...)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2536e8024ce4939c2aa36ded2381415182f1fb76
|
util/timer.lua
|
util/timer.lua
|
-- Prosody IM v0.3
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local get_time = os.time;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else func(); end
end
add_task = _add_task;
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in ipairs(new_data) do
t_insert(data, d);
end
new_data = {};
elseif #data == 0 then
return;
end
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
t_remove(data, i);
local r = func();
if type(r) == "number" then _add_task(r, func); end
end
end
end);
return _M;
|
-- Prosody IM v0.3
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ns_addtimer = require "net.server".addtimer;
local get_time = os.time;
local t_insert = table.insert;
local t_remove = table.remove;
local ipairs, pairs = ipairs, pairs;
local type = type;
local data = {};
local new_data = {};
module "timer"
local function _add_task(delay, func)
local current_time = get_time();
delay = delay + current_time;
if delay >= current_time then
t_insert(new_data, {delay, func});
else func(); end
end
add_task = _add_task;
ns_addtimer(function()
local current_time = get_time();
if #new_data > 0 then
for _, d in pairs(new_data) do
t_insert(data, d);
end
new_data = {};
end
for i, d in pairs(data) do
local t, func = d[1], d[2];
if t <= current_time then
data[i] = nil;
local r = func();
if type(r) == "number" then _add_task(r, func); end
end
end
end);
return _M;
|
util.timer: More small fixes I forgot to commit
|
util.timer: More small fixes I forgot to commit
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2f4a33a19bfb6119cd0f896ac764bd078c5d43c8
|
vi_views.lua
|
vi_views.lua
|
-- Functions for manipulating views
local M = {}
local function unsplit_other(ts)
if ts.vertical == nil then
-- Ensure this view is focused (so we don't delete the focused view)
for k,v in ipairs(_G._VIEWS) do
if ts == v then
ui.goto_view(k)
break
end
end
view.unsplit(ts)
else
unsplit_other(ts[1])
end
end
local function close_siblings_of(v, ts)
local v = view
local ts = ts or ui.get_split_table()
if ts.vertical == nil then
-- This is just a view
return false
else
if ts[1] == v then
-- We can't quite just close the current view. Pick the first
-- on the other side.
return unsplit_other(ts[2])
else if ts[2] == v then
return unsplit_other(ts[1])
else
return close_siblings_of(v, ts[1]) or close_siblings_of(v, ts[2])
end end
end
end
M.close_siblings_of = close_siblings_of
--
-- Find the view's parent split (in ui.get_split_table())
local function find_view_parent(v, ts)
local ts = ts or ui.get_split_table()
if ts[1] and ts[2] then
-- This is a split
if ts[1] == v or ts[2] == v then return ts end
return find_view_parent(v, ts[1]) or find_view_parent(v, ts[2])
else
-- Must be a view - which can't be v's parent.
return nil
end
end
--
-- Find the view's parent's size (either vertical or horizontal, depending
-- on the split)
local function find_view_parent_size(v, split, width, height)
local ts, w, h
if split == nil then
ts = ui.get_split_table()
w = ui.size[1]
h = ui.size[2] - 2 -- Top and bottom lines used by UI
else
ts = split
w = width
h = height
end
if ts[1] and ts[2] then
-- This is a split. Calculate the subsplit sizes
local w1, h1, w2, h2 = w, h, w, h
if ts.vertical then
w1 = ts.size
w2 = w - ts.size - 1
else
h1 = ts.size
h2 = h - ts.size - 1
end
if ts[1] == v or ts[2] == v then
-- This is v's parent
if ts.vertical then return w else return h end
else
-- recurse
return find_view_parent_size(v, ts[1], w1, h1) or
find_view_parent_size(v, ts[2], w2, h2)
end
else
-- Must be a view - which can't be v's parent.
return
end
end
-- Grow (or shrink, with a negative increment) a view's size.
function M.grow_view(v, inc)
local parent = find_view_parent(v)
local is_first = v == parent[1]
local parent_size = find_view_parent_size(v)
if not is_first then inc = -inc end
local new_size = v.size + inc
if new_size < 1 then new_size = 1 end
if new_size >= (parent_size-1) then new_size = parent_size - 2 end
v.size = new_size
end
return M
|
-- Functions for manipulating views
local M = {}
local function unsplit_other(ts)
if ts.vertical == nil then
-- Ensure this view is focused (so we don't delete the focused view)
for k,v in ipairs(_G._VIEWS) do
if ts == v then
ui.goto_view(k)
break
end
end
view.unsplit(ts)
else
unsplit_other(ts[1])
end
end
local function close_siblings_of(v, ts)
local v = view
local ts = ts or ui.get_split_table()
if ts.vertical == nil then
-- This is just a view
return false
else
if ts[1] == v then
-- We can't quite just close the current view. Pick the first
-- on the other side.
return unsplit_other(ts[2])
else if ts[2] == v then
return unsplit_other(ts[1])
else
return close_siblings_of(v, ts[1]) or close_siblings_of(v, ts[2])
end end
end
end
M.close_siblings_of = close_siblings_of
--
-- Find the view's parent split (in ui.get_split_table())
local function find_view_parent(v, ts)
local ts = ts or ui.get_split_table()
if ts[1] and ts[2] then
-- This is a split
if ts[1] == v or ts[2] == v then return ts end
return find_view_parent(v, ts[1]) or find_view_parent(v, ts[2])
else
-- Must be a view - which can't be v's parent.
return nil
end
end
--
-- Find the view's parent's size (either vertical or horizontal, depending
-- on the split)
local function find_view_parent_size(v, split, width, height)
local ts, w, h
if split == nil then
ts = ui.get_split_table()
w = ui.size[1]
h = ui.size[2] - 2 -- Top and bottom lines used by UI
else
ts = split
w = width
h = height
end
if ts[1] and ts[2] then
-- This is a split. Calculate the subsplit sizes
local w1, h1, w2, h2 = w, h, w, h
if ts.vertical then
w1 = ts.size
w2 = w - ts.size - 1
else
h1 = ts.size
h2 = h - ts.size - 1
end
if ts[1] == v or ts[2] == v then
-- This is v's parent
if ts.vertical then return w else return h end
else
-- recurse
return find_view_parent_size(v, ts[1], w1, h1) or
find_view_parent_size(v, ts[2], w2, h2)
end
else
-- Must be a view - which can't be v's parent.
return
end
end
-- Grow (or shrink, with a negative increment) a view's size.
function M.grow_view(v, inc)
local parent = find_view_parent(v)
-- Do nothing if no split
if perent == nil then return end
local is_first = v == parent[1]
local parent_size = find_view_parent_size(v)
if not is_first then inc = -inc end
local new_size = v.size + inc
if new_size < 1 then new_size = 1 end
if new_size >= (parent_size-1) then new_size = parent_size - 2 end
v.size = new_size
end
return M
|
Fix an error when adjusting the size of a non-split view.
|
Fix an error when adjusting the size of a non-split view.
|
Lua
|
mit
|
jugglerchris/textadept-vi,jugglerchris/textadept-vi
|
ebbfaf1c13c4867e65d34b3a7ef581cc344d4dc6
|
build/premake4.lua
|
build/premake4.lua
|
function setTargetObjDir(outDir)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
--"_debug_win32_vs2008"
local suffix = "_" .. cfg .. "_" .. plat .. "_" .. action
targetPath = outDir
suffix = string.lower(suffix)
local obj_path = "../intermediate/" .. cfg .. "/" .. action .. "/" .. prj.name
obj_path = string.lower(obj_path)
configuration {cfg, plat}
targetdir(targetPath)
objdir(obj_path)
targetsuffix(suffix)
end
end
end
function linkLib(libBaseName)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
local cfgName = cfg
--"_debug_win32_vs2008"
local suffix = "_" .. cfgName .. "_" .. plat .. "_" .. action
libFullName = libBaseName .. string.lower(suffix)
configuration {cfg, plat}
links(libFullName)
end
end
end
solution "test"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-msse4.2 -Werror -Wall -Wextra"
project "gtest"
kind "StaticLib"
defines { "GTEST_HAS_PTHREAD=0" }
files {
"../thirdparty/gtest/src/gtest-all.cc",
"../thirdparty/gtest/src/**.h",
}
includedirs {
"../thirdparty/gtest/",
"../thirdparty/gtest/include",
}
setTargetObjDir("../thirdparty/lib")
project "unittest"
kind "ConsoleApp"
buildoptions "-Weffc++"
files {
"../include/**.h",
"../test/unittest/**.cpp",
"../test/unittest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
project "perftest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/perftest/**.cpp",
"../test/perftest/**.c",
"../test/perftest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
"../thirdparty/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/libjson/",
"../thirdparty/yajl/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
solution "example"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
includedirs "../include/"
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize", "EnableSSE2" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-Werror -Wall -Wextra -Weffc++"
project "condense"
kind "ConsoleApp"
files "../example/condense/*"
setTargetObjDir("../bin")
project "pretty"
kind "ConsoleApp"
files "../example/pretty/*"
setTargetObjDir("../bin")
project "prettyauto"
kind "ConsoleApp"
files "../example/prettyauto/*"
setTargetObjDir("../bin")
project "tutorial"
kind "ConsoleApp"
files "../example/tutorial/*"
setTargetObjDir("../bin")
project "serialize"
kind "ConsoleApp"
files "../example/serialize/*"
setTargetObjDir("../bin")
project "simpledom"
kind "ConsoleApp"
files "../example/simpledom/*"
setTargetObjDir("../bin")
|
function setTargetObjDir(outDir)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
--"_debug_win32_vs2008"
local suffix = "_" .. cfg .. "_" .. plat .. "_" .. action
targetPath = outDir
suffix = string.lower(suffix)
local obj_path = "../intermediate/" .. cfg .. "/" .. action .. "/" .. prj.name
obj_path = string.lower(obj_path)
configuration {cfg, plat}
targetdir(targetPath)
objdir(obj_path)
targetsuffix(suffix)
end
end
end
function linkLib(libBaseName)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
local cfgName = cfg
--"_debug_win32_vs2008"
local suffix = "_" .. cfgName .. "_" .. plat .. "_" .. action
libFullName = libBaseName .. string.lower(suffix)
configuration {cfg, plat}
links(libFullName)
end
end
end
solution "test"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-msse4.2 -Werror -Wall -Wextra"
project "gtest"
kind "StaticLib"
defines { "GTEST_HAS_PTHREAD=0" }
files {
"../thirdparty/gtest/src/gtest-all.cc",
"../thirdparty/gtest/src/**.h",
}
includedirs {
"../thirdparty/gtest/",
"../thirdparty/gtest/include",
}
setTargetObjDir("../thirdparty/lib")
project "unittest"
kind "ConsoleApp"
if _ACTION == "gmake" then
buildoptions "-Weffc++"
end
files {
"../include/**.h",
"../test/unittest/**.cpp",
"../test/unittest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
project "perftest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/perftest/**.cpp",
"../test/perftest/**.c",
"../test/perftest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
"../thirdparty/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/libjson/",
"../thirdparty/yajl/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
solution "example"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
includedirs "../include/"
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize", "EnableSSE2" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-Werror -Wall -Wextra -Weffc++"
project "condense"
kind "ConsoleApp"
files "../example/condense/*"
setTargetObjDir("../bin")
project "pretty"
kind "ConsoleApp"
files "../example/pretty/*"
setTargetObjDir("../bin")
project "prettyauto"
kind "ConsoleApp"
files "../example/prettyauto/*"
setTargetObjDir("../bin")
project "tutorial"
kind "ConsoleApp"
files "../example/tutorial/*"
setTargetObjDir("../bin")
project "serialize"
kind "ConsoleApp"
files "../example/serialize/*"
setTargetObjDir("../bin")
project "simpledom"
kind "ConsoleApp"
files "../example/simpledom/*"
setTargetObjDir("../bin")
|
Fixes premake4 script for VS
|
Fixes premake4 script for VS
|
Lua
|
mit
|
zhengxle/rapidjson,zhengxle/rapidjson,zhengxle/rapidjson
|
a31c9b64d816ac3a694fbc397ccf491292fc7f23
|
pyf.lua
|
pyf.lua
|
-- Issue: Mapping Chinese Pinyin First Letter Implementation
-- Copyright (C)2017 ms2008 <[email protected]>
local bit = require "bit"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local bit_band = bit.band
local bit_bor = bit.bor
local bit_lshift = bit.lshift
local string_format = string.format
local string_gmatch = string.gmatch
local string_match = string.match
local string_byte = string.byte
local string_char = string.char
local table_concat = table.concat
local io_open = io.open
local io_close = io.close
local ipairs = ipairs
local tonumber = tonumber
ffi.cdef[[
char pinyinFirstLetter(unsigned short hanzi);
]]
local _M = {
_VERSION = '0.10'
}
local pyf_lib
-- Find shared object file package.cpath, obviating the need of setting
-- LD_LIBRARY_PATH
local function find_shared_obj(cpath, so_name)
for k in string_gmatch(cpath, "[^;]+") do
local so_path = string_match(k, "(.*/)")
so_path = so_path .. so_name
-- Don't get me wrong, the only way to know if a file exist is trying
-- to open it.
local f = io_open(so_path)
if f ~= nil then
io_close(f)
return so_path
end
end
end
-- Helper wrappring script for loading shared object pinyin.so (FFI interface)
-- from package.cpath instead of LD_LIBRARTY_PATH.
local function load_pyf_parser()
if pyf_lib ~= nil then
return pyf_lib
else
local so_path = find_shared_obj(package.cpath, "pinyin.so")
if so_path ~= nil then
pyf_lib = ffi.load(so_path)
return pyf_lib
end
end
end
local function pinyinFirstLetter(hanzi)
if not pyf_lib then
pyf_lib = load_pyf_parser()
end
local result = pyf_lib.pinyinFirstLetter(hanzi)
-- return ffi_str(result)
return string_char(result)
end
-- taken from http://jinnianshilongnian.iteye.com/blog/2187643
local function utf8_to_unicode(str)
if not str or str == "" then
return nil
end
local res, seq, val = {}, 0, nil
for i = 1, #str do
local c = string_byte(str, i)
if seq == 0 then
if val then
res[#res + 1] = string_format("%04x", val)
end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
0
if seq == 0 then
ngx.log(ngx.ERR, 'invalid UTF-8 character sequence' .. ",,," .. tostring(str))
return str
end
val = bit_band(c, 2 ^ (8 - seq) - 1)
else
val = bit_bor(bit_lshift(val, 6), bit_band(c, 0x3F))
end
seq = seq - 1
end
if val then
res[#res + 1] = string_format("%04x", val)
end
if #res == 0 then
return str
end
return table_concat(res, "")
end
local function uniStr(str)
if not str then
return nil
end
local tab = {}
for uchar in string_gmatch(str, "[%z\1-\127\194-\244][\128-\191]*") do
tab[#tab+1] = uchar
end
return tab
end
function _M:pinyin(s)
local pyf = {}
for i, v in ipairs(uniStr(s)) do
pyf[i] = pinyinFirstLetter(tonumber(utf8_to_unicode(v), 16))
end
return table_concat(pyf, "")
end
return _M
|
-- Issue: Mapping Chinese Pinyin First Letter Implementation
-- Copyright (C)2017 ms2008 <[email protected]>
local bit = require "bit"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local bit_band = bit.band
local bit_bor = bit.bor
local bit_lshift = bit.lshift
local string_format = string.format
local string_gmatch = string.gmatch
local string_match = string.match
local string_byte = string.byte
local string_char = string.char
local table_concat = table.concat
local io_open = io.open
local io_close = io.close
local ipairs = ipairs
local tonumber = tonumber
ffi.cdef[[
char pinyinFirstLetter(unsigned short hanzi);
]]
local _M = {
_VERSION = '0.10'
}
local pyf_lib
-- Find shared object file package.cpath, obviating the need of setting
-- LD_LIBRARY_PATH
local function find_shared_obj(cpath, so_name)
for k in string_gmatch(cpath, "[^;]+") do
local so_path = string_match(k, "(.*/)")
so_path = so_path .. so_name
-- Don't get me wrong, the only way to know if a file exist is trying
-- to open it.
local f = io_open(so_path)
if f ~= nil then
io_close(f)
return so_path
end
end
end
-- Helper wrappring script for loading shared object pinyin.so (FFI interface)
-- from package.cpath instead of LD_LIBRARTY_PATH.
local function load_pyf_parser()
if pyf_lib ~= nil then
return pyf_lib
else
local so_path = find_shared_obj(package.cpath, "pinyin.so")
if so_path ~= nil then
pyf_lib = ffi.load(so_path)
return pyf_lib
end
end
end
-- Unicode code point range[19968, 20902]
local function pinyinFirstLetter(hanzi)
if not pyf_lib then
pyf_lib = load_pyf_parser()
end
local result = pyf_lib.pinyinFirstLetter(hanzi)
-- return ffi_str(result)
return string_char(result)
end
-- taken from http://jinnianshilongnian.iteye.com/blog/2187643
local function utf8_to_unicode(str)
if not str or str == "" then
return nil
end
local res, seq, val = {}, 0, nil
for i = 1, #str do
local c = string_byte(str, i)
if seq == 0 then
if val then
res[#res + 1] = string_format("%04x", val)
end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
0
if seq == 0 then
ngx.log(ngx.ERR, 'invalid UTF-8 character sequence' .. ",,," .. tostring(str))
return str
end
val = bit_band(c, 2 ^ (8 - seq) - 1)
else
val = bit_bor(bit_lshift(val, 6), bit_band(c, 0x3F))
end
seq = seq - 1
end
if val then
res[#res + 1] = string_format("%04x", val)
end
if #res == 0 then
return str
end
return table_concat(res, "")
end
local function uniStr(str)
if not str then
return nil
end
local tab = {}
for uchar in string_gmatch(str, "[%z\1-\127\194-\244][\128-\191]*") do
tab[#tab+1] = uchar
end
return tab
end
function _M:pinyin(s)
local pyf = {}
for i, v in ipairs(uniStr(s)) do
pyf[i] = pinyinFirstLetter(tonumber(utf8_to_unicode(v), 16))
end
return table_concat(pyf, "")
end
return _M
|
minor fixes
|
minor fixes
|
Lua
|
mit
|
ms2008/lua-resty-pyf
|
9ad7646259d0b157c0da2c7e0c53e6997cc1826f
|
src/nodes/wall.lua
|
src/nodes/wall.lua
|
local Wall = {}
Wall.__index = Wall
function Wall.new(node, collider)
local wall = {}
setmetatable(wall, Wall)
wall.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
wall.bb.node = wall
collider:setPassive(wall.bb)
return wall
end
function Wall:collide(player, dt, mtv_x, mtv_y)
if mtv_x ~= 0 then
player.velocity.x = 0
player.position.x = player.position.x + mtv_x
end
if mtv_y ~= 0 then
player.velocity.y = 0
player.position.y = player.position.y + mtv_y
end
end
return Wall
|
local Wall = {}
Wall.__index = Wall
function Wall.new(node, collider)
local wall = {}
setmetatable(wall, Wall)
wall.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
wall.bb.node = wall
wall.node = node
collider:setPassive(wall.bb)
return wall
end
function Wall:collide(player, dt, mtv_x, mtv_y)
if mtv_x ~= 0 then
player.velocity.x = 0
player.position.x = player.position.x + mtv_x
end
if mtv_y > 0 then
player.velocity.y = 0
player.position.y = player.position.y + mtv_y
end
if mtv_y < 0 then
player.velocity.y = 0
player.position.y = self.node.y - player.height
player.jumping = false
end
end
return Wall
|
Bug fix so you can stand on a wall
|
Bug fix so you can stand on a wall
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
86e3f50ff9364fee13315bba0dd834ff4dea7715
|
lib/utils/cuda.lua
|
lib/utils/cuda.lua
|
require 'torch'
require 'nn'
require 'nngraph'
local Cuda = {
nn = nn,
activated = false
}
function Cuda.init(opt, gpuIdx)
Cuda.activated = opt.gpuid > 0
if Cuda.activated then
local _, err = pcall(function()
require 'cutorch'
require 'cunn'
if opt.cudnn then
require 'cudnn'
Cuda.nn = cudnn
end
if gpuIdx == nil then
-- allow memory access between devices
cutorch.getKernelPeerToPeerAccess(true)
if opt.seed then
cutorch.manualSeedAll(opt.seed)
end
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(gpuIdx)
end
if opt.seed then
cutorch.manualSeed(opt.seed)
end
end)
if err then
error(err)
end
end
end
function Cuda.convert(obj)
if torch.typename(obj) == nil and type(obj) == 'table' then
for i = 1, #obj do
obj[i] = Cuda.convert(obj[i])
end
return obj
end
if Cuda.activated then
if obj.cuda ~= nil then
return obj:cuda()
end
else
-- Defaults to float instead of double.
return obj:float()
end
end
function Cuda.getGPUs(ngpu)
local gpus = {}
if Cuda.activated then
if ngpu > cutorch.getDeviceCount() then
error("not enough available GPU - " .. ngpu .. " requested, " .. cutorch.getDeviceCount() .. " available")
end
gpus[1] = Cuda.gpuid
local i = 1
while #gpus ~= ngpu do
if i ~= gpus[1] then
table.insert(gpus, i)
end
i = i + 1
end
else
for _ = 1, ngpu do
table.insert(gpus, 0)
end
end
return gpus
end
return Cuda
|
require 'torch'
require 'nn'
require 'nngraph'
local Cuda = {
nn = nn,
activated = false
}
function Cuda.init(opt, gpuIdx)
Cuda.activated = opt.gpuid > 0
if Cuda.activated then
local _, err = pcall(function()
require 'cutorch'
require 'cunn'
if opt.cudnn then
require 'cudnn'
Cuda.nn = cudnn
end
if gpuIdx == nil then
-- allow memory access between devices
cutorch.getKernelPeerToPeerAccess(true)
if opt.seed then
cutorch.manualSeedAll(opt.seed)
end
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(gpuIdx)
end
if opt.seed then
cutorch.manualSeed(opt.seed)
end
end)
if err then
error(err)
end
end
end
function Cuda.convert(obj)
if not torch.typename(obj) and type(obj) == 'table' then
for k, v in pairs(obj) do
obj[k] = Cuda.convert(v)
end
elseif torch.typename(obj) then
if Cuda.activated and obj.cuda ~= nil then
return obj:cuda()
elseif obj.float ~= nil then
-- Defaults to float instead of double.
return obj:float()
end
end
return obj
end
function Cuda.getGPUs(ngpu)
local gpus = {}
if Cuda.activated then
if ngpu > cutorch.getDeviceCount() then
error("not enough available GPU - " .. ngpu .. " requested, " .. cutorch.getDeviceCount() .. " available")
end
gpus[1] = Cuda.gpuid
local i = 1
while #gpus ~= ngpu do
if i ~= gpus[1] then
table.insert(gpus, i)
end
i = i + 1
end
else
for _ = 1, ngpu do
table.insert(gpus, 0)
end
end
return gpus
end
return Cuda
|
fix cuda conversion
|
fix cuda conversion
|
Lua
|
mit
|
jsenellart-systran/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,srush/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,cservan/OpenNMT_scores_0.2.0,jsenellart/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT
|
d1af3049263b724db00b52c7a66146519411c4db
|
nyagos.lua
|
nyagos.lua
|
print("Nihongo Yet Another GOing Shell")
print(string.format("Build at %s with commit %s",nyagos.stamp,nyagos.commit))
print("Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG")
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=os.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function set(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.setenv(left,expand(right))
end
else
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original,1,true) then
right = original
else
right = right .. ";" .. original
end
end
if right then
nyagos.setenv(left,expand(right))
end
end
end
function alias(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.alias(left,right)
end
else
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
x = nyagos.exec
original_print = print
print = nyagos.echo
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
nyagos.setenv("PATHEXT",nyagos.getenv("PATHEXT")..";."..string.upper(suffix))
end
nyagos.suffixes[suffix]=cmdline
end
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
nyagos.argsfilter = function(args)
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
for i=0,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
alias{
assoc='%COMSPEC% /c assoc $*',
attrib='%COMSPEC% /c attrib $*',
copy='%COMSPEC% /c copy $*',
del='%COMSPEC% /c del $*',
dir='%COMSPEC% /c dir $*',
['for']='%COMSPEC% /c for $*',
md='%COMSPEC% /c md $*',
mkdir='%COMSPEC% /c mkdir $*',
mklink='%COMSPEC% /c mklink $*',
move='%COMSPEC% /c move $*',
open='%COMSPEC% /c for %I in ($*) do @start "%I"',
rd='%COMSPEC% /c rd $*',
ren='%COMSPEC% /c ren $*',
rename='%COMSPEC% /c rename $*',
rmdir='%COMSPEC% /c rmdir $*',
start='%COMSPEC% /c start $*',
['type']='%COMSPEC% /c type $*',
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end,
ls='ls -oF $*',
lua_e=function(args)
assert(load(args[1]))()
end,
which=function(args)
for dir1 in string.gmatch(os.getenv('PATH'),"[^;]+") do
for ext1 in string.gmatch(os.getenv('PATHEXT'),"[^;]+") do
local path1 = dir1 .. "\\" .. args[1] .. ext1
if exists(path1) then
nyagos.echo(path1)
end
end
end
end
}
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
x'cd'
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
print("Nihongo Yet Another GOing Shell")
print(string.format("Build at %s with commit %s",nyagos.stamp,nyagos.commit))
print("Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG")
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return nyagos.getenv(w)
end)
end
function hasList(list,target)
local LIST=";"..string.upper(list)..";"
local TARGET=";"..string.upper(target)..";"
return string.find(LIST,TARGET,1,true)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=nyagos.getenv("PATH")
if not hasList(list,dir) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function set(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.setenv(left,expand(right))
end
else
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=nyagos.getenv(left)
if string.find(right,original,1,true) then
right = original
else
right = right .. ";" .. original
end
end
if right then
nyagos.setenv(left,expand(right))
end
end
end
function alias(equation)
if type(equation) == 'table' then
for left,right in pairs(equation) do
nyagos.alias(left,right)
end
else
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
x = nyagos.exec
original_print = print
print = nyagos.echo
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not hasList(orgpathext,newext) then
nyagos.setenv("PATHEXT",orgpathext..";."..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
suffix(".js",{"cscript"})
suffix(".vbs",{"cscript"})
nyagos.argsfilter = function(args)
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
local pathlist = which({args[0]},1)
if #pathlist < 0 then
newargs[#cmdline] = args[0]
else
newargs[#cmdline] = pathlist[1]
end
for i=1,#args do
newargs[#cmdline+i] = args[i]
end
return newargs
end
function which(args,n)
local list={}
for dir1 in string.gmatch(nyagos.getenv('PATH'),"[^;]+") do
local path0 = dir1 .. "\\" .. args[1]
if exists(path0) then
list[ #list+1 ] = path0
n = n - 1
if n == 0 then
return list
end
end
for ext1 in string.gmatch(nyagos.getenv('PATHEXT'),"[^;]+") do
local path1 = dir1 .. "\\" .. args[1] .. ext1
if exists(path1) then
list[ #list+1 ] = path1
n = n - 1
if n == 0 then
return list
end
end
end
end
return list
end
alias{
assoc='%COMSPEC% /c assoc $*',
attrib='%COMSPEC% /c attrib $*',
copy='%COMSPEC% /c copy $*',
del='%COMSPEC% /c del $*',
dir='%COMSPEC% /c dir $*',
['for']='%COMSPEC% /c for $*',
md='%COMSPEC% /c md $*',
mkdir='%COMSPEC% /c mkdir $*',
mklink='%COMSPEC% /c mklink $*',
move='%COMSPEC% /c move $*',
open='%COMSPEC% /c for %I in ($*) do @start "%I"',
rd='%COMSPEC% /c rd $*',
ren='%COMSPEC% /c ren $*',
rename='%COMSPEC% /c rename $*',
rmdir='%COMSPEC% /c rmdir $*',
start='%COMSPEC% /c start $*',
['type']='%COMSPEC% /c type $*',
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end,
ls='ls -oF $*',
lua_e=function(args)
assert(load(args[1]))()
end,
which=function(args)
for _,path1 in pairs(which(args,0)) do
nyagos.echo(path1)
end
end
}
local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE")
if home then
x'cd'
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
suffix 関数実行時の諸不具合を修正
|
suffix 関数実行時の諸不具合を修正
* PATHEXT に拡張子を二重追加してしまう。
→ os.getenv ではなく、nyagos.getenv を使うようにした。
|
Lua
|
bsd-3-clause
|
hattya/nyagos,hattya/nyagos,zetamatta/nyagos,kissthink/nyagos,nocd5/nyagos,tsuyoshicho/nyagos,hattya/nyagos,kissthink/nyagos,kissthink/nyagos,tyochiai/nyagos
|
64abaf9c2511ea1241efc04722daf9f0ed7589b1
|
packages/boustrophedon/init.lua
|
packages/boustrophedon/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "boustrophedon"
local _swap
function package:_init (class)
base._init(self, class)
SILE.hyphenator.languages.grc = { patterns={} }
SILE.nodeMakers.grc = pl.class(SILE.nodeMakers.unicode)
function SILE.nodeMakers.grc.iterator (node, items)
return coroutine.wrap(function ()
for i = 1, #items do
node:addToken(items[i].text, items[i])
node:makeToken()
node:makePenalty()
coroutine.yield(SILE.nodefactory.glue("0pt plus 2pt"))
end
end)
end
_swap = SILE.nodefactory.vbox({})
_swap.outputYourself = function (_, typesetter, _)
typesetter.frame.direction = typesetter.frame.direction == "LTR-TTB" and "RTL-TTB" or "LTR-TTB"
typesetter.frame:newLine()
end
end
function package:registerCommands ()
self:registerCommand("boustrophedon", function (_, content)
SILE.typesetter:leaveHmode()
local saveBoxup = SILE.typesetter.boxUpNodes
local swaps = 0
SILE.typesetter.boxUpNodes = function (self_)
local vboxlist = saveBoxup(self_)
local nl = {}
for i = 1, #vboxlist do
nl[#nl+1] = vboxlist[i]
if nl[#nl].is_vbox then
nl[#nl+1] = _swap
swaps = swaps + 1
end
end
return nl
end
SILE.process(content)
SILE.typesetter:leaveHmode()
SILE.typesetter.boxUpNodes = saveBoxup
if swaps % 2 == 1 then
SILE.typesetter:pushVbox(_swap)
end
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.boustrophedon]
Partly designed to show off SILE’s extensibility, and partly designed for real use by classicists, the \autodoc:package{boustrophedon} package allows you to typeset ancient Greek texts in the ‘ox-turning’ layout—the first line is written left to right as normal, but the next is set right to left, then left to right, and so on.
To use it, you will need to set the font’s language to ancient Greek (\code{grc}) and wrap text in a \autodoc:environment{boustrophedon} environment:
\set[parameter=document.parindent,value=0]{\par
\begin{boustrophedon}
\font[size=22pt,family=Gentium Plus,language=grc]
\noindent{}ΧΑΙΡΕΔΕΜΟΤΟΔΕΣΕΜΑΠΑΤΕΡΕΣΤΕΣΕΘΑΝΟΝΤΟΣΑΝΦΙΧΑΡΕΣΑΓΑΘΟΝΠΑΙΔΑΟΛΟΦΘΡΟΜΕΝΟΣΦΑΙΔΙΜΟΣΕΠΟΙΕ
\end{boustrophedon}
}
(Under normal circumstances, that line would appear as \font[language=grc,family=Gentium Plus]{
ΧΑΙΡΕΔΕΜΟΤΟΔΕΣΕΜΑΠΑΤΕΡΕΣΤΕΣΕΘΑΝΟΝΤΟΣΑΝΦΙΧΑΡΕΣΑΓΑΘΟΝΠΑΙΔΑΟΛΟΦΘΡΟΜΕΝΟΣΦΑΙΔΙΜΟΣΕΠΟΙΕ
}.)
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "boustrophedon"
function package:_init (class)
base._init(self, class)
SILE.hyphenator.languages.grc = { patterns={} }
SILE.nodeMakers.grc = pl.class(SILE.nodeMakers.unicode)
function SILE.nodeMakers.grc.iterator (node, items)
return coroutine.wrap(function ()
for i = 1, #items do
node:addToken(items[i].text, items[i])
node:makeToken()
node:makePenalty()
coroutine.yield(SILE.nodefactory.glue("0pt plus 2pt"))
end
end)
end
end
local function hackVboxDir(v, dir)
local output = v.outputYourself
v.outputYourself = function (self, typesetter, line)
typesetter.frame.direction = dir
typesetter.frame:newLine()
output(self, typesetter, line)
end
end
function package:registerCommands ()
self:registerCommand("boustrophedon", function (_, content)
SILE.typesetter:leaveHmode()
local saveBoxup = SILE.typesetter.boxUpNodes
SILE.typesetter.boxUpNodes = function (self_)
local vboxlist = saveBoxup(self_)
local startdir = SILE.typesetter.frame.direction
local dir = startdir
for i = 1, #vboxlist do
if vboxlist[i].is_vbox then
hackVboxDir(vboxlist[i], dir)
dir = dir == "LTR-TTB" and "RTL-TTB" or "LTR-TTB"
end
end
if startdir == dir then
local restore = SILE.nodefactory.vbox({})
restore.outputYourself = function (_, typesetter, _)
typesetter.frame.direction = startdir
typesetter.frame:newLine()
end
vboxlist[#vboxlist+1] = restore
end
return vboxlist
end
SILE.process(content)
SILE.typesetter:leaveHmode()
SILE.typesetter.boxUpNodes = saveBoxup
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.boustrophedon]
Partly designed to show off SILE’s extensibility, and partly designed for real use by classicists, the \autodoc:package{boustrophedon} package allows you to typeset ancient Greek texts in the ‘ox-turning’ layout—the first line is written left to right as normal, but the next is set right to left, then left to right, and so on.
To use it, you will need to set the font’s language to ancient Greek (\code{grc}) and wrap text in a \autodoc:environment{boustrophedon} environment:
\set[parameter=document.parindent,value=0]{\par
\begin{boustrophedon}
\font[size=22pt,family=Gentium Plus,language=grc]
\noindent{}ΧΑΙΡΕΔΕΜΟΤΟΔΕΣΕΜΑΠΑΤΕΡΕΣΤΕΣΕΘΑΝΟΝΤΟΣΑΝΦΙΧΑΡΕΣΑΓΑΘΟΝΠΑΙΔΑΟΛΟΦΘΡΟΜΕΝΟΣΦΑΙΔΙΜΟΣΕΠΟΙΕ
\end{boustrophedon}
}
(Under normal circumstances, that line would appear as \font[language=grc,family=Gentium Plus]{
ΧΑΙΡΕΔΕΜΟΤΟΔΕΣΕΜΑΠΑΤΕΡΕΣΤΕΣΕΘΑΝΟΝΤΟΣΑΝΦΙΧΑΡΕΣΑΓΑΘΟΝΠΑΙΔΑΟΛΟΦΘΡΟΜΕΝΟΣΦΑΙΔΙΜΟΣΕΠΟΙΕ
}.)
\end{document}
]]
return package
|
fix(packages): Ensure a page switch does not break boustrophedon (#1615)
|
fix(packages): Ensure a page switch does not break boustrophedon (#1615)
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
2ce409bbe610d4bb4a744d63db1d3fbca5f69e74
|
tcpdns.lua
|
tcpdns.lua
|
local socket = require("socket")
local struct = require("struct")
-----------------------------------------
-- LRU cache function
-----------------------------------------
local function LRU(size)
local keys, dict = {}, {}
local function get(key)
local value = dict[key]
if value and keys[1] ~= key then
for i, k in ipairs(keys) do
if k == key then
table.insert(keys, 1, table.remove(keys, i))
break
end
end
end
return value
end
local function add(key, value)
if not get(key) then
if #keys == size then
dict[keys[size]] = nil
table.remove(keys)
end
table.insert(keys, 1, key)
end
dict[key] = value
end
return {add = add, get = get}
end
-----------------------------------------
-- task package
-----------------------------------------
do
local pool = {}
local mutex = {}
local clk = setmetatable({}, {__mode = "k"})
local function go(f, ...)
local co = coroutine.create(f)
coroutine.resume(co, ...)
if coroutine.status(co) ~= "dead" then
local i = 0
repeat i = i + 1 until not pool[i]
pool[i] = co
clk[co] = clk[co] or os.clock()
end
end
local function step()
for i, co in ipairs(pool) do
if os.clock() >= clk[co] then
coroutine.resume(co)
if coroutine.status(co) == "dead" then
pool[i] = nil
end
end
end
return #pool
end
local function sleep(n)
n = n or 0
clk[coroutine.running()] = os.clock() + n
coroutine.yield()
end
local function loop(n)
n = n or 0.001
local sleep = ps.sleep or socket.sleep
while step() ~= 0 do sleep(n) end
end
local function lock(o, n)
while mutex[o] do sleep(n) end
mutex[o] = true
end
local function unlock(o)
mutex[o] = nil
end
task = setmetatable(
{
go = go, sleep = sleep,
step = step, loop = loop,
lock = lock, unlock = unlock
},
{__len = function() return #pool end}
)
end
-----------------------------------------
-- TCP DNS proxy
-----------------------------------------
local cache = LRU(20)
local task = task
local hosts = {
"8.8.8.8", "8.8.4.4",
"208.67.222.222", "208.67.220.220"
}
local function queryDNS(host, data)
local sock = socket.tcp()
sock:settimeout(2)
local recv = ""
if sock:connect(host, 53) then
sock:send(struct.pack(">h", #data)..data)
sock:settimeout(0)
repeat
task.sleep(0.01)
local s, status, partial = sock:receive(1024)
recv = recv..(s or partial)
until #recv > 0 or status == "closed"
sock:close()
end
return recv
end
local function transfer(skt, data, ip, port)
local domain = (data:sub(14, -6):gsub("[^%w]", "."))
print("domain: "..domain, "thread: "..#task)
task.lock(domain, 0.01)
if cache.get(domain) then
skt:sendto(data:sub(1, 2)..cache.get(domain), ip, port)
else
for _, host in ipairs(hosts) do
data = queryDNS(host, data)
if #data > 0 then break end
end
if #data > 0 then
data = data:sub(3)
cache.add(domain, data:sub(3))
skt:sendto(data, ip, port)
end
end
task.unlock(domain)
end
local function udpserver()
local udp = socket.udp()
udp:settimeout(0)
udp:setsockname('*', 53)
while true do
local data, ip, port = udp:receivefrom()
if data then
task.go(transfer, udp, data, ip, port)
end
task.sleep(0)
end
end
task.go(udpserver)
task.loop()
|
local socket = require("socket")
local struct = require("struct")
-----------------------------------------
-- LRU cache function
-----------------------------------------
local function LRU(size)
local keys, dict = {}, {}
local function get(key)
local value = dict[key]
if value and keys[1] ~= key then
for i, k in ipairs(keys) do
if k == key then
table.insert(keys, 1, table.remove(keys, i))
break
end
end
end
return value
end
local function add(key, value)
if not get(key) then
if #keys == size then
dict[keys[size]] = nil
table.remove(keys)
end
table.insert(keys, 1, key)
end
dict[key] = value
end
return {add = add, get = get}
end
-----------------------------------------
-- task package
-----------------------------------------
do
local pool = {}
local mutex = {}
local clk = setmetatable({}, {__mode = "k"})
local function go(f, ...)
local co = coroutine.create(f)
coroutine.resume(co, ...)
if coroutine.status(co) ~= "dead" then
table.insert(pool, co)
clk[co] = clk[co] or os.clock()
end
end
local function step()
for i, co in ipairs(pool) do
if os.clock() >= clk[co] then
coroutine.resume(co)
end
end
local i = 1
while pool[i] do
if coroutine.status(pool[i]) == "dead" then
table.remove(pool, i)
else
i = i + 1
end
end
return #pool
end
local function sleep(n)
n = n or 0
clk[coroutine.running()] = os.clock() + n
coroutine.yield()
end
local function loop(n)
n = n or 0.001
local sleep = ps.sleep or socket.sleep
while step() ~= 0 do sleep(n) end
end
local function lock(o, n)
while mutex[o] do sleep(n) end
mutex[o] = true
end
local function unlock(o)
mutex[o] = nil
end
task = setmetatable(
{
go = go, sleep = sleep,
step = step, loop = loop,
lock = lock, unlock = unlock
},
{__len = function() return #pool end}
)
end
-----------------------------------------
-- TCP DNS proxy
-----------------------------------------
local cache = LRU(20)
local task = task
local hosts = {
"8.8.8.8", "8.8.4.4",
"208.67.222.222", "208.67.220.220"
}
local function queryDNS(host, data)
local sock = socket.tcp()
sock:settimeout(2)
local recv = ""
if sock:connect(host, 53) then
sock:send(struct.pack(">h", #data)..data)
sock:settimeout(0)
repeat
task.sleep(0.01)
local s, status, partial = sock:receive(1024)
recv = recv..(s or partial)
until #recv > 0 or status == "closed"
sock:close()
end
return recv
end
local function transfer(skt, data, ip, port)
local domain = (data:sub(14, -6):gsub("[^%w]", "."))
print("domain: "..domain, "thread: "..#task)
task.lock(domain, 0.01)
if cache.get(domain) then
skt:sendto(data:sub(1, 2)..cache.get(domain), ip, port)
else
for _, host in ipairs(hosts) do
data = queryDNS(host, data)
if #data > 0 then break end
end
if #data > 0 then
data = data:sub(3)
cache.add(domain, data:sub(3))
skt:sendto(data, ip, port)
end
end
task.unlock(domain)
end
local function udpserver()
local udp = socket.udp()
udp:settimeout(0)
udp:setsockname('*', 53)
while true do
local data, ip, port = udp:receivefrom()
if data then
task.go(transfer, udp, data, ip, port)
end
task.sleep(0)
end
end
task.go(udpserver)
task.loop()
|
fix functions go and step
|
fix functions go and step
|
Lua
|
mit
|
uleelx/dnsforwarder
|
7172ac0afb8f2cec5af058975ca2bb887da7e4cc
|
init.lua
|
init.lua
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
local renamer = require("textadept-nim.rename")
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
-- Smart replacer key
local smart_replace_key = "cg"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
nimsuggest.check()
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function remove_type_info(text, position)
if buffer == nil or buffer:get_lexer(true) ~= "nim" then
return
end
local name = text:match("^([^:]+):.*")
if name ~= nil
then
local pos = buffer.current_pos
local to_paste = name:sub(pos-position+1)
buffer:insert_text(pos, to_paste)
buffer:word_right_end()
buffer:auto_c_cancel()
end
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
buffer.auto_c_separator = 35
icons:register()
local shift = 0
local curline = buffer:get_cur_line()
local cur_col = buffer.column[buffer.current_pos] + 1
for i = 1, cur_col do
local shifted_col = cur_col - i
local c = curline:sub(shifted_col, shifted_col)
if c == c:match("([^%w_-])")
then
shift = i - 1
break
end
end
local suggestions = {}
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind])
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
if #suggestions == 1 then
remove_type_info(suggestions[1], buffer.current_pos - shift)
return
end
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, on_file_load)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.AUTO_C_SELECTION, remove_type_info)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
-- Smart replace
[smart_replace_key] = renamer.spawn_dialog,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function ()
return nim_compiler.." "..
sessions.active[sessions.session_of(buffer.filename)].project.backend..
" %p"
end
textadept.run.run_commands.nim = function ()
return nim_compiler.." "..
sessions.active[sessions.session_of(buffer.filename)].project.backend..
" --run %p"
end
end
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
local renamer = require("textadept-nim.rename")
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
-- Smart replacer key
local smart_replace_key = "cg"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
nimsuggest.check()
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function remove_type_info(text, position)
if buffer == nil or buffer:get_lexer(true) ~= "nim" then
return
end
local name = text:match("^([^:]+):.*")
if name ~= nil
then
local pos = buffer.current_pos
local to_paste = name:sub(pos-position+1)
buffer:insert_text(pos, to_paste)
buffer:word_right_end()
buffer:auto_c_cancel()
end
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
buffer.auto_c_separator = 35
icons:register()
local shift = 0
local curline = buffer:get_cur_line()
local cur_col = buffer.column[buffer.current_pos] + 1
for i = 1, cur_col do
local shifted_col = cur_col - i
local c = curline:sub(shifted_col, shifted_col)
if c == c:match("([^%w_-])")
then
shift = i - 1
break
end
end
local suggestions = {}
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind])
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
if #suggestions == 1 then
remove_type_info(suggestions[1], buffer.current_pos - shift)
return
end
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, on_file_load)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.AUTO_C_SELECTION, remove_type_info)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
-- Smart replace
[smart_replace_key] = renamer.spawn_dialog,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of(buffer.filename)].project.backend..
" %p"
end
textadept.run.run_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of[buffer.filename]].project.backend..
" --run %p"
end
end
|
Fixed broken run and compile commands
|
Fixed broken run and compile commands
|
Lua
|
mit
|
xomachine/textadept-nim
|
1802727ae22e590badc102057c044c98b736462e
|
autotest/main.lua
|
autotest/main.lua
|
local skynet = require "skynet"
local test = require "xunit"
local snax = require "snax"
require "skynet.manager"
local max_client = 64
local function start_watchdog()
local watchdog = skynet.newservice("watchdog")
skynet.call(watchdog, "lua", "start", {
port = 8888,
maxclient = max_client,
nodelay = true,
})
assert(watchdog)
skynet.kill(watchdog)
return true
end
local function test_skynet_api()
local service = skynet.uniqueservice("skynetservice")
assert(service)
local service1 = skynet.queryservice("skynetservice")
assert(service1)
skynet.send(service, "lua", "send_func", "MAIN_SEND")
assert("MAIN_CALL" == skynet.call(service, "lua", "call_func", "MAIN_CALL"))
skynet.kill(service1)
skynet.kill(service)
return true
end
local function test_snax_api()
local service = snax.uniqueservice("snaxservice", "hello world")
assert(service)
local service1 = snax.queryservice("snaxservice")
assert(service1 == service)
service.post.hello("MAIN_POST")
assert("MAIN_REQ" == service.req.hello("MAIN_REQ"))
snax.kill(service1)
snax.kill(service)
return true
end
skynet.start(function()
test("start watchdog", start_watchdog)
test("test skynet api", test_skynet_api)
test("test snax api", test_snax_api)
print("Test finished...")
skynet.abort()
os.exit(true)
end)
|
local skynet = require "skynet"
local test = require "xunit"
local snax = require "snax"
require "skynet.manager"
local max_client = 64
local function start_watchdog()
local watchdog = skynet.newservice("watchdog")
skynet.call(watchdog, "lua", "start", {
port = 8888,
maxclient = max_client,
nodelay = true,
})
assert(watchdog)
skynet.kill(watchdog)
return true
end
local function test_skynet_api()
local service = skynet.uniqueservice("skynetservice")
assert(service)
local service1 = skynet.queryservice("skynetservice")
assert(service1)
skynet.send(service, "lua", "send_func", "MAIN_SEND")
assert("MAIN_CALL" == skynet.call(service, "lua", "call_func", "MAIN_CALL"))
skynet.kill(service)
return true
end
local function test_snax_api()
local service = snax.uniqueservice("snaxservice", "hello world")
assert(service)
local service1 = snax.queryservice("snaxservice")
assert(service1 == service)
service.post.hello("MAIN_POST")
assert("MAIN_REQ" == service.req.hello("MAIN_REQ"))
snax.kill(service)
return true
end
skynet.start(function()
test("start watchdog", start_watchdog)
test("test skynet api", test_skynet_api)
test("test snax api", test_snax_api)
print("Test finished...")
skynet.abort()
print("Shit, use os.exit exit!")
os.exit(true)
end)
|
fix auto test
|
fix auto test
|
Lua
|
mit
|
firedtoad/skynet-mingw,firedtoad/skynet-mingw,firedtoad/skynet-mingw,dpull/skynet-mingw,dpull/skynet-mingw
|
521bdd85de5c9873660c2e11c5f06314dc00de5b
|
videolist/node.lua
|
videolist/node.lua
|
gl.setup(1920, 1080)
local playlist
local current_video_idx
util.file_watch("playlist.txt", function(content)
playlist = {}
for filename in string.gmatch(content, "[^\r\n]+") do
playlist[#playlist+1] = filename
end
current_video_idx = 0
print("new playlist")
pp(playlist)
end)
function next_video()
current_video_idx = current_video_idx + 1
if current_video_idx > #playlist then
current_video_idx = 1
end
video = util.videoplayer(playlist[current_video_idx], {loop=false})
end
function node.render()
if not video or not video:next() then
next_video()
end
util.draw_correct(video, 0, 0, WIDTH, HEIGHT)
end
|
gl.setup(1920, 1080)
local playlist, video, current_video_idx
util.file_watch("playlist.txt", function(content)
playlist = {}
for filename in string.gmatch(content, "[^\r\n]+") do
playlist[#playlist+1] = filename
end
current_video_idx = 0
print("new playlist")
pp(playlist)
end)
function next_video()
current_video_idx = current_video_idx + 1
if current_video_idx > #playlist then
current_video_idx = 1
end
if video then
video:dispose()
end
video = util.videoplayer(playlist[current_video_idx], {loop=false})
end
function node.render()
if not video or not video:next() then
next_video()
end
util.draw_correct(video, 0, 0, WIDTH, HEIGHT)
end
|
fixed for gc changes
|
fixed for gc changes
|
Lua
|
bsd-2-clause
|
dividuum/info-beamer-nodes,dividuum/info-beamer-nodes
|
c73ae598bc87b47ac78edc0b402bd5d8971421e2
|
LookupTable.lua
|
LookupTable.lua
|
local THNN = require 'nn.THNN'
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 4
function LookupTable:__init(nIndex, nOutput, paddingValue, maxNorm, normType)
parent.__init(self)
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIndex, nOutput):zero()
self.paddingValue = paddingValue or 0
self.maxNorm = maxNorm or nil
self.normType = normType or nil
self:reset()
end
function LookupTable:backCompatibility()
self._count = self._count or torch.IntTensor()
self._input = self._input or torch.LongTensor()
if not self.shouldScaleGradByFreq then
self.shouldScaleGradByFreq = false
end
end
function LookupTable:accUpdateOnly()
self.gradWeight = nil
return self
end
function LookupTable:setPadding(paddingValue)
self.paddingValue = paddingValue
return self
end
function LookupTable:setMaxNorm(maxNorm)
self.maxNorm = maxNorm
return self
end
function LookupTable:setNormType(normType)
self.normType = normType
return self
end
function LookupTable:scaleGradByFreq()
self.shouldScaleGradByFreq = true
return self
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:normal(0, stdv)
end
function LookupTable:makeInputContiguous(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then
self.copiedInput = true
self._input:resize(input:size()):copy(input)
return self._input
end
self.copiedInput = false
return input
end
function LookupTable:updateOutput(input)
self:backCompatibility()
self:renorm(input)
input = self:makeInputContiguous(input)
if input:dim() == 1 then
self.output:index(self.weight, 1, input)
elseif input:dim() == 2 then
self.output:index(self.weight, 1, input:view(-1))
self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2))
else
error("input must be a vector or matrix")
end
return self.output
end
function LookupTable:updateGradInput(input, gradOutput)
-- the input can be of any type (as in the forward it's
-- converted anyway to LongTensor) thus, need to allocate
-- new memory each time the user changes the input type
if torch.type(self.gradInput) ~= torch.type(input) then
self.gradInput = input.new()
end
if not self.gradInput:isSameSizeAs(input) then
self.gradInput:resizeAs(input):zero()
end
return self.gradInput
end
function LookupTable:accGradParameters(input, gradOutput, scale)
self:backCompatibility()
input = self.copiedInput and self._input or input
if input:dim() == 2 then
input = input:view(-1)
elseif input:dim() ~= 1 then
error("input must be a vector or matrix")
end
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradWeight.THNN.LookupTable_accGradParameters(
input:cdata(),
gradOutput:cdata(),
self.gradWeight:cdata(),
self._count:cdata(),
THNN.optionalTensor(self._sorted),
THNN.optionalTensor(self._indices),
self.shouldScaleGradByFreq or false,
self.paddingValue or 0,
scale or 1
)
end
function LookupTable:renorm(input)
if not self.maxNorm then
return
end
-- copy input into _input, so _input is continous.
-- The copied _input will be modified in the C code.
self._input:resize(input:size()):copy(input)
local row_idx = self._input
if row_idx:dim() == 2 then
row_idx = row_idx:view(-1)
elseif row_idx:dim() ~= 1 then
error("input must be a vector or matrix")
end
-- "row_idx" and "weight" will be modified in the C code
self.weight.THNN.LookupTable_renorm(
row_idx:cdata(),
self.weight:cdata(),
self.maxNorm,
self.normType or 2
)
end
function LookupTable:type(type, tensorCache)
parent.type(self, type, tensorCache)
if type == 'torch.CudaTensor' then
-- CUDA uses _sorted and _indices temporary tensors
self._sorted = self.weight.new()
self._indices = self.weight.new()
self._count = self.weight.new()
self._input = self.weight.new()
else
-- self._count and self._input should only be converted if using Cuda
self._count = torch.IntTensor()
self._input = torch.LongTensor()
end
return self
end
function LookupTable:clearState()
nn.utils.clear(self, '_count', '_input', '_gradOutput')
return parent.clearState(self)
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
local THNN = require 'nn.THNN'
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 4
function LookupTable:__init(nIndex, nOutput, paddingValue, maxNorm, normType)
parent.__init(self)
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIndex, nOutput):zero()
self.paddingValue = paddingValue or 0
self.maxNorm = maxNorm or nil
self.normType = normType or nil
self:reset()
end
function LookupTable:backCompatibility()
self._count = self._count or torch.IntTensor()
self._input = self._input or torch.LongTensor()
if not self.shouldScaleGradByFreq then
self.shouldScaleGradByFreq = false
end
end
function LookupTable:accUpdateOnly()
self.gradWeight = nil
return self
end
function LookupTable:setPadding(paddingValue)
self.paddingValue = paddingValue
return self
end
function LookupTable:setMaxNorm(maxNorm)
self.maxNorm = maxNorm
return self
end
function LookupTable:setNormType(normType)
self.normType = normType
return self
end
function LookupTable:scaleGradByFreq()
self.shouldScaleGradByFreq = true
return self
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:normal(0, stdv)
end
function LookupTable:makeInputContiguous(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then
self.copiedInput = true
self._input:resize(input:size()):copy(input)
return self._input
end
self.copiedInput = false
return input
end
function LookupTable:updateOutput(input)
self:backCompatibility()
self:renorm(input)
input = self:makeInputContiguous(input)
if input:dim() == 1 then
self.output:index(self.weight, 1, input)
elseif input:dim() == 2 then
self.output:index(self.weight, 1, input:view(-1))
self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2))
else
error("input must be a vector or matrix")
end
return self.output
end
function LookupTable:updateGradInput(input, gradOutput)
-- the input can be of any type (as in the forward it's
-- converted anyway to LongTensor) thus, need to allocate
-- new memory each time the user changes the input type
if torch.type(self.gradInput) ~= torch.type(input) then
self.gradInput = input.new()
end
if not self.gradInput:isSameSizeAs(input) then
self.gradInput:resizeAs(input):zero()
end
return self.gradInput
end
function LookupTable:accGradParameters(input, gradOutput, scale)
self:backCompatibility()
input = self.copiedInput and self._input or input
if input:dim() == 2 then
input = input:view(-1)
elseif input:dim() ~= 1 then
error("input must be a vector or matrix")
end
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradWeight.THNN.LookupTable_accGradParameters(
input:cdata(),
gradOutput:cdata(),
self.gradWeight:cdata(),
self._count:cdata(),
THNN.optionalTensor(self._sorted),
THNN.optionalTensor(self._indices),
self.shouldScaleGradByFreq or false,
self.paddingValue or 0,
scale or 1
)
end
function LookupTable:renorm(input)
if not self.maxNorm then
return
end
-- copy input into _input, so _input is continous.
-- The copied _input will be modified in the C code.
self._input:resize(input:size()):copy(input)
local row_idx = self._input
if row_idx:dim() == 2 then
row_idx = row_idx:view(-1)
elseif row_idx:dim() ~= 1 then
error("input must be a vector or matrix")
end
-- "row_idx" and "weight" will be modified in the C code
self.weight.THNN.LookupTable_renorm(
row_idx:cdata(),
self.weight:cdata(),
self.maxNorm,
self.normType or 2
)
end
function LookupTable:type(type, tensorCache)
parent.type(self, type, tensorCache)
if type == 'torch.CudaTensor' then
-- CUDA uses _sorted and _indices temporary tensors
self._sorted = torch.CudaLongTensor.new()
self._indices = torch.CudaLongTensor.new()
self._count = torch.CudaLongTensor.new()
self._input = torch.CudaLongTensor.new()
else
-- self._count and self._input should only be converted if using Cuda
self._count = torch.IntTensor()
self._input = torch.LongTensor()
end
return self
end
function LookupTable:clearState()
nn.utils.clear(self, '_count', '_input', '_gradOutput')
return parent.clearState(self)
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
fix for cutorch index* changes
|
fix for cutorch index* changes
|
Lua
|
bsd-3-clause
|
sagarwaghmare69/nn,colesbury/nn,kmul00/nn,apaszke/nn,eriche2016/nn,joeyhng/nn,nicholas-leonard/nn
|
c503fb873bb48454f44c10eea3642fe7a1c2ae79
|
LookupTable.lua
|
LookupTable.lua
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 4
function LookupTable:__init(nIndex, nOutput)
parent.__init(self)
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIndex, nOutput):zero()
self:reset()
end
function LookupTable:backCompatibility()
self._count = self._count or torch.IntTensor()
self._input = self._input or torch.LongTensor()
if self.shouldScaleGradByFreq == nil then
self.shouldScaleGradByFreq = false
end
end
function LookupTable:accUpdateOnly()
self.gradWeight = nil
return self
end
function LookupTable:scaleGradByFreq()
self.shouldScaleGradByFreq = true
return self
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:normal(0, stdv)
end
function LookupTable:makeInputContiguous(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then
self.copiedInput = true
self._input:resize(input:size()):copy(input)
return self._input
end
self.copiedInput = false
return input
end
function LookupTable:updateOutput(input)
self:backCompatibility()
input = self:makeInputContiguous(input)
if input:dim() == 1 then
self.output:index(self.weight, 1, input)
elseif input:dim() == 2 then
self.output:index(self.weight, 1, input:view(-1))
self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2))
else
error("input must be a vector or matrix")
end
return self.output
end
function LookupTable:accGradParameters(input, gradOutput, scale)
self:backCompatibility()
input = self.copiedInput and self._input or input
if input:dim() == 2 then
input = input:view(-1)
elseif input:dim() ~= 1 then
error("input must be a vector or matrix")
end
self.gradWeight.nn.LookupTable_accGradParameters(self, input, gradOutput, scale)
end
function LookupTable:type(type)
parent.type(self, type)
if type == 'torch.CudaTensor' then
-- CUDA uses _sorted and _indices temporary tensors
self._sorted = self.weight.new()
self._indices = self.weight.new()
else
-- self._count and self._input should only be converted if using Cuda
self._count = torch.IntTensor()
self._input = torch.LongTensor()
end
return self
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 4
function LookupTable:__init(nIndex, nOutput)
parent.__init(self)
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIndex, nOutput):zero()
self:reset()
end
function LookupTable:backCompatibility()
self._count = self._count or torch.IntTensor()
self._input = self._input or torch.LongTensor()
if self.shouldScaleGradByFreq == nil then
self.shouldScaleGradByFreq = false
end
end
function LookupTable:accUpdateOnly()
self.gradWeight = nil
return self
end
function LookupTable:scaleGradByFreq()
self.shouldScaleGradByFreq = true
return self
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:normal(0, stdv)
end
function LookupTable:makeInputContiguous(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then
self.copiedInput = true
self._input:resize(input:size()):copy(input)
return self._input
end
self.copiedInput = false
return input
end
function LookupTable:updateOutput(input)
self:backCompatibility()
input = self:makeInputContiguous(input)
if input:dim() == 1 then
self.output:index(self.weight, 1, input)
elseif input:dim() == 2 then
self.output:index(self.weight, 1, input:view(-1))
self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2))
else
error("input must be a vector or matrix")
end
return self.output
end
function LookupTable:accGradParameters(input, gradOutput, scale)
self:backCompatibility()
input = self.copiedInput and self._input or input
if input:dim() == 2 then
input = input:view(-1)
elseif input:dim() ~= 1 then
error("input must be a vector or matrix")
end
self.gradWeight.nn.LookupTable_accGradParameters(self, input, gradOutput, scale)
end
function LookupTable:type(type)
parent.type(self, type)
if type == 'torch.CudaTensor' then
-- CUDA uses _sorted and _indices temporary tensors
self._sorted = self.weight.new()
self._indices = self.weight.new()
self._count = self.weight.new()
self._input = self.weight.new()
else
-- self._count and self._input should only be converted if using Cuda
self._count = torch.IntTensor()
self._input = torch.LongTensor()
end
return self
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
fixing small bug in :type() of lookup table
|
fixing small bug in :type() of lookup table
|
Lua
|
bsd-3-clause
|
jzbontar/nn,Djabbz/nn,colesbury/nn,nicholas-leonard/nn,forty-2/nn,PraveerSINGH/nn,mlosch/nn,diz-vara/nn,jhjin/nn,clementfarabet/nn,xianjiec/nn,eulerreich/nn,zhangxiangxiao/nn,abeschneider/nn,kmul00/nn,apaszke/nn,hughperkins/nn,Jeffyrao/nn,PierrotLC/nn,sagarwaghmare69/nn,sbodenstein/nn,caldweln/nn,jonathantompson/nn,vgire/nn,douwekiela/nn,rotmanmi/nn,zchengquan/nn,EnjoyHacking/nn,witgo/nn,aaiijmrtt/nn,Aysegul/nn,joeyhng/nn,noa/nn,Moodstocks/nn,LinusU/nn,ominux/nn,lvdmaaten/nn,lukasc-ch/nn,ivendrov/nn,bartvm/nn,davidBelanger/nn,elbamos/nn,eriche2016/nn,andreaskoepf/nn,adamlerer/nn,GregSatre/nn
|
60160151087bf904b5e0771c1b66677fdb881eec
|
lib/gettext.lua
|
lib/gettext.lua
|
#!/usr/bin/env lua
-----------------------------------------------------------
-- load an mo file and return a lua table
-- @param mo_file name of the file to load
-- @return table on success
-- @return nil,string on failure
-- @copyright J.Jorgen von Bargen
-- @licence I provide this as public domain
-- @see http://www.gnu.org/software/hello/manual/gettext/MO-Files.html
-----------------------------------------------------------
function load_mo_file(mo_file)
--------------------------------
-- open file and read data
--------------------------------
local fd,err=io.open(mo_file,"rb")
if not fd then return nil,err end
local mo_data=fd:read("*all")
fd:close()
--------------------------------
-- precache some functions
--------------------------------
local byte=string.byte
local sub=string.sub
--------------------------------
-- check format
--------------------------------
local peek_long --localize
local magic=sub(mo_data,1,4)
-- intel magic 0xde120495
if magic=="\222\018\004\149" then
peek_long=function(offs)
local a,b,c,d=byte(mo_data,offs+1,offs+4)
return ((d*256+c)*256+b)*256+a
end
-- motorola magic = 0x950412de
elseif magic=="\149\004\018\222" then
peek_long=function(offs)
local a,b,c,d=byte(mo_data,offs+1,offs+4)
return ((a*256+b)*256+c)*256+d
end
else
return nil,"no valid mo-file"
end
--------------------------------
-- version
--------------------------------
local V=peek_long(4)
if V~=0 then
return nul,"unsupported version"
end
------------------------------
-- get number of offsets of table
------------------------------
local N,O,T=peek_long(8),peek_long(12),peek_long(16)
------------------------------
-- traverse and get strings
------------------------------
local hash={}
for nstr=1,N do
local ol,oo=peek_long(O),peek_long(O+4) O=O+8
local tl,to=peek_long(T),peek_long(T+4) T=T+8
hash[sub(mo_data,oo+1,oo+ol)]=sub(mo_data,to+1,to+tl)
end
return function(text)
return hash[text] or text
end
-- return hash -- return table
end
--[[ EXPLICATIONS / HOWTO
usage:
local mo_data=assert(load_mo_file("appl.mo"))
print(mo_data["again"])
-- nochmal
print(mo_data["nixda"])
-- nil
You could also change "return hash" to
return function(text)
return hash[text] or text
end
then you'll get a kind of gettext function
local gettext=assert(load_mo_file("appl.mo"))
print(gettext"again")
-- nochmal
print(gettext"nixda")
-- nixda
with a slight modification this will be ready-to-use for the xgettext tool:
_=assert(load_mo_file("appl.mo"))
print(_("again"))
print(_("nixda"))
]]--
|
#!/usr/bin/env lua
-----------------------------------------------------------
-- load an mo file and return a lua table
-- @param mo_file name of the file to load
-- @return table on success
-- @return nil,string on failure
-- @copyright J.Jorgen von Bargen
-- @licence I provide this as public domain
-- @see http://www.gnu.org/software/hello/manual/gettext/MO-Files.html
-- @see http://lua.2524044.n2.nabble.com/State-of-Lua-and-GNU-gettext-tt4797364.html#a4835939
-----------------------------------------------------------
function load_mo_file(mo_file)
--------------------------------
-- open file and read data
--------------------------------
local fd,err=io.open(mo_file,"rb")
if not fd then return nil,err end
local mo_data=fd:read("*all")
fd:close()
--------------------------------
-- precache some functions
--------------------------------
local byte=string.byte
local sub=string.sub
--------------------------------
-- check format
--------------------------------
local peek_long --localize
local magic=sub(mo_data,1,4)
-- intel magic 0xde120495
if magic=="\222\018\004\149" then
peek_long=function(offs)
local a,b,c,d=byte(mo_data,offs+1,offs+4)
return ((d*256+c)*256+b)*256+a
end
-- motorola magic = 0x950412de
elseif magic=="\149\004\018\222" then
peek_long=function(offs)
local a,b,c,d=byte(mo_data,offs+1,offs+4)
return ((a*256+b)*256+c)*256+d
end
else
return nil,"no valid mo-file"
end
--------------------------------
-- version
--------------------------------
local V=peek_long(4)
if V~=0 then
return nul,"unsupported version"
end
------------------------------
-- get number of offsets of table
------------------------------
local N,O,T=peek_long(8),peek_long(12),peek_long(16)
------------------------------
-- traverse and get strings
------------------------------
local hash={}
for nstr=1,N do
local ol,oo=peek_long(O),peek_long(O+4) O=O+8
local tl,to=peek_long(T),peek_long(T+4) T=T+8
hash[sub(mo_data,oo+1,oo+ol)]=sub(mo_data,to+1,to+tl)
end
return function(text)
return hash[text] or text
end
end
|
[FIX] Clean up lib/gettext.lua file from useless explanations
|
[FIX] Clean up lib/gettext.lua file from useless explanations
|
Lua
|
agpl-3.0
|
blankoworld/makefly,blankoworld/makefly,blankoworld/makefly
|
1852e1858f3a112e7d68ab84e9302a47ae6ab0d1
|
scripts/format.lua
|
scripts/format.lua
|
-- Get the Gerrit base URL from the given change URL.
local function get_gerrit_base_url(change_url)
return string.sub(change_url, 1, #change_url - string.find(string.reverse(change_url), "/"))
end
-- Get a URL for a Gerrit query.
local function get_query_url(base_url, query, ...)
return string.format("%s/q/%s", base_url, string.format(query, ...))
end
-- Format a link.
local function format_link(text, target)
return string.format("[%s](%s)", text, target)
end
-- Format a link to a Gerrit query.
local function format_query_link(base_url, text, query, ...)
return format_link(text, get_query_url(base_url, query, ...))
end
-- Format a link to a user.
local function format_user(base_url, user, role)
return format_query_link(
base_url,
user.name or user.email,
"%s:%s+status:open",
role, user.email
)
end
-- Format a change's subject.
local function format_change_subject(change)
return format_link(change.subject, change.url)
end
-- Format a change's project.
local function format_change_project(base_url, change)
local result = format_query_link(
base_url,
change.project,
"project:%s+status:open",
change.project
)
if change.branch ~= "master" then
result = result .. ", branch:" .. change.branch
end
if change.topic then
result = result .. ", topic:" .. format_query_link(
base_url,
change.topic,
"topic:%s+status:open",
change.topic
)
end
return result
end
local APPROVAL_ICONS = {
["WaitForVerification"] = {[-1] = "⏳"},
["Code-Review"] = {[-2] = "👎", [-1] = "🤷", [1] = "👌", [2] = "👍"},
["Verified"] = {[-1] = "❌", [1] = "✔"},
-- fallback
["*"] = {[-2] = "👎", [-1] = "🙅", [1] = "🙆", [2] = "👍"},
}
local function get_approval_icon(type, value, old_value)
if value == 0 then
if old_value ~= 0 then
return "📝"
else
return nil
end
end
type_icons = APPROVAL_ICONS[type] or APPROVAL_ICONS["*"]
return type_icons[value]
end
local function format_approval(approval)
local approval_value = tonumber(approval.value)
local old_approval_value = tonumber(approval.old_value or "0")
local icon = get_approval_icon(approval.type, approval_value, old_approval_value)
local sign = ""
if approval_value > 0 then
sign = "+"
end
if icon then
icon = icon .. " "
else
icon = ""
end
return string.format("%s%s%s (%s)", icon, sign, approval_value, approval.type)
end
-- return an iterator over the lines in the given string
local function lines_iter(s)
return string.gmatch(s, "[^\r\n]+")
end
local function format_comment(comment, is_human)
local lines = {}
for line in lines_iter(comment) do
if is_human and not line:match "^Patch Set" and not line:match "%(%d+ comments?%)" then
table.insert(lines, "> " .. line)
elseif string.match(line, "FAILURE") then
table.insert(lines, "> " .. line)
end
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n")
end
end
local function format_inline_comment(base_url, change, patchset, comment)
local lines = {}
for line in lines_iter(comment.message) do
if #lines == 0 then
local url = string.format(
"%s/#/c/%s/%s/%s@%s",
base_url,
change.number,
patchset.number,
comment.file,
comment.line
)
table.insert(
lines,
string.format(
"> [Line %s](%s) by %s: %s",
comment.line,
url,
format_user(base_url, comment.reviewer, "reviewer"),
line
)
)
else
table.insert(lines, "> " .. line)
end
end
return table.concat(lines, "\n")
end
local function format_inline_comments(base_url, change, patchset)
local lines = {}
local comments = patchset.comments or {}
table.sort(comments, function (c1, c2) return c1.file < c2.file end)
local file
for _i, comment in ipairs(comments) do
if comment.file ~= file then
file = comment.file
table.insert(lines, string.format("`%s`", file))
end
table.insert(lines, format_inline_comment(base_url, change, patchset, comment))
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n") .. "\n"
end
end
-- Filter and format messages
-- return nil to filter the message
function format_comment_added(event, is_human)
local change = event.change
local patchset = event.patchSet
local base_url = get_gerrit_base_url(change.url)
local msg = format_change_subject(change) .. " (" .. format_change_project(base_url, change) .. ")"
local formatted_approvals = {}
for _i, approval in ipairs(event.approvals) do
local formatted_approval = format_approval(approval)
if formatted_approval then
table.insert(formatted_approvals, formatted_approval)
end
end
if #formatted_approvals > 0 then
msg = msg .. " " .. table.concat(formatted_approvals, ", ")
elseif not (is_human and patchset.comments and #patchset.comments > 0) then
-- TODO: messages without approvals should still be formatted since they
-- can be comment responses. This should be handled at a higher level.
-- Keep this here for now to prevent spamming.
return
end
msg = msg .. " from " .. format_user(base_url, event.author, "reviewer")
msg = msg .. (format_comment(event.comment, is_human) or "")
msg = msg .. (format_inline_comments(base_url, change, patchset) or "")
return msg
end
function format_reviewer_added(event)
local change = event.change
local base_url = get_gerrit_base_url(change.url)
return string.format(
"%s (%s) by %s 👓 Added as reviewer",
format_change_subject(change),
format_change_project(base_url, change),
format_user(base_url, change.owner, "owner")
)
end
|
-- Get the Gerrit base URL from the given change URL.
local function get_gerrit_base_url(change_url)
return string.sub(change_url, 1, #change_url - string.find(string.reverse(change_url), "/"))
end
-- Get a URL for a Gerrit query.
local function get_query_url(base_url, query, ...)
return string.format("%s/q/%s", base_url, string.format(query, ...))
end
-- Format a link.
local function format_link(text, target)
return string.format("[%s](%s)", text, target)
end
-- Format a link to a Gerrit query.
local function format_query_link(base_url, text, query, ...)
return format_link(text, get_query_url(base_url, query, ...))
end
-- Format a link to a user.
local function format_user(base_url, user, role)
return format_query_link(
base_url,
user.name or user.email,
"%s:%s+status:open",
role, user.email
)
end
-- Format a change's subject.
local function format_change_subject(change)
return format_link(change.subject, change.url)
end
-- Format a change's project.
local function format_change_project(base_url, change)
local result = format_query_link(
base_url,
change.project,
"project:%s+status:open",
change.project
)
if change.branch ~= "master" then
result = result .. ", branch:" .. change.branch
end
if change.topic then
result = result .. ", topic:" .. format_query_link(
base_url,
change.topic,
"topic:%s+status:open",
change.topic
)
end
return result
end
local APPROVAL_ICONS = {
["WaitForVerification"] = {[-1] = "⏳"},
["Code-Review"] = {[-2] = "👎", [-1] = "🤷", [1] = "👌", [2] = "👍"},
["Verified"] = {[-1] = "❌", [1] = "✔"},
-- fallback
["*"] = {[-2] = "👎", [-1] = "🙅", [1] = "🙆", [2] = "👍"},
}
local function get_approval_icon(type, value, old_value)
if value == 0 then
if old_value ~= 0 then
return "📝"
else
return nil
end
end
type_icons = APPROVAL_ICONS[type] or APPROVAL_ICONS["*"]
return type_icons[value]
end
local function format_approval(approval)
local approval_value = tonumber(approval.value) or 0
local old_approval_value = tonumber(approval.oldValue) or 0
if old_approval_value == approval_value then
return nil
end
local icon = get_approval_icon(approval.type, approval_value, old_approval_value)
local sign = ""
if approval_value > 0 then
sign = "+"
end
if icon then
icon = icon .. " "
else
icon = ""
end
return string.format("%s%s%s (%s)", icon, sign, approval_value, approval.type)
end
-- return an iterator over the lines in the given string
local function lines_iter(s)
return string.gmatch(s, "[^\r\n]+")
end
local function format_comment(comment, is_human)
local lines = {}
for line in lines_iter(comment) do
if is_human and not line:match "^Patch Set" and not line:match "%(%d+ comments?%)" then
table.insert(lines, "> " .. line)
elseif string.match(line, "FAILURE") then
table.insert(lines, "> " .. line)
end
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n")
end
end
local function format_inline_comment(base_url, change, patchset, comment)
local lines = {}
for line in lines_iter(comment.message) do
if #lines == 0 then
local url = string.format(
"%s/#/c/%s/%s/%s@%s",
base_url,
change.number,
patchset.number,
comment.file,
comment.line
)
table.insert(
lines,
string.format(
"> [Line %s](%s) by %s: %s",
comment.line,
url,
format_user(base_url, comment.reviewer, "reviewer"),
line
)
)
else
table.insert(lines, "> " .. line)
end
end
return table.concat(lines, "\n")
end
local function format_inline_comments(base_url, change, patchset)
local lines = {}
local comments = patchset.comments or {}
table.sort(comments, function (c1, c2) return c1.file < c2.file end)
local file
for _i, comment in ipairs(comments) do
if comment.file ~= file then
file = comment.file
table.insert(lines, string.format("`%s`", file))
end
table.insert(lines, format_inline_comment(base_url, change, patchset, comment))
end
if #lines > 0 then
return "\n\n" .. table.concat(lines, "\n\n") .. "\n"
end
end
-- Filter and format messages
-- return nil to filter the message
function format_comment_added(event, is_human)
local change = event.change
local patchset = event.patchSet
local base_url = get_gerrit_base_url(change.url)
local msg = format_change_subject(change) .. " (" .. format_change_project(base_url, change) .. ")"
local formatted_approvals = {}
table.sort(event.approvals, function(a1, a2) return a1.type < a2.type end)
for _i, approval in ipairs(event.approvals) do
local formatted_approval = format_approval(approval)
if formatted_approval then
table.insert(formatted_approvals, formatted_approval)
end
end
if #formatted_approvals > 0 then
msg = msg .. " " .. table.concat(formatted_approvals, ", ")
elseif not (is_human and patchset.comments and #patchset.comments > 0) then
-- TODO: messages without approvals should still be formatted since they
-- can be comment responses. This should be handled at a higher level.
-- Keep this here for now to prevent spamming.
return
end
msg = msg .. " from " .. format_user(base_url, event.author, "reviewer")
msg = msg .. (format_comment(event.comment, is_human) or "")
msg = msg .. (format_inline_comments(base_url, change, patchset) or "")
return msg
end
function format_reviewer_added(event)
local change = event.change
local base_url = get_gerrit_base_url(change.url)
return string.format(
"%s (%s) by %s 👓 Added as reviewer",
format_change_subject(change),
format_change_project(base_url, change),
format_user(base_url, change.owner, "owner")
)
end
|
improve approvals formatting
|
improve approvals formatting
* fix handling old values
* don't show labels that didn't change
* sort labels by type
|
Lua
|
apache-2.0
|
boxdot/gerritbot-rs,boxdot/gerritbot-rs,boxdot/gerritbot-rs
|
ec2381c621f6f96da18172e34207d64c4330d871
|
script/gift.lua
|
script/gift.lua
|
local GiftPower = {
[1001] = 10,
[1003] = 80,
[1009] = 800,
[1010] = 2500,
[1012] = 1100,
[1013] = 10,
[1014] = 80,
[1015] = 80,
}
local SN = 0
GiftMgr = {}
GiftMgr.orderid2req = {}
function GiftMgr:new(sid, presenters)
self.__index = self
local ins = setmetatable({}, self)
ins.sid = sid
ins.presenters = presenters
ins.powers = {} -- {uid=power}
ins.camps = {{}, {}} -- {camp_a_powers, camp_b_powers}
ins.options = {}
ins.polls = {0, 0, 0, 0}
ins.polled_players = {}
return ins
end
-- req -- [to_uid, gift.id, gift.count]
function GiftMgr:regGiftOrder(from_uid, req)
if req.to_uid == 0 then return "", 0, "" end
local t, sn = os.date("%Y%m%d%H%M%S"), GoGetSn()
local to_md5_args = { APPID, from_uid, req.to_uid, req.gift.id,
req.gift.count, sn, self.sid, SRVID,
t, AUTH_KEY }
local to_md5 = string.format("%s%s%s%s%s%s%s%s%s%s", unpack(to_md5_args))
to_md5_args[10] = GoMd5(to_md5)
local post_string = string.format(
"appid=%s&fromuid=%s&touid=%s&giftid=%s&giftcount=%s&sn=%s&ch=%s&srvid=%s&time=%s&verify=%s",
unpack(to_md5_args))
local ss = GoPost(GIFT_URL, post_string)
local op, orderid, token = self:checkPostRet(ss)
if orderid ~= "" then
self.orderid2req[orderid] = req
end
return token, sn, orderid
end
function GiftMgr:checkPostRet(ss)
local ret = parseUrlArg(ss)
return ret["op_ret"] or "", ret["orderid"] or "", ret["token"] or ""
end
function GiftMgr:whichPresenter(uid)
if self.presenters[1].uid == uid then
return 1
elseif self.presenters[2].uid == uid then
return 2
end
return nil
end
function GiftMgr:increasePower(uid, touid, gid, gcount)
print("increasePower")
local p = GiftPower[gid] * gcount
local cur_p = self.powers[uid] or 0
self.powers[uid] = p + cur_p
local o = self:whichPresenter(touid)
if not o then return end
cur_p = self.camps[o].uid or 0
self.camps[o][uid] = cur_p + p
end
function GiftMgr:poll(player, idx)
if self.polled_players[player.uid] or idx > 4 or idx < 1 then
return "FL"
end
self.polled_players[player.uid] = idx
local p = self.powers[player.uid] or 1
self.polls[idx] = self.polls[idx] + p
self.powers[player.uid] = 0
return "OK"
end
function GiftMgr:sortPower(to_sort, top_n)
local sorted = {}
for k, v in pairs(to_sort) do
table.insert(sorted, {k, v})
end
table.sort(sorted, function(a, b) return a[2] > b[2] end)
local ret = {}
for i, v in ipairs(sorted) do
table.insert(ret, {user={uid=v[1]}, s=v[2]})
if i >= top_n then break end
end
return ret
end
function GiftMgr:top3()
return self:sortPower(self.powers, 3)
end
function GiftMgr:vips()
return self:sortPower(self.camps[1], 2),
self:sortPower(self.camps[2], 2)
end
function GiftMgr:getPollResult()
local ret = 1
if self.polls[1] == self.polls[2] and
self.polls[2] == self.polls[3] and
self.polls[3] == self.polls[4] then
ret = 4
else
for i=2, 4 do
if self.polls[i] > ret then
ret = i
end
end
end
return self.options[ret]
end
-- cls methond
function GiftMgr.finishGift(uid, orderid)
print("finishGift", uid, orderid)
local t = os.date("%Y%m%d%H%M%S")
local to_md5_args = { APPID, uid, orderid, SRVID, t, AUTH_KEY }
local to_md5 = string.format("%s%s%s%s%s%s", unpack(to_md5_args))
to_md5_args[#to_md5_args] = GoMd5(to_md5)
local post_string = string.format(
"appid=%s&uid=%s&orderid=%s&srvid=%s&time=%s&verify=%s",
unpack(to_md5_args))
local ss = GoPost(FINISH_GIFT_URL, post_string)
print("finish order ret", ss)
end
|
local GiftPower = {
[1001] = 10,
[1003] = 80,
[1009] = 800,
[1010] = 2500,
[1012] = 1100,
[1013] = 10,
[1014] = 80,
[1015] = 80,
}
local SN = 0
GiftMgr = {}
GiftMgr.orderid2req = {}
function GiftMgr:new(sid, presenters)
self.__index = self
local ins = setmetatable({}, self)
ins.sid = sid
ins.presenters = presenters
ins.powers = {} -- {uid=power}
ins.camps = {{}, {}} -- {camp_a_powers, camp_b_powers}
ins.options = {}
ins.polls = {0, 0, 0, 0}
ins.polled_players = {}
return ins
end
-- req -- [to_uid, gift.id, gift.count]
function GiftMgr:regGiftOrder(from_uid, req)
if req.to_uid == 0 then return "", 0, "" end
local t, sn = os.date("%Y%m%d%H%M%S"), GoGetSn()
local to_md5_args = { APPID, from_uid, req.to_uid, req.gift.id,
req.gift.count, sn, self.sid, SRVID,
t, AUTH_KEY }
local to_md5 = string.format("%s%s%s%s%s%s%s%s%s%s", unpack(to_md5_args))
to_md5_args[10] = GoMd5(to_md5)
local post_string = string.format(
"appid=%s&fromuid=%s&touid=%s&giftid=%s&giftcount=%s&sn=%s&ch=%s&srvid=%s&time=%s&verify=%s",
unpack(to_md5_args))
local ss = GoPost(GIFT_URL, post_string)
local op, orderid, token = self:checkPostRet(ss)
if orderid ~= "" then
self.orderid2req[orderid] = req
end
return token, sn, orderid
end
function GiftMgr:checkPostRet(ss)
local ret = parseUrlArg(ss)
return ret["op_ret"] or "", ret["orderid"] or "", ret["token"] or ""
end
function GiftMgr:whichPresenter(uid)
if self.presenters[1].uid == uid then
return 1
elseif self.presenters[2].uid == uid then
return 2
end
return nil
end
function GiftMgr:increasePower(uid, touid, gid, gcount)
print("increasePower")
local p = GiftPower[gid] * gcount
local cur_p = self.powers[uid] or 0
self.powers[uid] = p + cur_p
local o = self:whichPresenter(touid)
if not o then return end
cur_p = self.camps[o].uid or 0
self.camps[o][uid] = cur_p + p
end
function GiftMgr:poll(player, idx)
if self.polled_players[player.uid] or idx > 4 or idx < 1 then
return "FL"
end
self.polled_players[player.uid] = idx
local p = self.powers[player.uid] or 1
self.polls[idx] = self.polls[idx] + p
self.powers[player.uid] = 0
return "OK"
end
function GiftMgr:sortPower(to_sort, top_n)
local sorted = {}
for k, v in pairs(to_sort) do
table.insert(sorted, {k, v})
end
table.sort(sorted, function(a, b) return a[2] > b[2] end)
local ret = {}
for i, v in ipairs(sorted) do
table.insert(ret, {user={uid=v[1]}, s=v[2]})
if i >= top_n then break end
end
return ret
end
function GiftMgr:top3()
return self:sortPower(self.powers, 3)
end
function GiftMgr:vips()
return self:sortPower(self.camps[1], 2),
self:sortPower(self.camps[2], 2)
end
function GiftMgr:getPollResult()
if self.polls[1] == self.polls[2] and
self.polls[2] == self.polls[3] and
self.polls[3] == self.polls[4] then
return self.options[4]
end
local idx, poll = 1, self.polls[1]
for i=2, 4 do
if self.polls[i] > poll then
idx, poll = i, self.polls[i]
end
end
return self.options[idx]
end
-- cls methond
function GiftMgr.finishGift(uid, orderid)
print("finishGift", uid, orderid)
local t = os.date("%Y%m%d%H%M%S")
local to_md5_args = { APPID, uid, orderid, SRVID, t, AUTH_KEY }
local to_md5 = string.format("%s%s%s%s%s%s", unpack(to_md5_args))
to_md5_args[#to_md5_args] = GoMd5(to_md5)
local post_string = string.format(
"appid=%s&uid=%s&orderid=%s&srvid=%s&time=%s&verify=%s",
unpack(to_md5_args))
local ss = GoPost(FINISH_GIFT_URL, post_string)
print("finish order ret", ss)
end
|
fix getPollResult bug
|
fix getPollResult bug
|
Lua
|
apache-2.0
|
lsaint/act,lsaint/act,lsaint/act
|
7efaa10e079bbf11492c4f3cd6fb0988267808cb
|
rbm.lua
|
rbm.lua
|
require('nn')
require('pl')
require('torch')
require('rbm-util')
require('rbm-regularization')
require('rbm-grads')
require ('socket') -- for timing
function rbmtrain(rbm,x_train,y_train,x_val,y_val,x_semisup)
-- train RBM
-- Reset gradient accums
-- Print rbm
--print(x_train)
--print(y_train)
--print(x_val)
--print(y_val)
--print(x_semisup)
printRBM(rbm,x_train,x_val,x_semisup)
--x = torch.rand(10,5)
--x_mean = torch.mm(torch.ones(x:size(1),1),x:mean(1))
--x = torch.add(x,-x_mean)
local x_tr,y_tr,x_semi, total_time, epoch_time,acc_train
local best_val_err = 1/0
local patience = rbm.patience
total_time = socket.gettime()
-- extend error tensors if resuming training
if rbm.err_train:size(1) <= rbm.numepochs then
rbm.err_recon_train = extendTensor(rbm,rbm.err_trecon_train,rbm.numepochs)
rbm.err_train = extendTensor(rbm,rbm.err_train,rbm.numepochs)
rbm.err_val = extendTensor(rbm,rbm.err_val,rbm.numepochs)
print("extend RBM:",rbm)
end
for epoch = rbm.currentepoch, rbm.numepochs do
epoch_time = socket.gettime()
rbm.cur_err = torch.zeros(1)
rbm.currentepoch = epoch
for i = 1, x_train:size(1) do -- iter over samples
x_tr,y_tr,x_semi = getsamples(rbm,x_train,y_train,x_semisup,i)
regularization.applydropoutordropconnect(rbm,i) -- cp org weights, drops weights if enabled
grads.calculategrads(rbm,x_tr,y_tr,x_semi) -- calculates dW, dU, db, dc and dd
regularization.applyregularization(rbm) -- regularizes dW, dU, db, dc and dd
updategradsandmomentum(rbm)
-- update vW, vU, vb, vc and vd, formulae: vx = vX*mom + dX
restoreorgweights(rbm,i) -- restore weights from before dropping
updateweights(rbm) -- updates W,U,b,c and d, formulae: X = X + vX
if (i % 5000) == 0 then
io.write(".")
io.flush()
end
-- Force garbagecollector to collect. Reduces memory with atleast factor of 3.
if (i % 100) == 0 then
collectgarbage()
end
end -- samples loop
epoch_time = socket.gettime() - epoch_time
rbm.err_recon_train[epoch] = rbm.cur_err:div(rbm.n_samples)
--timer = torch.Timer()
err_train = 1-accuracy(rbm,x_train,y_train)
rbm.err_train[epoch] = err_train
--print(timer:time().real)
if x_val and y_val then
err_val = 1-accuracy(rbm,x_val,y_val)
rbm.err_val[epoch] = err_val
if err_val < best_val_err then
best_val_err = err_val
patience = rbm.patience
saverbm(rbm.tempfile,rbm) -- save current best
best_rbm = cprbm(rbm) -- save best weights
best = '***'
else
patience = patience - 1
best = ''
end
end
print(string.format("%i/%i -LR: %f, MOM %f - Recon err: %4.1f err TR: %f err VAL: %f time: %f Patience %i %s", epoch, rbm.numepochs, rbm.learningrate,rbm.momentum, rbm.cur_err[1],err_train,err_val or 1/0,epoch_time, patience,best))
if patience < 0 then -- Stop training
-- Cp weights from best_rbm
rbm.W = best_rbm.W:clone()
rbm.U = best_rbm.U:clone()
rbm.b = best_rbm.b:clone()
rbm.c = best_rbm.c:clone()
rbm.d = best_rbm.d:clone()
break
end
end
total_time = socket.gettime() - total_time
print("Mean epoch time:", total_time / rbm.numepochs)
return(rbm)
end
function getsamples(rbm,x_train,y_train,x_semisup,i_tr)
local x_tr, y_tr
x_tr = x_train[i_tr]:resize(1,x_train:size(2))
y_tr = y_train[i_tr]:resize(1,y_train:size(2))
if rbm.beta > 0 then
i_semi = (i_tr-1) % x_semisup:size(1) +1;
x_semi = x_semisup[i_tr]:resize(1,x_semisup:size(2))
end
return x_tr,y_tr,x_semi
end
function updategradsandmomentum(rbm)
-- multiply updates by learningrate
rbm.dW:mul(rbm.learningrate)
rbm.dU:mul(rbm.learningrate)
rbm.db:mul(rbm.learningrate)
rbm.dc:mul(rbm.learningrate)
rbm.dd:mul(rbm.learningrate)
-- If momentum is zero this will be zero
--if momentum > 0 then
if rbm.momentum > 0 then
rbm.vW:mul(rbm.momentum)
rbm.vU:mul(rbm.momentum)
rbm.vb:mul(rbm.momentum)
rbm.vc:mul(rbm.momentum)
rbm.vd:mul(rbm.momentum)
else
rbm.vW:fill(0)
rbm.vU:fill(0)
rbm.vb:fill(0)
rbm.vc:fill(0)
rbm.vd:fill(0)
end
-- Add current update to momentum
rbm.vW:add(rbm.dW)
rbm.vU:add(rbm.dU)
rbm.vb:add(rbm.db)
rbm.vc:add(rbm.dc)
rbm.vd:add(rbm.dd)
end
function updateweights(rbm)
-- update gradients
rbm.W:add(rbm.vW)
rbm.U:add(rbm.vU)
rbm.b:add(rbm.vb)
rbm.c:add(rbm.vc)
rbm.d:add(rbm.vd)
end
function restoreorgweights(rbm,i)
if rbm.dropconnect > 0 then
-- TODO: not sure if i need to clone here
rbm.W = rbm.W_org:clone();
rbm.U = rbm.U_org:clone();
rbm.c = rbm.c_org:clone();
end
end
function cprbm(rbm)
newrbm = {}
newrbm.W = rbm.W:clone()
newrbm.U = rbm.U:clone()
newrbm.b = rbm.b:clone()
newrbm.c = rbm.c:clone()
newrbm.d = rbm.d:clone()
return(newrbm)
end
-- extend old tensor to
function extendTensor(rbm,oldtensor,newsize,fill)
if fill then fill = fill else fill = -1 end
local newtensor
newtensor = torch.Tensor(newsize):fill(fill)
newtensor[{{1,rbm.currentepoch}}] = oldtensor:clone()
return newtensor
end
|
require('nn')
require('pl')
require('torch')
require('rbm-util')
require('rbm-regularization')
require('rbm-grads')
require ('socket') -- for timing
function rbmtrain(rbm,x_train,y_train,x_val,y_val,x_semisup)
-- train RBM
-- Reset gradient accums
-- Print rbm
--print(x_train)
--print(y_train)
--print(x_val)
--print(y_val)
--print(x_semisup)
printRBM(rbm,x_train,x_val,x_semisup)
--x = torch.rand(10,5)
--x_mean = torch.mm(torch.ones(x:size(1),1),x:mean(1))
--x = torch.add(x,-x_mean)
local x_tr,y_tr,x_semi, total_time, epoch_time,acc_train
local best_val_err = 1/0
local patience = rbm.patience
total_time = socket.gettime()
-- extend error tensors if resuming training
if rbm.err_train:size(1) <= rbm.numepochs then
rbm.err_recon_train = extendTensor(rbm, rbm.err_recon_train,rbm.numepochs)
rbm.err_train = extendTensor(rbm,rbm.err_train,rbm.numepochs)
rbm.err_val = extendTensor(rbm,rbm.err_val,rbm.numepochs)
end
for epoch = rbm.currentepoch, rbm.numepochs do
epoch_time = socket.gettime()
rbm.cur_err = torch.zeros(1)
rbm.currentepoch = epoch
for i = 1, x_train:size(1) do -- iter over samples
x_tr,y_tr,x_semi = getsamples(rbm,x_train,y_train,x_semisup,i)
regularization.applydropoutordropconnect(rbm,i) -- cp org weights, drops weights if enabled
grads.calculategrads(rbm,x_tr,y_tr,x_semi) -- calculates dW, dU, db, dc and dd
regularization.applyregularization(rbm) -- regularizes dW, dU, db, dc and dd
updategradsandmomentum(rbm)
-- update vW, vU, vb, vc and vd, formulae: vx = vX*mom + dX
restoreorgweights(rbm,i) -- restore weights from before dropping
updateweights(rbm) -- updates W,U,b,c and d, formulae: X = X + vX
if (i % 5000) == 0 then
io.write(".")
io.flush()
end
-- Force garbagecollector to collect. Reduces memory with atleast factor of 3.
if (i % 100) == 0 then
collectgarbage()
end
end -- samples loop
epoch_time = socket.gettime() - epoch_time
rbm.err_recon_train[epoch] = rbm.cur_err:div(rbm.n_samples)
--timer = torch.Timer()
err_train = 1-accuracy(rbm,x_train,y_train)
rbm.err_train[epoch] = err_train
--print(timer:time().real)
if x_val and y_val then
err_val = 1-accuracy(rbm,x_val,y_val)
rbm.err_val[epoch] = err_val
if err_val < best_val_err then
best_val_err = err_val
patience = rbm.patience
saverbm(rbm.tempfile,rbm) -- save current best
best_rbm = cprbm(rbm) -- save best weights
best = '***'
else
patience = patience - 1
best = ''
end
end
print(string.format("%i/%i -LR: %f, MOM %f - Recon err: %4.1f err TR: %f err VAL: %f time: %f Patience %i %s", epoch, rbm.numepochs, rbm.learningrate,rbm.momentum, rbm.cur_err[1],err_train,err_val or 1/0,epoch_time, patience,best))
if patience < 0 then -- Stop training
-- Cp weights from best_rbm
rbm.W = best_rbm.W:clone()
rbm.U = best_rbm.U:clone()
rbm.b = best_rbm.b:clone()
rbm.c = best_rbm.c:clone()
rbm.d = best_rbm.d:clone()
break
end
end
total_time = socket.gettime() - total_time
print("Mean epoch time:", total_time / rbm.numepochs)
return(rbm)
end
function getsamples(rbm,x_train,y_train,x_semisup,i_tr)
local x_tr, y_tr
x_tr = x_train[i_tr]:resize(1,x_train:size(2))
y_tr = y_train[i_tr]:resize(1,y_train:size(2))
if rbm.beta > 0 then
i_semi = (i_tr-1) % x_semisup:size(1) +1;
x_semi = x_semisup[i_tr]:resize(1,x_semisup:size(2))
end
return x_tr,y_tr,x_semi
end
function updategradsandmomentum(rbm)
-- multiply updates by learningrate
rbm.dW:mul(rbm.learningrate)
rbm.dU:mul(rbm.learningrate)
rbm.db:mul(rbm.learningrate)
rbm.dc:mul(rbm.learningrate)
rbm.dd:mul(rbm.learningrate)
-- If momentum is zero this will be zero
--if momentum > 0 then
if rbm.momentum > 0 then
rbm.vW:mul(rbm.momentum)
rbm.vU:mul(rbm.momentum)
rbm.vb:mul(rbm.momentum)
rbm.vc:mul(rbm.momentum)
rbm.vd:mul(rbm.momentum)
else
rbm.vW:fill(0)
rbm.vU:fill(0)
rbm.vb:fill(0)
rbm.vc:fill(0)
rbm.vd:fill(0)
end
-- Add current update to momentum
rbm.vW:add(rbm.dW)
rbm.vU:add(rbm.dU)
rbm.vb:add(rbm.db)
rbm.vc:add(rbm.dc)
rbm.vd:add(rbm.dd)
end
function updateweights(rbm)
-- update gradients
rbm.W:add(rbm.vW)
rbm.U:add(rbm.vU)
rbm.b:add(rbm.vb)
rbm.c:add(rbm.vc)
rbm.d:add(rbm.vd)
end
function restoreorgweights(rbm,i)
if rbm.dropconnect > 0 then
-- TODO: not sure if i need to clone here
rbm.W = rbm.W_org:clone();
rbm.U = rbm.U_org:clone();
rbm.c = rbm.c_org:clone();
end
end
function cprbm(rbm)
newrbm = {}
newrbm.W = rbm.W:clone()
newrbm.U = rbm.U:clone()
newrbm.b = rbm.b:clone()
newrbm.c = rbm.c:clone()
newrbm.d = rbm.d:clone()
return(newrbm)
end
-- extend old tensor to
function extendTensor(rbm,oldtensor,newsize,fill)
if fill then fill = fill else fill = -1 end
local newtensor
newtensor = torch.Tensor(newsize):fill(fill)
newtensor[{{1,rbm.currentepoch}}] = oldtensor[{{1,rbm.currentepoch}}]:clone()
return newtensor
end
|
fix extend training error
|
fix extend training error
|
Lua
|
bsd-3-clause
|
skaae/rbm_toolbox_lua,elezar/rbm_toolbox_lua
|
fde6d616428e01e61f4a5ae58bb70021d029606e
|
control.lua
|
control.lua
|
require 'util'
require 'gui'
require 'test'
function print(stuff)
game.players[1].print(stuff)
end
function setup()
global.hoverboard = global.hoverboard or {}
for _, player in pairs(game.players) do
createPlayerMag(player.index)
end
end
function activateEquipment(index)
global.hoverboard[index].inserted = true
UI.initialize(index)
end
function deactivateEquipment(index)
if global.hoverboard[index].inserted == true then
global.hoverboard[index].inserted = false
UI.destroy(index)
end
end
function createPlayerMag(i)
local entity = {
charge = 0,
active = false,
inserted = false
}
global.hoverboard[i] = entity
end
script.on_init(setup)
function getTile()
return game.player.surface.get_tile(game.player.position.x,game.player.position.y)
end
function getArmor(index)
local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1]
return armor
end
function armorCheck(index)
local armor = getArmor(index)
if armor.valid_for_read and armor.has_grid then
return true
end
return false
end
script.on_event(defines.events.on_tick, function(event)
--if global.dead == false then
-- if global.tick == 0 then
-- UI.initialize()
-- global.tick = global.tick + 1
-- end
-- hoverMode()
--end
end)
script.on_event(defines.events.on_player_armor_inventory_changed, function(event)
local index = event.player_index
if armorCheck(index) then
local armor = getArmor(index)
local equipment = armor.grid.equipment
for i, e in ipairs(equipment) do
if e.name == "hoverboard" then
activateEquipment(index)
end
end
else
deactivateEquipment(index)
end
end)
script.on_event(defines.events.on_player_placed_equipment, function(event)
local index = event.player_index
if armorCheck(index) and event.equipment.name == "hoverboard" then
activateEquipment(index)
end
end)
script.on_event(defines.events.on_player_removed_equipment, function(event)
local index = event.player_index
if armorCheck(index) and event.equipment == "hoverboard" then
deactivateEquipment(index)
end
end)
script.on_event(defines.events.on_entity_died, function(event)
if event.entity.name == "player" then
global.dead = true
end
end)
script.on_event(defines.events.on_gui_click,function(event)
local index = event.player_index
local active = global.hoverboard[index].active
if event.element.name == "mode" then
if active == false then
active = true
elseif status == true then
active = false
end
UI.switchMode(active,index)
end
end)
script.on_event(defines.events.on_built_entity,function(event)
if event.created_entity.name == "accelerator" then
game.player.print("beep")
end
end)
function activeHoverMode()
local orientation = game.player.walking_state.direction
if global.charge > 0 then
global.charge = global.charge - 1
game.player.walking_state = {walking = true, direction = orientation}
end
end
function hoverMode()
if global.hoverboard.status == true then
activeHoverMode()
tileCheck()
Ui.updateStatus()
end
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function tileCheck()
local tile = getTile()
local walk = game.player.walking_state.walking
if tile.name == "accelerator" then
if global.charge <= 40 then
global.charge = global.charge + 10
end
elseif tile.name == "down" then
game.player.walking_state = {walking = walk, direction = defines.direction.south}
elseif tile.name == "up" then
game.player.walking_state = {walking = walk, direction = defines.direction.north}
elseif tile.name == "right" then
game.player.walking_state = {walking = walk, direction = defines.direction.east}
elseif tile.name == "left" then
game.player.walking_state = {walking = walk, direction = defines.direction.west}
elseif inboundTile(tile.name) == false then
global.charge = 0
end
end
|
require 'util'
require 'gui'
require 'test'
function print(stuff)
game.players[1].print(stuff)
end
function setup()
global.hoverboard = global.hoverboard or {}
for _, player in pairs(game.players) do
createPlayerMag(player.index)
end
end
function activateEquipment(index)
global.hoverboard[index].inserted = true
UI.initialize(index)
end
function deactivateEquipment(index)
if global.hoverboard[index].inserted == true then
global.hoverboard[index].inserted = false
UI.destroy(index)
end
end
function createPlayerMag(i)
local entity = {
charge = 0,
active = false,
inserted = false
}
global.hoverboard[i] = entity
end
script.on_init(setup)
function getTile()
return game.player.surface.get_tile(game.player.position.x,game.player.position.y)
end
function getArmor(index)
local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1]
return armor
end
function armorCheck(index)
local armor = getArmor(index)
if armor.valid_for_read and armor.has_grid then
return true
end
return false
end
script.on_event(defines.events.on_tick, function(event)
--if global.dead == false then
-- if global.tick == 0 then
-- UI.initialize()
-- global.tick = global.tick + 1
-- end
-- hoverMode()
--end
end)
script.on_event(defines.events.on_player_armor_inventory_changed, function(event)
local index = event.player_index
if armorCheck(index) then
local armor = getArmor(index)
local equipment = armor.grid.equipment
for i, e in ipairs(equipment) do
if e.name == "hoverboard" then
activateEquipment(index)
end
end
else
deactivateEquipment(index)
end
end)
script.on_event(defines.events.on_player_placed_equipment, function(event)
local index = event.player_index
if armorCheck(index) and event.equipment.name == "hoverboard" then
activateEquipment(index)
end
end)
script.on_event(defines.events.on_player_removed_equipment, function(event)
local index = event.player_index
if armorCheck(index) and event.equipment == "hoverboard" then
deactivateEquipment(index)
end
end)
script.on_event(defines.events.on_entity_died, function(event)
if event.entity.name == "player" then
global.dead = true
end
end)
script.on_event(defines.events.on_gui_click,function(event)
local index = event.player_index
local active = global.hoverboard[index].active
if event.element.name == "mode" then
if active == false then
global.hoverboard[index].active = true
elseif active == true then
global.hoverboard[index].active = false
end
UI.switchMode(active,index)
end
end)
script.on_event(defines.events.on_built_entity,function(event)
if event.created_entity.name == "accelerator" then
game.player.print("beep")
end
end)
function activeHoverMode()
local orientation = game.player.walking_state.direction
if global.charge > 0 then
global.charge = global.charge - 1
game.player.walking_state = {walking = true, direction = orientation}
end
end
function hoverMode()
if global.hoverboard.status == true then
activeHoverMode()
tileCheck()
Ui.updateStatus()
end
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function tileCheck()
local tile = getTile()
local walk = game.player.walking_state.walking
if tile.name == "accelerator" then
if global.charge <= 40 then
global.charge = global.charge + 10
end
elseif tile.name == "down" then
game.player.walking_state = {walking = walk, direction = defines.direction.south}
elseif tile.name == "up" then
game.player.walking_state = {walking = walk, direction = defines.direction.north}
elseif tile.name == "right" then
game.player.walking_state = {walking = walk, direction = defines.direction.east}
elseif tile.name == "left" then
game.player.walking_state = {walking = walk, direction = defines.direction.west}
elseif inboundTile(tile.name) == false then
global.charge = 0
end
end
|
fix switching
|
fix switching
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
50d3420705f4d1bb6253a92a8e8df061fc9f6579
|
dotfiles/config/nvim/lua/colorscheme.lua
|
dotfiles/config/nvim/lua/colorscheme.lua
|
local function highlight(hi)
vim.cmd("autocmd ColorScheme * highlight " .. hi)
end
vim.g["nightflyUnderlineMatchParen"] = 1
vim.cmd("colorscheme nightfly")
highlight("CustomModifiedFlag guibg=Red guifg=White")
highlight("Pmenu ctermfg=0 ctermbg=13 guifg=fg guibg=#1d3b53")
-- For focused windows, use the 'default' background color (from tmux). This
-- means the current Vim window will be highlighted only if the tmux pane that
-- vim is running in is also currently active.
highlight("Normal guibg=NONE")
-- Unfocused background color duplicated in tmux config
highlight("NormalNC guibg=#000a13")
|
vim.g["nightflyUnderlineMatchParen"] = 1
vim.cmd("colorscheme nightfly")
vim.api.nvim_set_hl(0, "CustomModifiedFlag", {bg="Red", fg="White"})
vim.api.nvim_set_hl(0, "Pmenu", {fg=0, bg=13, fg="fg", bg="#1d3b53"})
-- For focused windows, use the 'default' background color (from tmux). This
-- means the current Vim window will be highlighted only if the tmux pane that
-- vim is running in is also currently active.
vim.api.nvim_set_hl(0, "Normal", {bg="NONE"})
-- Unfocused background color duplicated in tmux config
vim.api.nvim_set_hl(0, "NormalNC", {bg="#000a13"})
|
Fix custom neovim colorscheme overrides
|
Fix custom neovim colorscheme overrides
|
Lua
|
mit
|
davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles
|
3bb2ed5bffc96f709c666897eb17931c17a633f1
|
tweak/scripts/EXAMPLE.lua
|
tweak/scripts/EXAMPLE.lua
|
--actual documentation is at the bottom of the file
--i thought i'd start with a heavily commented example first
--declare your own constants and functions here
function abs(x) --> absolute value convenience function
if x < 0 then
return -x
else
return x
end
end
--this is the function that gets called when the screen moves
--remember to "return" it at the end
--"view" is the icon page you will be manipulating (aka a view)
--"offset" is the x-offset of the current page to the center of the screen
--"width" and "height" are the width and height of the screen
return function(view, offset, width, height)
local percent = offset/width
view:rotate(percent*math.pi/3, 1, 0, 0) --> this will tilt the page slightly backward
local first_icon = view[1]
first_icon:rotate(percent*math.pi*2) --> this will spin the first icon in the page
local i = 0
while true do --> loop through all of the icons
i = i + 1
local icon = view[i]
if icon == nil then --> if there is no view
break --break out of the loop
else
icon.alpha = 1 - abs(percent) --> set the opacity with respect to how far away it is from the center of the screen
-- this calls the absolute value function we declared earlier
end
end
end
--errors are stored in /var/mobile/Library/Logs/Cylinder/errors.log
--[[
--available functions:
dofile("file.lua") --> runs the lua file like a function and returns whatever it returns
view:rotate(angle, pitch, yaw, roll) --> rotate the view by angle (in radians).
-- typically pitch, yaw, roll are 1, -1 or 0.
-- pitch is tilt forward or back (3D)
-- yaw is tilt left or right (3D)
-- roll is the flat one.
view:rotate(angle) --> equivalent of view:rotate(angle, 0, 0, 1)
-- *****WARNING*******
-- DO NOT rotate the pitch or yaw of the page AND its icons. this
-- will make them blur and cause performance loss. roll only is fine.
view:translate(x, y, z) --> this one should be obvious.
-- there is no scale function. the same effect can be achieved
-- using view:translate on the Z axis.
view.alpha = 0 --> completely transparent
view.alpha = 0.5 --> semitransparent
view.alpha = 1 --> completely opaque
-- you can only get the x/y/width/height
-- you can't set them
-- these are useful for tweaks that allow
-- more than 4 icons per row and stuff
-- or tweaks that scale the icons down
-- or ipads
view.x
view.y
view.width
view.height
--builtin lua functions
math.random(1, 100) --> random number between 1 and 100
math.pi --------------> 3.14159265......
math.sin(math.pi/6) --> 0.5
math.cos(math.pi/3) --> 0.5
math.tan(math.pi/4) --> 1
math.rad(180) --------> math.pi
math.deg(math.pi) ----> 180
math.abs(-32) --------> 32
math.floor(2.4328) ---> 2
os.time() ---> number of seconds since January 1st, 1970
print("blah blah blah") -----> writes to /var/mobile/Library/Logs/Cylinder/print.log
-- ....yeah those are some basics,
-- there are a ton more. just google
-- "lua 5.2 standard library" or something
-- and you can see all the functions you can use.
-- i disabled a few dangerous ones like os.exit and
-- os.execute for obvious reasons but most of them are
-- there.
-- *************************
-- **** ADVANCED USERS *****
-- *************************
view.transform --> this is if you want to
-- manipulate the transformation matrix directly.
-- it will return an array like this:
[m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44]
-- and you can edit it however you like.
-- the BASE_TRANSFORM global variable is the
-- equivalent of CATransform3DIdentity in Cocoa.
-- NOTE: you have to set it back again, kinda like
-- a view's frame. i.e.:
local transform = view.transform
transform[12] = -0.002 ---> allow perspective (don't worry i already do this automatically when you rotate)
view.transform = transform
-- more will be added later
]]
|
--actual documentation is at the bottom of the file
--i thought i'd start with a heavily commented example first
--declare your own constants and functions here
function abs(x) --> absolute value convenience function
if x < 0 then
return -x
else
return x
end
end
--this is the function that gets called when the screen moves
--remember to "return" it at the end
--"view" is the icon page you will be manipulating (aka a view)
--"offset" is the x-offset of the current page to the center of the screen
--"width" and "height" are the width and height of the screen
return function(page, offset, screen_width, screen_height)
local percent = offset/page.width
page:rotate(percent*math.pi/3, 1, 0, 0) --> this will tilt the page slightly backward
local first_icon = page[1]
first_icon:rotate(percent*math.pi*2) --> this will spin the first icon in the page
local i = 0
while true do --> loop through all of the icons
i = i + 1
local icon = page[i]
if icon == nil then --> if there is no view
break --break out of the loop
else
icon.alpha = 1 - abs(percent) --> set the opacity with respect to how far away it is from the center of the screen
-- this calls the absolute value function we declared earlier
end
end
end
--errors are stored in /var/mobile/Library/Logs/Cylinder/errors.log
--[[
--available functions:
dofile("file.lua") --> runs the lua file like a function and returns whatever it returns
view:rotate(angle, pitch, yaw, roll) --> rotate the view by angle (in radians).
-- typically pitch, yaw, roll are 1, -1 or 0.
-- pitch is tilt forward or back (3D)
-- yaw is tilt left or right (3D)
-- roll is the flat one.
view:rotate(angle) --> equivalent of view:rotate(angle, 0, 0, 1)
-- *****WARNING*******
-- DO NOT rotate the pitch or yaw of the page AND its icons. this
-- will make them blur and cause performance loss. roll only is fine.
view:translate(x, y, z) --> this one should be obvious.
-- there is no scale function. the same effect can be achieved
-- using view:translate on the Z axis.
view.alpha = 0 --> completely transparent
view.alpha = 0.5 --> semitransparent
view.alpha = 1 --> completely opaque
-- you can only get the x/y/width/height
-- you can't set them
-- these are useful for tweaks that allow
-- more than 4 icons per row and stuff
-- or tweaks that scale the icons down
-- or ipads
view.x
view.y
view.width
view.height
--builtin lua functions
math.random(1, 100) --> random number between 1 and 100
math.pi --------------> 3.14159265......
math.sin(math.pi/6) --> 0.5
math.cos(math.pi/3) --> 0.5
math.tan(math.pi/4) --> 1
math.rad(180) --------> math.pi
math.deg(math.pi) ----> 180
math.abs(-32) --------> 32
math.floor(2.4328) ---> 2
os.time() ---> number of seconds since January 1st, 1970
print("blah blah blah") -----> writes to /var/mobile/Library/Logs/Cylinder/print.log
-- ....yeah those are some basics,
-- there are a ton more. just google
-- "lua 5.2 standard library" or something
-- and you can see all the functions you can use.
-- i disabled a few dangerous ones like os.exit and
-- os.execute for obvious reasons but most of them are
-- there.
-- *************************
-- **** ADVANCED USERS *****
-- *************************
view.transform --> this is if you want to
-- manipulate the transformation matrix directly.
-- it will return an array like this:
[m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44]
-- and you can edit it however you like.
-- the BASE_TRANSFORM global variable is the
-- equivalent of CATransform3DIdentity in Cocoa.
-- NOTE: you have to set it back again, kinda like
-- a view's frame. i.e.:
local transform = view.transform
transform[12] = -0.002 ---> allow perspective (don't worry i already do this automatically when you rotate)
view.transform = transform
-- more will be added later
]]
|
fix example
|
fix example
|
Lua
|
mit
|
rweichler/cylinder,rweichler/cylinder,rweichler/cylinder
|
40cc14d83f868ab80f80984f71e4dddff25a57a2
|
stdlib/game.lua
|
stdlib/game.lua
|
--- Game module
-- @module Game
Game = {}
Game.VALID_FILTER = function(v)
return v.valid
end
--- Messages all players currently connected to the game
-- @param msg message to send to players
-- @param condition (optional) optional condition to be true for the player to be messaged
-- @return the number of players who received the message
function Game.print_all(msg, condition)
local num = 0
for _, player in pairs(game.players) do
if player.valid and player.connected then
if condition == nil or select(2, pcall(condition, player)) then
player.print(msg)
num = num + 1
end
end
end
return num
end
--- Messages all players with the given force connected to the game
-- @param force (may be force name string, or force object) the players with the given force to message
-- @param msg message to send to players
-- @return the number of players who received the message
function Game.print_force(force, msg)
local force_name
if type(force) == "string" then
force_name = force
else
force_name = force.name
end
return Game.print_all(msg, function(player)
return player.force.name == force_name
end)
end
--- Messages all players with the given surface connected to the game
-- @param surface the players with the given surface to message
-- @param msg message to send to players
-- @return the number of players who received the message
function Game.print_surface(surface, msg)
local surface_name
if type(surface) == "string" then
surface_name = surface
else
surface_name = surface.name
end
return Game.print_all(msg, function(player)
return player.surface.name == surface_name
end)
end
return Game
|
--- Game module
-- @module Game
Game = {}
Game.VALID_FILTER = function(v)
return v.valid
end
--- Messages all players currently connected to the game
-- @param msg message to send to players
-- @param condition (optional) optional condition to be true for the player to be messaged
-- @return the number of players who received the message
function Game.print_all(msg, condition)
local num = 0
for _, player in pairs(game.players) do
if player.valid and player.connected then
if condition == nil or select(2, pcall(condition, player)) then
player.print(msg)
num = num + 1
end
end
end
return num
end
--- Messages all players with the given force connected to the game
-- @param force (may be force name string, or force object) the players with the given force to message
-- @param msg message to send to players
-- @return the number of players who received the message
function Game.print_force(force, msg)
local force_name
if type(force) == "string" then
force_name = force
else
force_name = force.name
end
return Game.print_all(msg, function(player)
return player.force.name == force_name
end)
end
--- Messages all players with the given surface connected to the game
-- @param surface the players with the given surface to message
-- @param msg message to send to players
-- @return the number of players who received the message
function Game.print_surface(surface, msg)
local surface_name
if type(surface) == "string" then
surface_name = surface
else
surface_name = surface.name
end
return Game.print_all(msg, function(player)
return player.surface.name == surface_name
end)
end
return Game
|
Fix mixed tabs/spaces
|
Fix mixed tabs/spaces
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
df675ff6a7b95e0b948b02f72a51e394201ea33b
|
src/kong/plugins/authentication/schema.lua
|
src/kong/plugins/authentication/schema.lua
|
local constants = require "kong.constants"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
print "HERE"
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
fixing import and removing debug info
|
fixing import and removing debug info
|
Lua
|
apache-2.0
|
ChristopherBiscardi/kong,paritoshmmmec/kong,skynet/kong,Skyscanner/kong,sbuettner/kong,puug/kong,vmercierfr/kong,bbalu/kong,AnsonSmith/kong,chourobin/kong,peterayeni/kong,wakermahmud/kong,ropik/kong
|
bd2675be62d3cc192119a3c3c16b70b665020ceb
|
src/app/scenes/RectBoyScene.lua
|
src/app/scenes/RectBoyScene.lua
|
-- Author: Hua Liang[Stupid ET] <[email protected]>
local RectBoyScene = class("RectBoyScene", function()
local scene = cc.Scene:createWithPhysics()
scene.name = "RectBoyScene"
scene:getPhysicsWorld():setGravity(cc.p(0, 0))
scene:getPhysicsWorld():setDebugDrawMask(config.debug and cc.PhysicsWorld.DEBUGDRAW_ALL or cc.PhysicsWorld.DEBUGDRAW_NONE)
return scene
end)
function RectBoyScene:ctor()
local schedulerID = 0
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local layer = cc.LayerColor:create(cc.c4b(100, 100, 100, 255))
local function bindEvent()
local function onTouchEnded(touch, event)
local location = touch:getLocation()
-- layer.boy:getPhysicsBody():applyImpulse(cc.p(0, 9800 * 4))
layer.boy:getPhysicsBody():setVelocity(cc.p(0, 400))
end
local touchListener = cc.EventListenerTouchOneByOne:create()
touchListener:registerScriptHandler(function() return true end, cc.Handler.EVENT_TOUCH_BEGAN)
touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
end
local function createRectBoy()
local textureBoy = cc.Director:getInstance():getTextureCache():addImage("boy.png")
local rect = cc.rect(0, 0, 40, 40)
local frame0 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
rect = cc.rect(40, 0, 40, 40)
local frame1 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
local spriteBoy = cc.Sprite:createWithSpriteFrame(frame0)
local size = spriteBoy:getContentSize()
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.1)
local animate = cc.Animate:create(animation);
spriteBoy:runAction(cc.RepeatForever:create(animate))
spriteBoy:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4 * 3)
spriteBoy.speed = 0
local body = cc.PhysicsBody:createBox(spriteBoy:getContentSize())
body:applyForce(cc.p(0, -98000))
body:setRotationEnable(false)
body:setVelocity(cc.p(100, 0))
spriteBoy:setPhysicsBody(body)
spriteBoy.body = body
return spriteBoy
end
local function onEnter()
bindEvent()
local boy = createRectBoy()
layer:addChild(boy)
layer.boy = boy
local groundNode = cc.Node:create()
groundNode:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(0, 0), cc.p(20000, 0)))
groundNode:setPosition(cc.p(origin.x - 10000, origin.y + 100))
layer:addChild(groundNode)
local voidNode = cc.Node:create()
local groundList = {}
for i = 0, 100 do
local node = cc.Sprite:create("blank.png")
node:setTextureRect(cc.rect(0, 0, 100, 5))
node:setColor(cc.c3b(255, 255, 255))
node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(-50, 0), cc.p(50, 0)))
node:setPosition(cc.p(math.random(0, 5000), 200 + math.random(10, 200)))
-- voidNode:addChild(node, 1, cc.p(0, 0), cc.p(0, 0))
layer:addChild(node)
groundList[#groundList + 1] = node
end
local function cameraFollow()
-- log.debug("p.x %f, %f", voidNode:getPosition())
-- layer:runAction(cc.MoveBy:create(0, cc.p(-1, 0)))
for idx, gd in ipairs(groundList) do
gd:runAction(cc.MoveBy:create(0, cc.p(-1, 0)))
end
-- groundLayer:setPositionX(groundLayer:getPositionX() - 1)
-- layer.boy:runAction(cc.MoveBy:create(0, cc.p(1, 0)))
end
layer:addChild(voidNode)
local schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(cameraFollow, 0, false)
end
local function onNodeEvent(event)
if "enter" == event then
onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
self:addChild(layer)
end
return RectBoyScene
|
-- Author: Hua Liang[Stupid ET] <[email protected]>
local RectBoyScene = class("RectBoyScene", function()
local scene = cc.Scene:createWithPhysics()
scene.name = "RectBoyScene"
scene:getPhysicsWorld():setGravity(cc.p(0, 0))
scene:getPhysicsWorld():setDebugDrawMask(config.debug and cc.PhysicsWorld.DEBUGDRAW_ALL or cc.PhysicsWorld.DEBUGDRAW_NONE)
return scene
end)
function RectBoyScene:ctor()
local schedulerID = 0
local kTagGround = 100
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local layer = cc.LayerColor:create(cc.c4b(100, 100, 100, 255))
local function bindEvent()
local function onTouchEnded(touch, event)
local location = touch:getLocation()
-- layer.boy:getPhysicsBody():applyImpulse(cc.p(0, 9800 * 4))
layer.boy:getPhysicsBody():setVelocity(cc.p(0, 400))
end
local touchListener = cc.EventListenerTouchOneByOne:create()
touchListener:registerScriptHandler(function() return true end, cc.Handler.EVENT_TOUCH_BEGAN)
touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
end
local function createRectBoy()
local textureBoy = cc.Director:getInstance():getTextureCache():addImage("boy.png")
local rect = cc.rect(0, 0, 40, 40)
local frame0 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
rect = cc.rect(40, 0, 40, 40)
local frame1 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
local spriteBoy = cc.Sprite:createWithSpriteFrame(frame0)
local size = spriteBoy:getContentSize()
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.1)
local animate = cc.Animate:create(animation);
spriteBoy:runAction(cc.RepeatForever:create(animate))
spriteBoy:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4 * 3)
spriteBoy.speed = 0
local body = cc.PhysicsBody:createBox(spriteBoy:getContentSize())
body:applyForce(cc.p(0, -98000 * 1.2))
body:setRotationEnable(false)
body:setVelocity(cc.p(100, 0))
spriteBoy:setPhysicsBody(body)
spriteBoy.body = body
return spriteBoy
end
local function onEnter()
bindEvent()
local boy = createRectBoy()
layer:addChild(boy)
layer.boy = boy
local groundNode = cc.Sprite:create("blank.png")
groundNode:setTextureRect(cc.rect(0, 0, 3000, 5))
groundNode:setColor(cc.c3b(255, 255, 255))
groundNode:setTag(kTagGround)
groundNode:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(-1500, 0), cc.p(1500, 0)))
groundNode:setPosition(cc.p(origin.x + visibleSize.width / 2, origin.y + 100))
layer:addChild(groundNode)
local function tick()
for idx, child in ipairs(layer:getChildren()) do
log.debug("child %s", idx)
if child:getTag() ~= kTagGround and child:getPositionX() < 0 then
child:removeFromParent()
end
end
if #layer:getChildren() < 8 then
for i = 0, 10 do
local node = cc.Sprite:create("blank.png")
node:setTextureRect(cc.rect(0, 0, 100, 5))
node:setColor(cc.c3b(255, 255, 255))
node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(-50, 0), cc.p(50, 0)))
local startX = layer.boy:getPositionX()
node:setPosition(cc.p(math.random(startX, startX + 1000), 200 + math.random(10, 400)))
node:runAction(cc.RepeatForever:create(cc.MoveBy:create(0, cc.p(-1, 0))))
layer:addChild(node)
end
end
end
local schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false)
end
local function onNodeEvent(event)
if "enter" == event then
onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
self:addChild(layer)
end
return RectBoyScene
|
fix ground postion, just move obstacle
|
fix ground postion, just move obstacle
|
Lua
|
apache-2.0
|
cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost
|
f0d43b1e0b11c0e543274607b897c38e1350c4e2
|
mod_host_guard/mod_host_guard.lua
|
mod_host_guard/mod_host_guard.lua
|
-- (C) 2011, Marco Cirillo (LW.Org)
-- Block or restrict by blacklist remote access to local components or hosts.
module:set_global()
local guard_blockall = module:get_option_set("host_guard_blockall", {})
local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
local guard_protect = module:get_option_set("host_guard_selective", {})
local guard_block_bl = module:get_option_set("host_guard_blacklist", {})
local s2smanager = require "core.s2smanager"
local config = require "core.configmanager"
local nameprep = require "util.encodings".stringprep.nameprep
local _make_connect = s2smanager.make_connect
function s2smanager.make_connect(session, connect_host, connect_port)
if not session.s2sValidation then
if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or
guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then
module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host)
s2smanager.destroy_session(session, "You're not authorized, good bye.")
return false;
end
end
return _make_connect(session, connect_host, connect_port)
end
local _stream_opened = s2smanager.streamopened
function s2smanager.streamopened(session, attr)
local host = attr.to and nameprep(attr.to)
local from = attr.from and nameprep(attr.from)
if not from then
session.s2sValidation = false
else
session.s2sValidation = true
end
if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or
guard_block_bl:contains(from) and guard_protect:contains(host) then
module:log("error", "remote service %s attempted to access restricted host %s", from, host)
session:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false;
end
_stream_opened(session, attr)
end
local function sdr_hook (event)
local origin, stanza = event.origin, event.stanza
if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then
if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or
guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then
module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to)
origin:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false
end
end
return nil
end
local function handle_activation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100)
module:log ("debug", "adding host protection for: "..host)
end
end
end
local function handle_deactivation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
module:log ("debug", "removing host protection for: "..host)
end
end
end
local function reload()
module:log ("debug", "server configuration reloaded, rehashing plugin tables...")
guard_blockall = module:get_option_set("host_guard_blockall", {})
guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
guard_protect = module:get_option_set("host_guard_components", {})
guard_block_bl = module:get_option_set("host_guard_blacklist", {})
end
local function setup()
module:log ("debug", "initializing host guard module...")
module:hook ("component-activated", handle_activation)
module:hook ("component-deactivated", handle_deactivation)
module:hook ("config-reloaded", reload)
for n,table in pairs(hosts) do
if table.type == "component" then
if guard_blockall:contains(n) or guard_protect:contains(n) then
hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
handle_activation(n)
end
end
end
end
if prosody.start_time then
setup()
else
module:hook ("server-started", setup)
end
|
-- (C) 2011, Marco Cirillo (LW.Org)
-- Block or restrict by blacklist remote access to local components or hosts.
module:set_global()
local guard_blockall = module:get_option_set("host_guard_blockall", {})
local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
local guard_protect = module:get_option_set("host_guard_selective", {})
local guard_block_bl = module:get_option_set("host_guard_blacklist", {})
local s2smanager = require "core.s2smanager"
local config = require "core.configmanager"
local nameprep = require "util.encodings".stringprep.nameprep
local _make_connect = s2smanager.make_connect
function s2smanager.make_connect(session, connect_host, connect_port)
if not session.s2sValidation then
if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or
guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then
module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host)
s2smanager.destroy_session(session, "You're not authorized, good bye.")
return false;
end
end
return _make_connect(session, connect_host, connect_port)
end
local _stream_opened = s2smanager.streamopened
function s2smanager.streamopened(session, attr)
local host = attr.to and nameprep(attr.to)
local from = attr.from and nameprep(attr.from)
if not from then
session.s2sValidation = false
else
session.s2sValidation = true
end
if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or
guard_block_bl:contains(from) and guard_protect:contains(host) then
module:log("error", "remote service %s attempted to access restricted host %s", from, host)
session:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false;
end
_stream_opened(session, attr)
end
local function sdr_hook (event)
local origin, stanza = event.origin, event.stanza
if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then
if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or
guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then
module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to)
origin:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false
end
end
return nil
end
local function handle_activation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100)
module:log ("debug", "adding host protection for: "..host)
end
end
end
local function handle_deactivation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
module:log ("debug", "removing host protection for: "..host)
end
end
end
local function init_hosts()
for n,table in pairs(hosts) do
hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
if guard_blockall:contains(n) or guard_protect:contains(n) then handle_activation(n) end
end
end
local function reload()
module:log ("debug", "server configuration reloaded, rehashing plugin tables...")
guard_blockall = module:get_option_set("host_guard_blockall", {})
guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
guard_protect = module:get_option_set("host_guard_selective", {})
guard_block_bl = module:get_option_set("host_guard_blacklist", {})
init_hosts()
end
local function setup()
module:log ("debug", "initializing host guard module...")
module:hook ("host-activated", handle_activation)
module:hook ("host-deactivated", handle_deactivation)
module:hook ("config-reloaded", reload)
init_hosts()
end
if prosody.start_time then
setup()
else
module:hook ("server-started", setup)
end
|
mod_host_guard: fixed plugin, minor code refactor.
|
mod_host_guard: fixed plugin, minor code refactor.
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
aa0450ab5da1e8525abbaa66aeb48649e4520336
|
frontend/device/generic/device.lua
|
frontend/device/generic/device.lua
|
local Event = require("ui/event")
local util = require("ffi/util")
local DEBUG = require("dbg")
local function yes() return true end
local function no() return false end
local Device = {
screen_saver_mode = false,
charging_mode = false,
survive_screen_saver = false,
model = nil,
powerd = nil,
screen = nil,
input = nil,
-- hardware feature tests: (these are functions!)
hasKeyboard = no,
hasKeys = no,
hasDPad = no,
isTouchDevice = no,
hasFrontlight = no,
-- use these only as a last resort. We should abstract the functionality
-- and have device dependent implementations in the corresponting
-- device/<devicetype>/device.lua file
-- (these are functions!)
isKindle = no,
isKobo = no,
isPocketBook = no,
isAndroid = no,
isSDL = no,
-- some devices have part of their screen covered by the bezel
viewport = nil,
-- enforce portrait orientation on display, no matter how configured at
-- startup
isAlwaysPortrait = no,
-- needs full screen refresh when resumed from screensaver?
needsScreenRefreshAfterResume = yes,
}
function Device:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Device:init()
if not self.screen then
error("screen/framebuffer must be implemented")
end
DEBUG("initializing for device", self.model)
DEBUG("framebuffer resolution:", self.screen:getSize())
if not self.input then
self.input = require("device/input"):new{device = self}
end
if not self.powerd then
self.powerd = require("device/generic/powerd"):new{device = self}
end
if self.viewport then
DEBUG("setting a viewport:", self.viewport)
self.screen:setViewport(self.viewport)
self.input:registerEventAdjustHook(
self.input.adjustTouchTranslate,
{x = 0 - self.viewport.x, y = 0 - self.viewport.y})
end
end
function Device:getPowerDevice()
return self.powerd
end
-- ONLY used for Kindle devices
function Device:intoScreenSaver()
local UIManager = require("ui/uimanager")
if self.screen_saver_mode == false then
self.screen:saveCurrentBB()
self.screen_saver_mode = true
end
UIManager:sendEvent(Event:new("FlushSettings"))
-- On FW >= 5.7.2, we sigstop awesome, but we need it to show stuff...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -cont awesome")
end
end
-- ONLY used for Kindle devices
function Device:outofScreenSaver()
-- On FW >= 5.7.2, put awesome to sleep again...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -stop awesome")
end
if self.screen_saver_mode == true then
-- wait for native system update screen before we recover saved
-- Blitbuffer.
util.usleep(1500000)
self.screen:restoreFromSavedBB()
self:resume()
if self:needsScreenRefreshAfterResume() then
self.screen:refreshFull()
end
end
self.screen_saver_mode = false
end
-- ONLY used for Kobo and PocketBook devices
function Device:onPowerEvent(ev)
local Screensaver = require("ui/screensaver")
if (ev == "Power" or ev == "Suspend") and not self.screen_saver_mode then
self.powerd:beforeSuspend()
local UIManager = require("ui/uimanager")
-- flushing settings first in case the screensaver takes too long time
-- that flushing has no chance to run
UIManager:sendEvent(Event:new("FlushSettings"))
DEBUG("Suspending...")
-- always suspend in portrait mode
self.orig_rotation_mode = self.screen:getRotationMode()
self.screen:setRotationMode(0)
Screensaver:show()
self.screen:refreshFull()
self.screen_saver_mode = true
UIManager:scheduleIn(10, self.suspend)
elseif (ev == "Power" or ev == "Resume") and self.screen_saver_mode then
DEBUG("Resuming...")
self:resume()
-- restore to previous rotation mode
self.screen:setRotationMode(self.orig_rotation_mode)
local UIManager = require("ui/uimanager")
UIManager:unschedule(self.suspend)
if self:needsScreenRefreshAfterResume() then
self.screen:refreshFull()
end
self.screen_saver_mode = false
self.powerd:refreshCapacity()
Screensaver:close()
self.powerd:afterResume()
end
end
-- Hardware function to suspend the device
function Device:suspend() end
-- Hardware function to resume the device
function Device:resume() end
function Device:usbPlugIn()
if self.charging_mode == false and self.screen_saver_mode == false then
self.screen:saveCurrentBB()
end
self.charging_mode = true
end
function Device:usbPlugOut()
if self.charging_mode == true and self.screen_saver_mode == false then
self.screen:restoreFromSavedBB()
self.screen:refreshFull()
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
self.charging_mode = false
end
--[[
prepare for application shutdown
--]]
function Device:exit()
require("ffi/input"):closeAll()
self.screen:close()
end
return Device
|
local Event = require("ui/event")
local util = require("ffi/util")
local DEBUG = require("dbg")
local function yes() return true end
local function no() return false end
local Device = {
screen_saver_mode = false,
charging_mode = false,
survive_screen_saver = false,
model = nil,
powerd = nil,
screen = nil,
input = nil,
-- hardware feature tests: (these are functions!)
hasKeyboard = no,
hasKeys = no,
hasDPad = no,
isTouchDevice = no,
hasFrontlight = no,
-- use these only as a last resort. We should abstract the functionality
-- and have device dependent implementations in the corresponting
-- device/<devicetype>/device.lua file
-- (these are functions!)
isKindle = no,
isKobo = no,
isPocketBook = no,
isAndroid = no,
isSDL = no,
-- some devices have part of their screen covered by the bezel
viewport = nil,
-- enforce portrait orientation on display, no matter how configured at
-- startup
isAlwaysPortrait = no,
-- needs full screen refresh when resumed from screensaver?
needsScreenRefreshAfterResume = yes,
}
function Device:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Device:init()
if not self.screen then
error("screen/framebuffer must be implemented")
end
DEBUG("initializing for device", self.model)
DEBUG("framebuffer resolution:", self.screen:getSize())
if not self.input then
self.input = require("device/input"):new{device = self}
end
if not self.powerd then
self.powerd = require("device/generic/powerd"):new{device = self}
end
if self.viewport then
DEBUG("setting a viewport:", self.viewport)
self.screen:setViewport(self.viewport)
self.input:registerEventAdjustHook(
self.input.adjustTouchTranslate,
{x = 0 - self.viewport.x, y = 0 - self.viewport.y})
end
end
function Device:getPowerDevice()
return self.powerd
end
-- ONLY used for Kindle devices
function Device:intoScreenSaver()
local UIManager = require("ui/uimanager")
if self.charging_mode == false and self.screen_saver_mode == false then
self.screen:saveCurrentBB()
self.screen_saver_mode = true
-- On FW >= 5.7.2, we sigstop awesome, but we need it to show stuff...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -cont awesome")
end
end
UIManager:sendEvent(Event:new("FlushSettings"))
end
-- ONLY used for Kindle devices
function Device:outofScreenSaver()
if self.screen_saver_mode == true and self.charging_mode == false then
-- On FW >= 5.7.2, put awesome to sleep again...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -stop awesome")
end
-- wait for native system update screen before we recover saved
-- Blitbuffer.
util.usleep(1500000)
self.screen:restoreFromSavedBB()
self:resume()
if self:needsScreenRefreshAfterResume() then
self.screen:refreshFull()
end
end
self.screen_saver_mode = false
end
-- ONLY used for Kobo and PocketBook devices
function Device:onPowerEvent(ev)
local Screensaver = require("ui/screensaver")
if (ev == "Power" or ev == "Suspend") and not self.screen_saver_mode then
self.powerd:beforeSuspend()
local UIManager = require("ui/uimanager")
-- flushing settings first in case the screensaver takes too long time
-- that flushing has no chance to run
UIManager:sendEvent(Event:new("FlushSettings"))
DEBUG("Suspending...")
-- always suspend in portrait mode
self.orig_rotation_mode = self.screen:getRotationMode()
self.screen:setRotationMode(0)
Screensaver:show()
self.screen:refreshFull()
self.screen_saver_mode = true
UIManager:scheduleIn(10, self.suspend)
elseif (ev == "Power" or ev == "Resume") and self.screen_saver_mode then
DEBUG("Resuming...")
self:resume()
-- restore to previous rotation mode
self.screen:setRotationMode(self.orig_rotation_mode)
local UIManager = require("ui/uimanager")
UIManager:unschedule(self.suspend)
if self:needsScreenRefreshAfterResume() then
self.screen:refreshFull()
end
self.screen_saver_mode = false
self.powerd:refreshCapacity()
Screensaver:close()
self.powerd:afterResume()
end
end
-- Hardware function to suspend the device
function Device:suspend() end
-- Hardware function to resume the device
function Device:resume() end
function Device:usbPlugIn()
if self.charging_mode == false and self.screen_saver_mode == false then
self.screen:saveCurrentBB()
-- On FW >= 5.7.2, we sigstop awesome, but we need it to show stuff...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -cont awesome")
end
end
self.charging_mode = true
end
function Device:usbPlugOut()
if self.charging_mode == true and self.screen_saver_mode == false then
-- On FW >= 5.7.2, put awesome to sleep again...
if os.getenv("AWESOME_STOPPED") == "yes" then
os.execute("killall -stop awesome")
end
-- Same as when going out of screensaver, wait for the native system
util.usleep(1500000)
self.screen:restoreFromSavedBB()
self.screen:refreshFull()
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
self.charging_mode = false
end
--[[
prepare for application shutdown
--]]
function Device:exit()
require("ffi/input"):closeAll()
self.screen:close()
end
return Device
|
Fix volumd's USBMS splash screen on FW 5.7.x
|
Fix volumd's USBMS splash screen on FW 5.7.x
That clears up my previous queries abour the dual checks ;p.
|
Lua
|
agpl-3.0
|
houqp/koreader,robert00s/koreader,Frenzie/koreader,lgeek/koreader,apletnev/koreader,Markismus/koreader,mwoz123/koreader,Frenzie/koreader,poire-z/koreader,koreader/koreader,pazos/koreader,chihyang/koreader,koreader/koreader,NiLuJe/koreader,NickSavage/koreader,Hzj-jie/koreader,mihailim/koreader,NiLuJe/koreader,poire-z/koreader,frankyifei/koreader
|
cd2dfc0226a264ae418d667cf17c43c9b2e8bcad
|
Examples/ubuntu-setup.cfg.lua
|
Examples/ubuntu-setup.cfg.lua
|
defaults.chrootdir=loader.path.combine(loader.workdir,"ubuntu_chroot")
defaults.user="root"
defaults.uid=0
defaults.gid=0
defaults.recalculate()
sandbox =
{
setup =
{
static_executor=true,
commands =
{
{'rm -f "etc/resolv.conf"', 'cp "/etc/resolv.conf" "etc/resolv.conf"'},
},
env_blacklist =
{
defaults.env.blacklist_main,
defaults.env.blacklist_audio,
defaults.env.blacklist_desktop,
defaults.env.blacklist_home,
defaults.env.blacklist_xdg,
},
-- set custom env variables,
env_set =
{
{
{"PATH","/fixups:/usr/sbin:/sbin:/usr/bin:/bin:/usr/bin/X11"},
{"HOME","/root"},
{"USER",defaults.user},
{"LOGNAME",defaults.user}
},
defaults.env.set_xdg_runtime,
}
},
bwrap =
{
defaults.bwrap.unshare_user,
defaults.bwrap.unshare_ipc,
defaults.bwrap.unshare_pid,
defaults.bwrap.unshare_uts,
defaults.bwrap.proc_mount,
defaults.bwrap.dev_mount,
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"etc"),"/etc"},
defaults.bwrap.xdg_runtime_dir,
defaults.bwrap.bin_rw_mount,
defaults.bwrap.usr_rw_mount,
defaults.bwrap.lib_rw_mount,
defaults.bwrap.lib64_rw_mount,
defaults.bwrap.fixups_mount,
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"root"),"/root"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"run"),"/run"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"sbin"),"/sbin"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"srv"),"/srv"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"opt"),"/opt"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"tmp"),"/tmp"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"var"),"/var"},
{"uid",defaults.uid},
{"gid",defaults.gid},
}
}
shell =
{
exec="/bin/bash",
path="/", -- optional, chdir to this directory inside sandbox before exec
env_unset={"TERM"}, -- optional, variables list to unset
env_set= -- optional, variables list to set
{
{"TERM",os.getenv("TERM")},
},
term_signal=defaults.signals.SIGHUP,
attach=true,
pty=true,
}
|
defaults.chrootdir=loader.path.combine(loader.workdir,"ubuntu_chroot")
defaults.user="root"
defaults.uid=0
defaults.gid=0
defaults.recalculate()
sandbox =
{
features =
{
"rootfixups",
},
setup =
{
static_executor=true,
commands =
{
{'rm -f "etc/resolv.conf"', 'cp "/etc/resolv.conf" "etc/resolv.conf"'},
},
env_blacklist =
{
defaults.env.blacklist_main,
defaults.env.blacklist_audio,
defaults.env.blacklist_desktop,
defaults.env.blacklist_home,
defaults.env.blacklist_xdg,
},
-- set custom env variables,
env_set =
{
{
{"PATH","/fixups:/usr/sbin:/sbin:/usr/bin:/bin:/usr/bin/X11"},
{"HOME","/root"},
{"USER",defaults.user},
{"LOGNAME",defaults.user}
},
defaults.env.set_xdg_runtime,
}
},
bwrap =
{
defaults.bwrap.unshare_user,
defaults.bwrap.unshare_ipc,
defaults.bwrap.unshare_pid,
defaults.bwrap.unshare_uts,
defaults.bwrap.proc_mount,
defaults.bwrap.dev_mount,
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"etc"),"/etc"},
defaults.bwrap.xdg_runtime_dir,
defaults.bwrap.bin_rw_mount,
defaults.bwrap.usr_rw_mount,
defaults.bwrap.lib_rw_mount,
defaults.bwrap.lib64_rw_mount,
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"root"),"/root"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"run"),"/run"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"sbin"),"/sbin"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"srv"),"/srv"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"opt"),"/opt"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"tmp"),"/tmp"},
{prio=10,"bind",loader.path.combine(defaults.chrootdir,"var"),"/var"},
{"uid",defaults.uid},
{"gid",defaults.gid},
}
}
shell =
{
exec="/bin/bash",
path="/", -- optional, chdir to this directory inside sandbox before exec
env_unset={"TERM"}, -- optional, variables list to unset
env_set= -- optional, variables list to set
{
{"TERM",os.getenv("TERM")},
},
term_signal=defaults.signals.SIGHUP,
attach=true,
pty=true,
}
|
ubuntu-setup.cfg.lua: use rootfixups feature
|
ubuntu-setup.cfg.lua: use rootfixups feature
|
Lua
|
mit
|
DarkCaster/Sandboxer,DarkCaster/Sandboxer
|
ec936934934127eb26e342835a1be6ab67887a9d
|
hostinfo/base.lua
|
hostinfo/base.lua
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local gmtNow = require('virgo/utils').gmtNow
local tableToString = require('virgo/util/misc').tableToString
local los = require('los')
local Object = require('core').Object
-------------------------------------------------------------------------------
local HostInfo = Object:extend()
function HostInfo:initialize()
self._params = {}
self._error = nil
end
function HostInfo:serialize()
return {
error = self._error,
metrics = self._params,
timestamp = gmtNow()
}
end
function HostInfo:getType()
return 'HostInfo'
end
function HostInfo:run(callback)
if not self:_isValidPlatform() then
self:_pushError('Unsupported operating system for ' .. self:getType())
return callback()
end
local status, err = pcall(function()
if self._run then self:_run(callback) else callback() end
end)
if not status then
self._params = {}
self:_pushError(err)
callback()
end
end
function HostInfo:getPlatforms()
return nil
end
function HostInfo:_isValidPlatform()
local currentPlatform = los.type()
-- All platforms are valid if getplatforms isnt defined
if not self:getPlatforms() then
return true
elseif #self:getPlatforms() == 0 then
return true
end
for _, platform in pairs(self:getPlatforms()) do
if platform == currentPlatform then
return true
end
end
return false
end
function HostInfo:_pushError(err)
local undeferr = 'No error specified but no data recieved'
if type(err) == 'nil' then
err = undeferr
elseif type(err) == 'string' then
if #err == 0 then err = undeferr end
elseif type(err) == 'number' then
err = 'Error code:' .. err
elseif type(err) == 'table' then
if not next(err) then
err = undeferr
else
err = tableToString(err)
end
end
-- Allow pusherror to be called more than once and additively build errmsgs
if self._error then
self._error = '>' .. self._error .. '\n>' .. err
else
self._error = err
end
end
function HostInfo:_pushParams(err, data)
-- flatten single entry objects
if type(data) == 'table' then
if #data == 1 then data = data[1] end
end
self._params = data
if err then
self:_pushError(err)
elseif not err and not data or not next(data) then
self:_pushError(err)
end
end
exports.HostInfo = HostInfo
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local gmtNow = require('virgo/utils').gmtNow
local tableToString = require('virgo/util/misc').tableToString
local los = require('los')
local Object = require('core').Object
-------------------------------------------------------------------------------
local HostInfo = Object:extend()
function HostInfo:initialize()
self._params = {}
self._error = nil
end
function HostInfo:serialize()
return {
error = self._error,
metrics = self._params,
timestamp = gmtNow()
}
end
function HostInfo:getType()
return 'HostInfo'
end
function HostInfo:run(callback)
if not self:_isValidPlatform() then
self:_pushError('Unsupported operating system for ' .. self:getType())
return callback()
end
local status, err = pcall(function()
if self._run then self:_run(callback) else callback() end
end)
if not status then
self._params = {}
self:_pushError(err)
callback()
end
end
function HostInfo:getPlatforms()
return nil
end
function HostInfo:_isValidPlatform()
local currentPlatform = los.type()
-- All platforms are valid if getplatforms isnt defined
if not self:getPlatforms() then
return true
elseif #self:getPlatforms() == 0 then
return true
end
for _, platform in pairs(self:getPlatforms()) do
if platform == currentPlatform then
return true
end
end
return false
end
function HostInfo:_pushError(err)
local undeferr = 'No error specified but no data recieved'
if type(err) == 'nil' then
err = undeferr
elseif type(err) == 'string' then
if #err == 0 then err = undeferr end
elseif type(err) == 'number' then
err = 'Error code:' .. err
elseif type(err) == 'table' then
if not next(err) then
err = undeferr
else
err = tableToString(err)
end
end
-- Allow pusherror to be called more than once and additively build errmsgs
if self._error then
self._error = '>' .. self._error .. '\n>' .. err
else
self._error = err
end
end
function HostInfo:_pushParams(err, data)
-- flatten single entry objects
if type(data) == 'table' then
if #data == 1 then data = data[1] end
end
self._params = data
if err then
if type(err) == 'table' and next(err) then
self:_pushError(err)
elseif type(err) == 'string' and #err > 0 then
self:_pushError(err)
end
elseif not err and not data or not next(data) then
self:_pushError(err)
end
end
exports.HostInfo = HostInfo
|
fix(hostinfo/base): Prevent erronously added undefined error messeages from being added to our response
|
fix(hostinfo/base): Prevent erronously added undefined error messeages from being added to our response
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
d600f2ef73fba8a7b8380108499cdc15be6836d4
|
wyx/event/EventManager.lua
|
wyx/event/EventManager.lua
|
local Class = require 'lib.hump.class'
-- EventManager
-- Provides a class that registers objects with itself, then notifies
-- those object when events occur.
local Event = getClass 'wyx.event.Event'
local eventsMT = {__mode = 'k'}
local format = string.format
-- EventManager class
local EventManager = Class{name='EventManager',
function(self, name)
name = name or 'EventManager'
verify('string', name)
self._name = name
self._events = {}
end
}
-- validate that the given object is an object or a function
local _validateObj = function(obj)
assert(obj and (type(obj) == 'table' or type(obj) == 'function'),
'expected an object or function (was %s)', type(obj))
end
-- destructor
function EventManager:destroy()
self:clear()
for k,v in pairs(self._events) do
for l,w in pairs(self._events[k]) do
self._events[k][l] = nil
end
self._events[k] = nil
end
self._events = nil
self._name = nil
self._lastDebugMsg = nil
self._lastDebugRepeat = nil
self._debug = nil
end
-- register an object to listen for the given events
-- obj can be:
-- a function
-- an object with a method that has the same name as the event
-- an object with an onEvent method
function EventManager:register(obj, events)
_validateObj(obj)
local hasOnEvent = type(obj) == 'function'
or obj.onEvent and type(obj.onEvent) == 'function'
if events.is_a then
events = {events}
end
for _,event in ipairs(events) do
verifyClass(Event, event)
local keyStr = tostring(event:getEventKey())
assert(hasOnEvent or (obj[keyStr] and type(obj[keyStr]) == 'function'),
'object "%s" is missing event callback method for event "%s"',
tostring(obj), keyStr)
local key = event:getEventKey()
-- event table has weak keys
self._events[key] = self._events[key] or setmetatable({}, eventsMT)
self._events[key][obj] = true
end
end
-- unregister an object from listening for the given events
function EventManager:unregister(obj, events)
_validateObj(obj)
if type(events) ~= 'table' then
events = {events}
end
for _,event in ipairs(events) do
verifyClass(Event, event)
local key = event:getEventKey()
if self._events[key] and self._events[key][obj] then
self._events[key][obj] = nil
end
end
end
-- register an object for all events
function EventManager:registerAll(obj)
self:register(obj, Event:getAllEvents())
end
-- unregister an object from all events
function EventManager:unregisterAll(obj)
local events = self:getRegisteredEvents(obj)
if events then self:unregister(obj, events) end
end
-- return a list of events for which obj is registered
function EventManager:getRegisteredEvents(obj)
_validateObj(obj)
local events = {}
for event,objs in pairs(self._events) do
if objs[obj] then
events[#events+1] = event
end
end
return #events > 0 and events or nil
end
-- notify a specific event, notifying all listeners of the event.
function EventManager:notify(event)
verifyClass(Event, event)
local key = event:getEventKey()
if self._events[key] then
for obj in pairs(self._events[key]) do
if self._debug then
local eventLevel = event:getDebugLevel()
if eventLevel <= self._debug then
local mgr = tostring(self)
local eventstr = tostring(event)
local objstr = tostring(obj.__class or obj)
local msg = format('[%s@%s] %s', mgr, objstr, eventstr)
if self._lastDebugMsg ~= msg then
if self._lastDebugRepeat and self._lastDebugRepeat > 0 then
local m = format('(Last message repeated %d times.)',
self._lastDebugRepeat)
if Console then Console:print(m) end
print(m)
end
self._lastDebugMsg = msg
self._lastDebugRepeat = 0
if Console then Console:print(msg) end
print(msg)
else
self._lastDebugRepeat = self._lastDebugRepeat + 1
end
end
end
if type(obj) == 'function' then -- function()
obj(event)
else
local keyStr = tostring(event:getEventKey())
if obj[keyStr] then obj[keyStr](obj, event) end -- obj:NamedEvent()
if obj.onEvent then obj:onEvent(event) end -- obj:onEvent()
end
end
end
event:destroy()
end
-- push an event into the event queue
function EventManager:push(event)
verifyClass(Event, event)
self._queue = self._queue or {}
self._queue[#self._queue + 1] = event
end
-- flush all events in the event queue and notify their listeners
function EventManager:flush()
if self._queue then
-- copy the queue to a local table in case notifying an event pushes
-- more events on the queue
local queue = {}
for i,event in ipairs(self._queue) do
queue[i] = event
self._queue[i] = nil
end
self._queue = nil
-- iterate through the copy of the queue and notify events
for _,event in ipairs(queue) do
self:notify(event)
end
end
end
-- remove all events in the queue without notifying listeners
function EventManager:clear()
if self._queue then
local num = #self._queue
for i=1,num do
self._queue[i] = nil
end
self._queue = nil
end
end
function EventManager:debug(level)
verify('number', level)
self._debug = level
end
function EventManager:__tostring() return self._name end
-- the module
return EventManager
|
local Class = require 'lib.hump.class'
-- EventManager
-- Provides a class that registers objects with itself, then notifies
-- those object when events occur.
local Event = getClass 'wyx.event.Event'
local eventsMT = {__mode = 'k'}
local format = string.format
-- EventManager class
local EventManager = Class{name='EventManager',
function(self, name)
name = name or 'EventManager'
verify('string', name)
self._name = name
self._events = {}
end
}
-- validate that the given object is an object or a function
local _validateObj = function(obj)
assert(obj and (type(obj) == 'table' or type(obj) == 'function'),
'expected an object or function (was %s)', type(obj))
end
-- destructor
function EventManager:destroy()
self:clear()
for k,v in pairs(self._events) do
for l,w in pairs(self._events[k]) do
self._events[k][l] = nil
end
self._events[k] = nil
end
self._events = nil
if self._unregisterQueue then self:_unregisterPending() end
self._name = nil
self._lastDebugMsg = nil
self._lastDebugRepeat = nil
self._debug = nil
end
-- register an object to listen for the given events
-- obj can be:
-- a function
-- an object with a method that has the same name as the event
-- an object with an onEvent method
function EventManager:register(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._registerQueue = self._registerQueue or {}
self._registerQueue[obj] = events
if not self._notifying then self:_registerPending() end
end
-- unregister an object from listening for the given events
function EventManager:unregister(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._unregisterQueue = self._unregisterQueue or {}
self._unregisterQueue[obj] = events
if not self._notifying then self:_unregisterPending() end
end
-- register an object for all events
function EventManager:registerAll(obj)
self:register(obj, Event:getAllEvents())
end
-- unregister an object from all events
function EventManager:unregisterAll(obj)
local events = self:getRegisteredEvents(obj)
if events then self:unregister(obj, events) end
end
-- return a list of events for which obj is registered
function EventManager:getRegisteredEvents(obj)
_validateObj(obj)
local events = {}
for event,objs in pairs(self._events) do
if objs[obj] then
events[#events+1] = event
end
end
return #events > 0 and events or nil
end
function EventManager:_registerPending()
if self._registerQueue then
for obj,events in pairs(self._registerQueue) do
local hasOnEvent = type(obj) == 'function'
or (type(obj) == 'table'
and obj.onEvent
and type(obj.onEvent) == 'function')
for _,event in ipairs(events) do
verifyClass(Event, event)
local keyStr = tostring(event:getEventKey())
assert(hasOnEvent or (obj[keyStr] and type(obj[keyStr]) == 'function'),
'object "%s" is missing event callback method for event "%s"',
tostring(obj), keyStr)
local key = event:getEventKey()
-- event table has weak keys
self._events[key] = self._events[key] or setmetatable({}, eventsMT)
self._events[key][obj] = true
end
self._registerQueue[obj] = nil
end
self._registerQueue = nil
end
end
function EventManager:_unregisterPending()
if self._unregisterQueue then
for obj,events in pairs(self._unregisterQueue) do
for _,event in ipairs(events) do
verifyClass(Event, event)
local key = event:getEventKey()
if self._events[key] and self._events[key][obj] then
self._events[key][obj] = nil
end
end
self._unregisterQueue[obj] = nil
end
self._unregisterQueue = nil
end
end
-- notify a specific event, notifying all listeners of the event.
function EventManager:notify(event)
verifyClass(Event, event)
self._notifying = true
local key = event:getEventKey()
if self._events[key] then
for obj in pairs(self._events[key]) do
if self._debug then
local eventLevel = event:getDebugLevel()
if eventLevel <= self._debug then
local mgr = tostring(self)
local eventstr = tostring(event)
local objstr = tostring(obj.__class or obj)
local msg = format('[%s@%s] %s', mgr, objstr, eventstr)
if self._lastDebugMsg ~= msg then
if self._lastDebugRepeat and self._lastDebugRepeat > 0 then
local m = format('(Last message repeated %d times.)',
self._lastDebugRepeat)
if Console then Console:print(m) end
print(m)
end
self._lastDebugMsg = msg
self._lastDebugRepeat = 0
if Console then Console:print(msg) end
print(msg)
else
self._lastDebugRepeat = self._lastDebugRepeat + 1
end
end
end
if type(obj) == 'function' then -- function()
obj(event)
else
local keyStr = tostring(event:getEventKey())
if obj[keyStr] then obj[keyStr](obj, event) end -- obj:NamedEvent()
if obj.onEvent then obj:onEvent(event) end -- obj:onEvent()
end
end
end
self:_registerPending()
self:_unregisterPending()
self._notifying = false
event:destroy()
end
-- push an event into the event queue
function EventManager:push(event)
verifyClass(Event, event)
self._queue = self._queue or {}
self._queue[#self._queue + 1] = event
end
-- flush all events in the event queue and notify their listeners
function EventManager:flush()
if self._queue then
-- copy the queue to a local table in case notifying an event pushes
-- more events on the queue
local queue = {}
for i,event in ipairs(self._queue) do
queue[i] = event
self._queue[i] = nil
end
self._queue = nil
-- iterate through the copy of the queue and notify events
for _,event in ipairs(queue) do
self:notify(event)
end
end
if not self._notifying then self:_unregisterPending() end
end
-- remove all events in the queue without notifying listeners
function EventManager:clear()
if self._queue then
local num = #self._queue
for i=1,num do
self._queue[i] = nil
end
self._queue = nil
end
if not self._notifying then self:_unregisterPending() end
end
function EventManager:debug(level)
verify('number', level)
self._debug = level
end
function EventManager:__tostring() return self._name end
-- the module
return EventManager
|
fix EventManager to queue register/unregister requests
|
fix EventManager to queue register/unregister requests
These requests are fulfilled after the notify step is finished. This avoids the situation where objects are inappropriately notified after being registered in the middle of a notify cycle. It also avoids the situation where the notify cycle can crash because an object was unregistered before it was notified.
|
Lua
|
mit
|
scottcs/wyx
|
2104895f9c75bc2b5c5c8a8da52f9116e368285c
|
lualib/sys/tls.lua
|
lualib/sys/tls.lua
|
local core = require "sys.core"
local type = type
local concat = table.concat
local assert = assert
local socket_pool = {}
local M = {}
local EVENT = {}
local ctx
local tls
local client_ctx
local function new_socket(fd, ctx)
local s = {
nil,
fd = fd,
delim = false,
co = false,
ssl = tls.open(ctx, fd),
closing = false,
}
socket_pool[fd] = s
return s
end
local function del_socket(s)
tls.close(s.ssl)
socket_pool[s.fd] = nil
end
local function wakeup(s, dat)
local co = s.co
s.co = false
core.wakeup(co, dat)
end
local function suspend(s)
assert(not s.co)
local co = core.running()
s.co = co
return core.wait(co)
end
local function handshake(s)
local ok = tls.handshake(s.ssl)
if ok then
return ok
end
s.delim = "~"
return suspend(s)
end
function EVENT.accept(fd, _, portid, addr)
local lc = socket_pool[portid];
local s = new_socket(fd, lc.ctx)
local ok = handshake(s)
if not ok then
return
end
local ok, err = core.pcall(lc.disp, fd, addr)
if not ok then
core.log(err)
M.close(fd)
end
end
function EVENT.close(fd, _, errno)
local s = socket_pool[fd]
if s == nil then
return
end
s.closing = true
if s.co then
wakeup(s, false)
del_socket(s)
end
end
function EVENT.data(fd, message)
local s = socket_pool[fd]
if not s then
return
end
local delim = s.delim
tls.message(s.ssl, message)
if not delim then --non suspend read
return
end
if type(delim) == "number" then
local dat = tls.read(s.ssl, delim)
if dat then
local n = delim - #dat
if n == 0 then
s.delim = false
else
s.delim = n
end
wakeup(s, dat)
end
elseif delim == "\n" then
local dat, ok = tls.readline(s.ssl)
if dat ~= "" then
if ok then
s.delim = false
end
wakeup(s, dat)
end
elseif delim == "~" then
local ok = tls.handshake(s.ssl)
if ok then
s.delim = false
wakeup(s, true)
end
end
end
local function socket_dispatch(type, fd, message, ...)
EVENT[type](fd, message, ...)
end
local function connect_normal(ip, bind)
local fd = core.connect(ip, socket_dispatch, bind)
if not fd then
return nil
end
local s = new_socket(fd, client_ctx)
local ok = handshake(s)
if ok then
return fd
end
M.close(fd)
return nil
end
function M.connect(ip, bind)
tls = require "sys.tls.tls"
ctx = require "sys.tls.ctx"
client_ctx = ctx.client()
M.connect = connect_normal
return connect_normal(ip, bind)
end
function M.listen(conf)
assert(conf.port)
assert(conf.disp)
local portid = core.listen(conf.port, socket_dispatch, conf.backlog)
if not portid then
return nil
end
tls = require "sys.tls.tls"
ctx = ctx or require "sys.tls.ctx"
socket_pool[portid] = {
fd = portid,
disp = conf.disp,
co = false,
ctx = ctx.server(conf.cert, conf.key, conf.ciphers),
}
return portid
end
function M.close(fd)
local s = socket_pool[fd]
if s == nil then
return false
end
if s.co then
wakeup(s, false)
end
del_socket(s)
core.close(fd)
return true
end
function M.read(fd, n)
local s = socket_pool[fd]
if not s then
return false
end
local d = tls.read(s.ssl, n)
if #d == n then
return d
end
if s.closing then
del_socket(s)
return false
end
s.delim = n
while s.delim do
local r = suspend(s)
if not r then
return false
end
d = d .. r
end
return d
end
function M.readall(fd)
local s = socket_pool[fd]
if not s then
return false
end
local r = tls.readall(s.ssl)
if r == "" and s.closing then
del_socket(s)
return false
end
return r
end
function M.readline(fd)
local s = socket_pool[fd]
if not s then
return false
end
local d, ok
d, ok = tls.readline(s.ssl)
if ok then
return d
end
s.delim = "\n"
while s.delim do
local r
r, ok = suspend(s)
if not r then
return false
end
d = d .. r
end
return d
end
function M.write(fd, str)
local s = socket_pool[fd]
if not s or s.closing then
return false, "already closed"
end
return tls.write(s.ssl, str)
end
return M
|
local core = require "sys.core"
local type = type
local concat = table.concat
local assert = assert
local socket_pool = {}
local M = {}
local EVENT = {}
local ctx
local tls
local client_ctx
local function new_socket(fd, ctx)
local s = {
nil,
fd = fd,
delim = false,
co = false,
ssl = tls.open(ctx, fd),
closing = false,
}
socket_pool[fd] = s
return s
end
local function del_socket(s)
tls.close(s.ssl)
socket_pool[s.fd] = nil
end
local function wakeup(s, dat)
local co = s.co
s.co = false
core.wakeup(co, dat)
end
local function suspend(s)
assert(not s.co)
local co = core.running()
s.co = co
return core.wait(co)
end
local function handshake(s)
local ok = tls.handshake(s.ssl)
if ok then
return ok
end
s.delim = "~"
return suspend(s)
end
function EVENT.accept(fd, _, portid, addr)
local lc = socket_pool[portid];
local s = new_socket(fd, lc.ctx)
local ok = handshake(s)
if not ok then
return
end
local ok, err = core.pcall(lc.disp, fd, addr)
if not ok then
core.log(err)
M.close(fd)
end
end
function EVENT.close(fd, _, errno)
local s = socket_pool[fd]
if s == nil then
return
end
s.closing = true
if s.co then
wakeup(s, false)
del_socket(s)
end
end
function EVENT.data(fd, message)
local s = socket_pool[fd]
if not s then
return
end
local delim = s.delim
tls.message(s.ssl, message)
if not delim then --non suspend read
return
end
if type(delim) == "number" then
local dat = tls.read(s.ssl, delim)
if dat then
local n = delim - #dat
if n == 0 then
s.delim = false
else
s.delim = n
end
wakeup(s, dat)
end
elseif delim == "\n" then
local dat, ok = tls.readline(s.ssl)
if dat ~= "" then
if ok then
s.delim = false
end
wakeup(s, dat)
end
elseif delim == "~" then
local ok = tls.handshake(s.ssl)
if ok then
s.delim = false
wakeup(s, true)
end
end
end
local function socket_dispatch(type, fd, message, ...)
EVENT[type](fd, message, ...)
end
local function connect_normal(ip, bind)
local fd = core.connect(ip, socket_dispatch, bind)
if not fd then
return nil
end
local s = new_socket(fd, client_ctx)
local ok = handshake(s)
if ok then
return fd
end
M.close(fd)
return nil
end
function M.connect(ip, bind)
tls = require "sys.tls.tls"
ctx = require "sys.tls.ctx"
client_ctx = ctx.client()
M.connect = connect_normal
return connect_normal(ip, bind)
end
function M.listen(conf)
assert(conf.port)
assert(conf.disp)
local portid = core.listen(conf.port, socket_dispatch, conf.backlog)
if not portid then
return nil
end
tls = require "sys.tls.tls"
ctx = ctx or require "sys.tls.ctx"
local c = ctx.server(conf.cert, conf.key, conf.ciphers)
new_socket(portid, c).ctx = c
return portid
end
function M.close(fd)
local s = socket_pool[fd]
if s == nil then
return false
end
if s.co then
wakeup(s, false)
end
del_socket(s)
core.close(fd)
return true
end
function M.read(fd, n)
local s = socket_pool[fd]
if not s then
return false
end
local d = tls.read(s.ssl, n)
if #d == n then
return d
end
if s.closing then
del_socket(s)
return false
end
s.delim = n
while s.delim do
local r = suspend(s)
if not r then
return false
end
d = d .. r
end
return d
end
function M.readall(fd)
local s = socket_pool[fd]
if not s then
return false
end
local r = tls.readall(s.ssl)
if r == "" and s.closing then
del_socket(s)
return false
end
return r
end
function M.readline(fd)
local s = socket_pool[fd]
if not s then
return false
end
local d, ok
d, ok = tls.readline(s.ssl)
if ok then
return d
end
s.delim = "\n"
while s.delim do
local r
r, ok = suspend(s)
if not r then
return false
end
d = d .. r
end
return d
end
function M.write(fd, str)
local s = socket_pool[fd]
if not s or s.closing then
return false, "already closed"
end
return tls.write(s.ssl, str)
end
return M
|
bugfix tls gc of listen socket
|
bugfix tls gc of listen socket
|
Lua
|
mit
|
findstr/silly
|
7bf0113c4fede35ec93fbdc0c46b26ad5c8dd42d
|
lualibs/mapdef.lua
|
lualibs/mapdef.lua
|
-- fce pro definici mapy
local push = table.insert
local mapdef = {
rules = {},
ANY = {}
}
_G.ANY = mapdef.ANY
function _G.line(def)
def._type = 'line'
def.color = def.color or error 'Missing color!'
def.feat = def.feat or error 'Missing feat!'
push(mapdef.rules, def)
end
function _G.area(def)
def._type = 'area'
def.color = def.color or error 'Missing color!'
def.feat = def.feat or error 'Missing feat!'
push(mapdef.rules, def)
end
return mapdef
|
-- fce pro definici mapy
local push = table.insert
local mapdef = {
rules = {},
ANY = {}
}
_G.ANY = mapdef.ANY
function _G.stylesheet(name)
mapdef.name = name
end
function _G.by(author)
mapdef.author = author
end
function _G.background(color)
mapdef.background = color
end
function _G.line(def)
def._type = 'line'
def.color = def.color or error 'Missing color!'
def.feat = def.feat or error 'Missing feat!'
push(mapdef.rules, def)
end
function _G.area(def)
def._type = 'area'
def.color = def.color or error 'Missing color!'
def.feat = def.feat or error 'Missing feat!'
push(mapdef.rules, def)
end
return mapdef
|
fix mapdef
|
fix mapdef
|
Lua
|
mit
|
severak/mapstyles,severak/mapstyles
|
2ad29e9e57b0538a4e5710af7c3cbebe397b99cc
|
modules/sorter.lua
|
modules/sorter.lua
|
local A, L = unpack(select(2, ...))
local M = A:NewModule("sorter", "AceEvent-3.0", "AceTimer-3.0")
A.sorter = M
M.private = {
sortMode = false,
lastSortMode = false,
resumeAfterCombat = false,
startTime = false,
stepCount = false,
timeoutTimer = false,
timeoutCount = false,
}
local R = M.private
local MAX_STEPS = 30
local MAX_TIMEOUTS = 20
local DELAY_TIMEOUT = 1.0
local floor, format, tostring, time = floor, format, tostring, time
local InCombatLockdown, IsInRaid, SendChatMessage = InCombatLockdown, IsInRaid, SendChatMessage
function M:OnEnable()
M:RegisterEvent("PLAYER_ENTERING_WORLD")
M:RegisterEvent("PLAYER_REGEN_ENABLED")
M:RegisterMessage("FIXGROUPS_PLAYER_CHANGED_GROUP")
end
function M:PLAYER_ENTERING_WORLD(event)
R.lastSortMode = false
end
function M:PLAYER_REGEN_ENABLED(event)
M:ResumeIfPaused()
end
function M:FIXGROUPS_PLAYER_CHANGED_GROUP(event, name, prevGroup, group)
if M:IsProcessing() and A.coreSort:DidActionFinish() then
M:ProcessStep()
else
if A.DEBUG >= 2 then A.console:Debugf(M, "someone else moved %s %d->%d", name, prevGroup, group) end
end
end
function M:IsSortingHealersBeforeDamagers()
return A.options.sortMode == "THMUR" and R.sortMode ~= "TMURH"
end
function M:IsSortingByMeter()
return R.sortMode == "meter"
end
function M:IsSplittingRaid()
return R.sortMode == "split"
end
function M:IsProcessing()
return R.stepCount and true or false
end
function M:IsPaused()
return R.resumeAfterCombat and true or false
end
function M:CanBegin()
return not M:IsProcessing() and not M:IsPaused() and not InCombatLockdown() and IsInRaid() and A.util:IsLeaderOrAssist()
end
function M:Stop()
A.coreSort:CancelAction()
M:ClearTimeout(true)
R.stepCount = false
R.startTime = false
R.sortMode = false
R.resumeAfterCombat = false
A.buttonGui:Refresh()
end
function M:StopTimedOut()
A.console:Printf(L["sorter.print.timedOut"], L["sorter.mode."..R.sortMode])
if A.DEBUG >= 1 then A.console:Debugf(M, "steps=%d seconds=%.1f timeouts=%d", R.stepCount, (time() - R.startTime), R.timeoutCount) end
M:Stop()
end
function M:StopIfNeeded()
if not A.util:IsLeaderOrAssist() or not IsInRaid() then
A.console:Print(L["sorter.print.needRank"])
M:Stop()
return true
end
if InCombatLockdown() then
local resumeSortMode = R.sortMode
M:Stop()
if A.options.resumeAfterCombat then
A.console:Printf(L["sorter.print.combatPaused"], L["sorter.mode."..resumeSortMode])
R.resumeAfterCombat = resumeSortMode
A.buttonGui:Refresh()
else
A.console:Printf(L["sorter.print.combatCancelled"], L["sorter.mode."..resumeSortMode])
end
return true
end
end
local function start(mode)
M:Stop()
R.sortMode = mode
if M:StopIfNeeded() then
return
end
A.group:PrintIfThereAreUnknowns()
if M:IsSortingByMeter() or M:IsSplittingRaid() then
-- Damage/healing meter snapshot is built once at the start,
-- not once every step.
A.meter:BuildSnapshot(M:IsSortingByMeter())
end
M:ProcessStep()
end
function M:StartMeter()
start("meter")
end
function M:StartSplit()
start("split")
end
function M:StartDefault()
local mode = A.options.sortMode
if mode == "TMURH" or mode == "THMUR" or mode == "meter" then
start(mode)
else
M:Stop()
if mode ~= "nosort" then
A.console:Errorf(M, "invalid sort mode %s!", tostring(mode))
end
end
end
function M:ResumeIfPaused()
if M:IsPaused() and not InCombatLockdown() then
local mode = R.resumeAfterCombat
A.console:Printf(L["sorter.print.combatResumed"], L["sorter.mode."..mode])
R.resumeAfterCombat = false
start(mode)
end
end
function M:ProcessStep()
if M:StopIfNeeded() then
return
end
M:ClearTimeout(false)
if not M:IsProcessing() then
R.stepCount = 0
R.startTime = time()
end
A.coreSort:BuildDelta()
if A.coreSort:IsDeltaEmpty() then
M:AnnounceComplete()
M:Stop()
return
elseif R.stepCount > MAX_STEPS then
M:StopTimedOut()
return
end
A.coreSort:ProcessDelta()
if A.DEBUG >= 2 then A.coreSort:DebugPrintAction() end
if A.coreSort:IsActionScheduled() then
R.stepCount = R.stepCount + 1
M:ScheduleTimeout()
A.buttonGui:Refresh()
else
M:Stop()
end
end
function M:AnnounceComplete()
if R.stepCount == 0 then
if M:IsSplittingRaid() then
A.console:Print(L["sorter.print.alreadySplit"])
else
A.console:Printf(L["sorter.print.alreadySorted"], L["sorter.mode."..R.sortMode])
end
else
-- Announce sort mode.
local msg
if M:IsSplittingRaid() then
msg = format(L["sorter.print.split"], A.coreSort:GetSplitGroups())
else
msg = format(L["sorter.print.sorted"], L["sorter.mode."..R.sortMode])
end
-- Announce group comp.
msg = format("%s %s: %s.", msg, L["phrase.groupComp"], A.group:GetComp(A.util.GROUP_COMP_STYLE.TEXT_FULL))
-- Announce who we excluded, if any.
local sitting = A.group:NumSitting()
if sitting == 1 then
msg = msg.." "..format(L["sorter.print.excludedSitting.singular"], A.util:GetMaxGroupsForInstance()+1)
elseif sitting > 1 then
msg = msg.." "..format(L["sorter.print.excludedSitting.plural"], sitting, A.util:GetMaxGroupsForInstance()+1)
end
-- Announce to group or to self.
if A.options.announceChatAlways or (A.options.announceChatPRN and R.lastSortMode ~= R.sortMode) then
SendChatMessage(format("[%s] %s", A.NAME, msg), A.util:GetGroupChannel())
else
A.console:Print(msg)
end
if A.DEBUG >= 1 then A.console:Debugf(M, "steps=%d seconds=%.1f timeouts=%d", R.stepCount, (time() - R.startTime), R.timeoutCount) end
end
R.lastSortMode = R.sortMode
end
function M:ClearTimeout(resetCount)
if R.timeoutTimer then
M:CancelTimer(R.timeoutTimer)
end
R.timeoutTimer = false
if resetCount then
R.timeoutCount = false
end
end
-- Timeouts can happen for a variety of reasons.
-- Example: While the raid leader's original request to move a player is en
-- route to the server, that player leaves the group or is moved to a different
-- group by someone else.
-- Another example: Good old-fashioned lag.
function M:ScheduleTimeout()
M:ClearTimeout(false)
R.timeoutTimer = M:ScheduleTimer(function ()
M:ClearTimeout(false)
R.timeoutCount = (R.timeoutCount or 0) + 1
if A.DEBUG >= 1 then A.console:Debugf(M, "timeout %d of %d", R.timeoutCount, MAX_TIMEOUTS) end
if R.timeoutCount >= MAX_TIMEOUTS then
M:StopTimedOut()
return
end
A.group:ForceBuildRoster(M, "Timeout")
M:ProcessStep()
end, DELAY_TIMEOUT)
end
|
local A, L = unpack(select(2, ...))
local M = A:NewModule("sorter", "AceEvent-3.0", "AceTimer-3.0")
A.sorter = M
M.private = {
sortMode = false,
lastSortMode = false,
announced = false,
resumeAfterCombat = false,
startTime = false,
stepCount = false,
timeoutTimer = false,
timeoutCount = false,
}
local R = M.private
local MAX_STEPS = 30
local MAX_TIMEOUTS = 20
local DELAY_TIMEOUT = 1.0
local floor, format, tostring, time = floor, format, tostring, time
local InCombatLockdown, IsInRaid, SendChatMessage = InCombatLockdown, IsInRaid, SendChatMessage
function M:OnEnable()
M:RegisterEvent("PLAYER_ENTERING_WORLD")
M:RegisterEvent("PLAYER_REGEN_ENABLED")
M:RegisterMessage("FIXGROUPS_PLAYER_CHANGED_GROUP")
end
function M:PLAYER_ENTERING_WORLD(event)
R.lastSortMode = false
end
function M:PLAYER_REGEN_ENABLED(event)
M:ResumeIfPaused()
end
function M:FIXGROUPS_PLAYER_CHANGED_GROUP(event, name, prevGroup, group)
if M:IsProcessing() and A.coreSort:DidActionFinish() then
M:ProcessStep()
else
if A.DEBUG >= 2 then A.console:Debugf(M, "someone else moved %s %d->%d", name, prevGroup, group) end
end
end
function M:IsSortingHealersBeforeDamagers()
return A.options.sortMode == "THMUR" and R.sortMode ~= "TMURH"
end
function M:IsSortingByMeter()
return R.sortMode == "meter"
end
function M:IsSplittingRaid()
return R.sortMode == "split"
end
function M:IsProcessing()
return R.stepCount and true or false
end
function M:IsPaused()
return R.resumeAfterCombat and true or false
end
function M:CanBegin()
return not M:IsProcessing() and not M:IsPaused() and not InCombatLockdown() and IsInRaid() and A.util:IsLeaderOrAssist()
end
function M:Stop()
A.coreSort:CancelAction()
M:ClearTimeout(true)
R.stepCount = false
R.startTime = false
R.sortMode = false
R.resumeAfterCombat = false
A.buttonGui:Refresh()
end
function M:StopTimedOut()
A.console:Printf(L["sorter.print.timedOut"], L["sorter.mode."..R.sortMode])
if A.DEBUG >= 1 then A.console:Debugf(M, "steps=%d seconds=%.1f timeouts=%d", R.stepCount, (time() - R.startTime), R.timeoutCount) end
M:Stop()
end
function M:StopIfNeeded()
if not A.util:IsLeaderOrAssist() or not IsInRaid() then
A.console:Print(L["sorter.print.needRank"])
M:Stop()
return true
end
if InCombatLockdown() then
local resumeSortMode = R.sortMode
M:Stop()
if A.options.resumeAfterCombat then
A.console:Printf(L["sorter.print.combatPaused"], L["sorter.mode."..resumeSortMode])
R.resumeAfterCombat = resumeSortMode
A.buttonGui:Refresh()
else
A.console:Printf(L["sorter.print.combatCancelled"], L["sorter.mode."..resumeSortMode])
end
return true
end
end
local function start(mode)
M:Stop()
R.sortMode = mode
if M:StopIfNeeded() then
return
end
A.group:PrintIfThereAreUnknowns()
if M:IsSortingByMeter() or M:IsSplittingRaid() then
-- Damage/healing meter snapshot is built once at the start,
-- not once every step.
A.meter:BuildSnapshot(M:IsSortingByMeter())
end
M:ProcessStep()
end
function M:StartMeter()
start("meter")
end
function M:StartSplit()
start("split")
end
function M:StartDefault()
local mode = A.options.sortMode
if mode == "TMURH" or mode == "THMUR" or mode == "meter" then
start(mode)
else
M:Stop()
if mode ~= "nosort" then
A.console:Errorf(M, "invalid sort mode %s!", tostring(mode))
end
end
end
function M:ResumeIfPaused()
if M:IsPaused() and not InCombatLockdown() then
local mode = R.resumeAfterCombat
A.console:Printf(L["sorter.print.combatResumed"], L["sorter.mode."..mode])
R.resumeAfterCombat = false
start(mode)
end
end
function M:ProcessStep()
if M:StopIfNeeded() then
return
end
M:ClearTimeout(false)
if not M:IsProcessing() then
R.stepCount = 0
R.startTime = time()
end
A.coreSort:BuildDelta()
if A.coreSort:IsDeltaEmpty() then
M:AnnounceComplete()
M:Stop()
return
elseif R.stepCount > MAX_STEPS then
M:StopTimedOut()
return
end
A.coreSort:ProcessDelta()
if A.DEBUG >= 2 then A.coreSort:DebugPrintAction() end
if A.coreSort:IsActionScheduled() then
R.stepCount = R.stepCount + 1
M:ScheduleTimeout()
A.buttonGui:Refresh()
else
M:Stop()
end
end
function M:AnnounceComplete()
if R.lastSortMode ~= R.sortMode then
R.announced = false
end
if R.stepCount == 0 then
if M:IsSplittingRaid() then
A.console:Print(L["sorter.print.alreadySplit"])
else
A.console:Printf(L["sorter.print.alreadySorted"], L["sorter.mode."..R.sortMode])
end
else
-- Announce sort mode.
local msg
if M:IsSplittingRaid() then
msg = format(L["sorter.print.split"], A.coreSort:GetSplitGroups())
else
msg = format(L["sorter.print.sorted"], L["sorter.mode."..R.sortMode])
end
-- Announce group comp.
msg = format("%s %s: %s.", msg, L["phrase.groupComp"], A.group:GetComp(A.util.GROUP_COMP_STYLE.TEXT_FULL))
-- Announce who we excluded, if any.
local sitting = A.group:NumSitting()
if sitting == 1 then
msg = msg.." "..format(L["sorter.print.excludedSitting.singular"], A.util:GetMaxGroupsForInstance()+1)
elseif sitting > 1 then
msg = msg.." "..format(L["sorter.print.excludedSitting.plural"], sitting, A.util:GetMaxGroupsForInstance()+1)
end
-- Announce to group or to self.
if A.options.announceChatAlways or (A.options.announceChatPRN and not R.announced) then
SendChatMessage(format("[%s] %s", A.NAME, msg), A.util:GetGroupChannel())
R.announced = true
else
A.console:Print(msg)
end
if A.DEBUG >= 1 then A.console:Debugf(M, "steps=%d seconds=%.1f timeouts=%d", R.stepCount, (time() - R.startTime), R.timeoutCount) end
end
R.lastSortMode = R.sortMode
end
function M:ClearTimeout(resetCount)
if R.timeoutTimer then
M:CancelTimer(R.timeoutTimer)
end
R.timeoutTimer = false
if resetCount then
R.timeoutCount = false
end
end
-- Timeouts can happen for a variety of reasons.
-- Example: While the raid leader's original request to move a player is en
-- route to the server, that player leaves the group or is moved to a different
-- group by someone else.
-- Another example: Good old-fashioned lag.
function M:ScheduleTimeout()
M:ClearTimeout(false)
R.timeoutTimer = M:ScheduleTimer(function ()
M:ClearTimeout(false)
R.timeoutCount = (R.timeoutCount or 0) + 1
if A.DEBUG >= 1 then A.console:Debugf(M, "timeout %d of %d", R.timeoutCount, MAX_TIMEOUTS) end
if R.timeoutCount >= MAX_TIMEOUTS then
M:StopTimedOut()
return
end
A.group:ForceBuildRoster(M, "Timeout")
M:ProcessStep()
end, DELAY_TIMEOUT)
end
|
fix issue where announcing the raid sort wasn't happening if the raid was already sorted initially
|
fix issue where announcing the raid sort wasn't happening if the raid was already sorted initially
|
Lua
|
mit
|
bencvt/FixGroups
|
55889c55383c90e80948d1a22ce59740662ef822
|
modules/alarm.lua
|
modules/alarm.lua
|
local ev = require'ev'
if(not ivar2.timers) then ivar2.timers = {} end
local alarm = function(self, source, destination, time, message)
local hour = time:match'(%d+)[ht]'
local min = time:match'(%d+)m'
local sec = time:match'(%d+)s'
local duration = 0
if(hour) then duration = duration + (hour * 60 * 60) end
if(min) then duration = duration + (min * 60) end
if(sec) then duration = duration + sec end
-- 60 days or more?
local nick = source.nick
if(duration >= (60 * 60 * 24 * 60) or duration == 0) then
return self:Msg(dest, src, "%s: :'(", nick)
end
local id = 'Alarm: ' .. nick
if(self.timers[id]) then
-- message is probably changed.
self.timers[id]:stop(ivar2.Loop)
end
local timer = ev.Timer.new(
function(loop, timer, revents)
if(#message == 0) then message = 'Timer finished.' end
self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.')
end,
duration
)
self:Notice(source.nick, "I'll poke you at %s.", os.date('%Y-%m-%d %X %Z', os.time() + duration))
self.timers[id] = timer
timer:start(ivar2.Loop)
end
return {
PRIVMSG = {
['^!alarm (%S+)%s?(.*)'] = alarm,
['^!timer (%S+)%s?(.*)'] = alarm,
},
}
|
local ev = require'ev'
if(not ivar2.timers) then ivar2.timers = {} end
local alarm = function(self, source, destination, time, message)
local weeks = time:match'(%d+)[w]'
local days = time:match'(%d+)[d]'
local hour = time:match'(%d+)[ht]'
local min = time:match'(%d+)m'
local sec = time:match'(%d+)s'
local duration = 0
if(weeks) then duration = duration + (weeks * 60 * 60 * 24 * 7) end
if(days) then duration = duration + (days * 60 * 60 * 24) end
if(hour) then duration = duration + (hour * 60 * 60) end
if(min) then duration = duration + (min * 60) end
if(sec) then duration = duration + sec end
-- 60 days or more?
local nick = source.nick
if(duration >= (60 * 60 * 24 * 60) or duration == 0) then
return self:Msg(dest, src, "%s: :'(", nick)
end
local id = 'Alarm: ' .. nick
if(self.timers[id]) then
-- message is probably changed.
self.timers[id]:stop(ivar2.Loop)
end
local timer = ev.Timer.new(
function(loop, timer, revents)
if(#message == 0) then message = 'Timer finished.' end
self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.')
end,
duration
)
self:Notice(source.nick, "I'll poke you at %s.", os.date('%Y-%m-%d %X %Z', os.time() + duration))
self.timers[id] = timer
timer:start(ivar2.Loop)
end
return {
PRIVMSG = {
['^!alarm (%S+)%s?(.*)'] = alarm,
['^!timer (%S+)%s?(.*)'] = alarm,
},
}
|
alarm: Support timers lasting for n weeks/days.
|
alarm: Support timers lasting for n weeks/days.
This fixes #27.
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
b5de36f034b0e9e357fca20cdcf2856c4f83f8b2
|
bin/toc2breaks.lua
|
bin/toc2breaks.lua
|
#!/bin/env lua
local project = os.getenv("PROJECT")
local basename = arg[1]
local tocfile = io.open(arg[2], "r")
if not tocfile then return false end
local doc = tocfile:read("*a")
tocfile:close()
local toc = assert(loadstring(doc))()
local yaml = require("yaml")
local meta = yaml.loadpath(arg[3])
local share = "https://owncloud.alerque.com/" .. (meta.owncloudshare and "index.php/s/" .. meta.owncloudshare .. "/download?path=%2F&files=" or "remote.php/webdav/viachristus/" .. project .. "/")
local infofile = io.open(arg[4], "w")
if not infofile then return false end
local infow = function(str, endpar)
str = str or ""
endpar = endpar and "\n" or ""
infofile:write(str .. "\n" .. endpar)
end
infow("TITLE:")
infow(meta.title, true)
infow("SUBTITLE:")
infow(meta.subtitle, true)
for k, v in ipairs(meta.creator) do
if v.role == "author" then meta.author = v.text end
end
infow("AUTHOR:" )
infow(meta.author, true)
infow("ABSTRACT:")
infow(meta.abstract, true)
local labels = {}
if toc[1] then
-- Label the first chunk before we skip to the content
labels[1] = toc[1].label[1]
-- Drop the first TOC entry, the top of the file will be 1
table.remove(toc, 1)
local lastpage = 1
local breaks = { 1 }
-- Get a table of major (more that 2 pages apart) TOC entries
for i, tocentry in pairs(toc) do
local pageno = tonumber(tocentry.pageno)
if pageno > lastpage + 2 then
table.insert(breaks, pageno)
labels[#breaks] = tocentry.label[1]
lastpage = pageno
else
labels[#breaks] = labels[#breaks] .. ", " .. tocentry.label[1]
end
end
-- Convert the table to page rages suitable for pdftk
for i, v in pairs(breaks) do
if i ~= 1 then
breaks[i-1] = breaks[i-1] .. "-" .. v - 1
end
end
breaks[#breaks] = breaks[#breaks] .. "-end"
else
breaks = {}
end
infow("SINGLE PDF:")
local out = basename .. "-app.pdf"
infow(share .. out, true)
-- Output a list suitable for shell script parsing
for i, v in pairs(breaks) do
local n = string.format("%03d", i)
local out = basename .. "-app-" .. n .. ".pdf"
-- Fieds expected by makefile to pass to pdftk
print(v, out)
-- Human readable info for copy/paste to the church app
infow("CHUNK " .. i .. ":")
infow(labels[i])
infow(share .. out, true)
end
infofile:close()
|
#!/bin/env lua
local project = os.getenv("PROJECT")
local basename = arg[1]
local tocfile = io.open(arg[2], "r")
if not tocfile then return false end
local doc = tocfile:read("*a")
tocfile:close()
local toc = assert(loadstring(doc))()
local yaml = require("yaml")
local meta = yaml.loadpath(arg[3])
local share = "https://owncloud.alerque.com/" .. (meta.owncloudshare and "index.php/s/" .. meta.owncloudshare .. "/download?path=%2F&files=" or "remote.php/webdav/viachristus/" .. project .. "/")
local infofile = io.open(arg[4], "w")
if not infofile then return false end
local infow = function(str, endpar)
str = str or ""
endpar = endpar and "\n" or ""
infofile:write(str .. "\n" .. endpar)
end
infow("TITLE:")
infow(meta.title, true)
infow("SUBTITLE:")
infow(meta.subtitle, true)
for k, v in ipairs(meta.creator) do
if v.role == "author" then meta.author = v.text end
end
infow("AUTHOR:" )
infow(meta.author, true)
infow("ABSTRACT:")
infow(meta.abstract, true)
infow("SINGLE PDF:")
local out = basename .. "-app.pdf"
infow(share .. out, true)
local labels = {}
local breaks = {}
if #toc > 0 then
-- Label the first chunk before we skip to the content
labels[1] = toc[1].label[1]
-- Drop the first TOC entry, the top of the file will be 1
table.remove(toc, 1)
local lastpage = 1
breaks = { 1 }
-- Get a table of major (more that 2 pages apart) TOC entries
for i, tocentry in pairs(toc) do
local pageno = tonumber(tocentry.pageno)
if pageno > lastpage + 2 then
table.insert(breaks, pageno)
labels[#breaks] = tocentry.label[1]
lastpage = pageno
else
labels[#breaks] = labels[#breaks] .. ", " .. tocentry.label[1]
end
end
-- Convert the table to page rages suitable for pdftk
for i, v in pairs(breaks) do
if i ~= 1 then
breaks[i-1] = breaks[i-1] .. "-" .. v - 1
end
end
breaks[#breaks] = breaks[#breaks] .. "-end"
end
-- Output a list suitable for shell script parsing
for i, v in pairs(breaks) do
local n = string.format("%03d", i)
local out = basename .. "-app-" .. n .. ".pdf"
-- Fieds expected by makefile to pass to pdftk
print(v, out)
-- Human readable info for copy/paste to the church app
infow("CHUNK " .. i .. ":")
infow(labels[i])
infow(share .. out, true)
end
infofile:close()
|
Fix variable scoping bug introduced by single chapter support if loop
|
Fix variable scoping bug introduced by single chapter support if loop
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
d3f3abb3369efc9b98ca6e7a6295fab6aa58eb56
|
src/lluv/websocket/handshake.lua
|
src/lluv/websocket/handshake.lua
|
-- Code based on https://github.com/lipp/lua-websockets
local sha1 = require'websocket.tools'.sha1
local base64 = require'websocket.tools'.base64
local tinsert = table.insert
local guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
local sec_websocket_accept = function(sec_websocket_key)
local a = sec_websocket_key..guid
local sha1 = sha1(a)
assert((#sha1 % 2) == 0)
return base64.encode(sha1)
end
local http_headers = function(request)
local headers = {}
if not request:match('.*HTTP/1%.1') then
return headers
end
request = request:match('[^\r\n]+\r\n(.*)')
local empty_line
for line in request:gmatch('[^\r\n]*\r\n') do
local name,val = line:match('([^%s]+)%s*:%s*([^\r\n]+)')
if name and val then
name = name:lower()
if not name:match('sec%-websocket') then
val = val:lower()
end
if not headers[name] then
headers[name] = val
else
headers[name] = headers[name]..','..val
end
elseif line == '\r\n' then
empty_line = true
else
assert(false,line..'('..#line..')')
end
end
return headers,request:match('\r\n\r\n(.*)')
end
local upgrade_request = function(req)
local format = string.format
local lines = {
format('GET %s HTTP/1.1',req.uri or ''),
format('Host: %s',req.host),
'Upgrade: websocket',
'Connection: Upgrade',
format('Sec-WebSocket-Key: %s',req.key),
format('Sec-WebSocket-Protocol: %s',table.concat(req.protocols,', ')),
'Sec-WebSocket-Version: 13',
}
if req.origin then
tinsert(lines,string.format('Origin: %s',req.origin))
end
if req.port and req.port ~= 80 then
lines[2] = format('Host: %s:%d',req.host,req.port)
end
tinsert(lines,'\r\n')
return table.concat(lines,'\r\n')
end
local accept_upgrade = function(request,protocols)
local headers = http_headers(request)
if headers['upgrade'] ~= 'websocket' or
not headers['connection'] or
not headers['connection']:match('upgrade') or
headers['sec-websocket-key'] == nil or
headers['sec-websocket-version'] ~= '13' then
return nil,'HTTP/1.1 400 Bad Request\r\n\r\n'
end
local prot
if headers['sec-websocket-protocol'] then
for protocol in headers['sec-websocket-protocol']:gmatch('([^,%s]+)%s?,?') do
for _,supported in ipairs(protocols) do
if supported == protocol then
prot = protocol
break
end
end
if prot then
break
end
end
end
local lines = {
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: '..headers['connection'],
string.format('Sec-WebSocket-Accept: %s',sec_websocket_accept(headers['sec-websocket-key'])),
}
if prot then
tinsert(lines,string.format('Sec-WebSocket-Protocol: %s',prot))
end
tinsert(lines,'\r\n')
return table.concat(lines,'\r\n'),prot
end
return {
sec_websocket_accept = sec_websocket_accept,
http_headers = http_headers,
accept_upgrade = accept_upgrade,
upgrade_request = upgrade_request,
}
|
-- Code based on https://github.com/lipp/lua-websockets
local tools = require'lluv.websocket.tools'
local sha1, base64 = tools.sha1, tools.base64
local guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
local sec_websocket_accept = function(sec_websocket_key)
local a = sec_websocket_key..guid
local sha1 = sha1(a)
assert((#sha1 % 2) == 0)
return base64.encode(sha1)
end
local http_headers = function(request)
local headers = {}
if not request:match('.*HTTP/1%.1') then
return headers
end
request = request:match('[^\r\n]+\r\n(.*)')
local empty_line
for line in request:gmatch('[^\r\n]*\r\n') do
local name,val = line:match('([^%s]+)%s*:%s*([^\r\n]+)')
if name and val then
name = name:lower()
if not name:match('sec%-websocket') then
val = val:lower()
end
if not headers[name] then
headers[name] = val
else
headers[name] = headers[name]..','..val
end
elseif line == '\r\n' then
empty_line = true
else
assert(false,line..'('..#line..')')
end
end
return headers,request:match('\r\n\r\n(.*)')
end
local upgrade_request = function(req)
local format = string.format
local lines = {
format('GET %s HTTP/1.1',req.uri or ''),
format('Host: %s',req.host),
'Upgrade: websocket',
'Connection: Upgrade',
format('Sec-WebSocket-Key: %s',req.key),
format('Sec-WebSocket-Protocol: %s',table.concat(req.protocols,', ')),
'Sec-WebSocket-Version: 13',
}
if req.origin then
lines[#lines + 1] = string.format('Origin: %s',req.origin)
end
if req.port and req.port ~= 80 then
lines[2] = format('Host: %s:%d',req.host,req.port)
end
lines[#lines + 1] = '\r\n'
return table.concat(lines,'\r\n')
end
local accept_upgrade = function(request,protocols)
local headers = http_headers(request)
if headers['upgrade'] ~= 'websocket' or
not headers['connection'] or
not headers['connection']:match('upgrade') or
headers['sec-websocket-key'] == nil or
headers['sec-websocket-version'] ~= '13' then
return nil,'HTTP/1.1 400 Bad Request\r\n\r\n'
end
local prot
if headers['sec-websocket-protocol'] then
for protocol in headers['sec-websocket-protocol']:gmatch('([^,%s]+)%s?,?') do
for _,supported in ipairs(protocols) do
if supported == protocol then
prot = protocol
break
end
end
if prot then
break
end
end
end
local lines = {
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: '..headers['connection'],
string.format('Sec-WebSocket-Accept: %s',sec_websocket_accept(headers['sec-websocket-key'])),
}
if prot then
lines[#lines + 1] = string.format('Sec-WebSocket-Protocol: %s', prot)
end
lines[#lines + 1] = '\r\n'
return table.concat(lines,'\r\n'),prot
end
return {
sec_websocket_accept = sec_websocket_accept,
http_headers = http_headers,
accept_upgrade = accept_upgrade,
upgrade_request = upgrade_request,
}
|
Fix. link to lua-websocket module.
|
Fix. link to lua-websocket module.
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
ac5a0e47f4d48ff1bd04259fdbb4670e09a5f010
|
lua/entities/gmod_wire_expression2/core/http.lua
|
lua/entities/gmod_wire_expression2/core/http.lua
|
/*
Simple HTTP Extension
(McLovin)
*/
E2Lib.RegisterExtension( "http", true )
local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE )
local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE )
local requests = {}
local run_on = {
clk = 0,
ents = {}
}
local function player_can_request( ply )
local preq = requests[ply]
return !preq or
(preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetInt()) or
(!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetInt())
end
__e2setcost( 20 )
e2function void httpRequest( string url )
if !player_can_request( self.player ) or url == "" then return end
requests[self.player] = {
in_progress = true,
t_start = CurTime(),
t_end = 0,
url = url
}
http.Get(
url,
"",
function( args, contents, size )
local ply = args[1]
if !IsValid( ply ) or !ply:IsPlayer() or !requests[ply] then return end
local preq = requests[ply]
preq.t_end = CurTime()
preq.in_progress = false
preq.data = contents or ""
preq.data = string.gsub( preq.data, string.char( 13 ) .. string.char( 10 ), "\n" )
run_on.clk = 1
for ent,eply in pairs( run_on.ents ) do
if IsValid( ent ) and ent.Execute and eply == ply then
ent:Execute()
end
end
run_on.clk = 0
end,
self.player
)
end
__e2setcost( 5 )
e2function number httpCanRequest()
return ( player_can_request( self.player ) ) and 1 or 0
end
e2function number httpClk()
return run_on.clk
end
e2function string httpData()
local preq = requests[self.player]
return preq and preq.data or ""
end
e2function string httpRequestUrl()
local preq = requests[self.player]
return preq and preq.url or ""
end
e2function string httpUrlEncode(string data)
local ndata = string.gsub( data, "[^%w _~%.%-]", function( str )
local nstr = string.format( "%X", string.byte( str ) )
return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr
end )
return string.gsub( ndata, " ", "+" )
end
e2function string httpUrlDecode(string data)
local ndata = string.gsub( data, "+", " " )
return string.gsub( ndata, "(%%%x%x)", function( str )
return string.char( tonumber( string.Right( str, 2 ), 16 ) )
end )
end
e2function void runOnHTTP( number rohttp )
run_on.ents[self.entity] = ( rohttp != 0 ) and self.player or nil
end
registerCallback( "destruct", function( self )
run_on.ents[self.entity] = nil
end )
|
/*
Simple HTTP Extension
(McLovin)
*/
E2Lib.RegisterExtension( "http", true )
local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE )
local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE )
local requests = {}
local run_on = {
clk = 0,
ents = {}
}
local function player_can_request( ply )
local preq = requests[ply]
return !preq or
(preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetInt()) or
(!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetInt())
end
__e2setcost( 20 )
e2function void httpRequest( string url )
if !player_can_request( self.player ) or url == "" then return end
requests[self.player] = {
in_progress = true,
t_start = CurTime(),
t_end = 0,
url = url
}
http.Fetch(
url,
function( body, length, headers, code )
local ply = self.player
if !IsValid( ply ) or !ply:IsPlayer() or !requests[ply] then return end
local preq = requests[ply]
preq.t_end = CurTime()
preq.in_progress = false
preq.data = body or ""
preq.data = string.gsub( preq.data, string.char( 13 ) .. string.char( 10 ), "\n" )
run_on.clk = 1
for ent,eply in pairs( run_on.ents ) do
if IsValid( ent ) and ent.Execute and eply == ply then
ent:Execute()
end
end
run_on.clk = 0
end
)
end
__e2setcost( 5 )
e2function number httpCanRequest()
return ( player_can_request( self.player ) ) and 1 or 0
end
e2function number httpClk()
return run_on.clk
end
e2function string httpData()
local preq = requests[self.player]
return preq and preq.data or ""
end
e2function string httpRequestUrl()
local preq = requests[self.player]
return preq and preq.url or ""
end
e2function string httpUrlEncode(string data)
local ndata = string.gsub( data, "[^%w _~%.%-]", function( str )
local nstr = string.format( "%X", string.byte( str ) )
return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr
end )
return string.gsub( ndata, " ", "+" )
end
e2function string httpUrlDecode(string data)
local ndata = string.gsub( data, "+", " " )
return string.gsub( ndata, "(%%%x%x)", function( str )
return string.char( tonumber( string.Right( str, 2 ), 16 ) )
end )
end
e2function void runOnHTTP( number rohttp )
run_on.ents[self.entity] = ( rohttp != 0 ) and self.player or nil
end
registerCallback( "destruct", function( self )
run_on.ents[self.entity] = nil
end )
|
Fixed httpRequest()
|
Fixed httpRequest()
|
Lua
|
apache-2.0
|
wiremod/wire,mitterdoo/wire,CaptainPRICE/wire,garrysmodlua/wire,sammyt291/wire,plinkopenguin/wiremod,rafradek/wire,notcake/wire,mms92/wire,NezzKryptic/Wire,thegrb93/wire,bigdogmat/wire,immibis/wiremod,dvdvideo1234/wire,Grocel/wire,Python1320/wire
|
e8244099175650a48f53669d41843996c7989902
|
pud/ui/Tooltip.lua
|
pud/ui/Tooltip.lua
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Bar = getClass 'pud.ui.Bar'
-- Tooltip
--
local Tooltip = Class{name='Tooltip',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self._margin = 0
end
}
-- destructor
function Tooltip:destroy()
self:clear()
self._margin = nil
Frame.destroy(self)
end
-- clear the tooltip
function Tooltip:clear()
if self._header1 then
self._header1:destroy()
self._header1 = nil
end
if self._header2 then
self._header2:destroy()
self._header2 = nil
end
if self._icon then
self._icon:destroy()
self._icon = nil
end
if self._lines then
local numLines = #self._lines
for i=1,numLines do
self._lines[i]:destroy()
self._lines[i] = nil
end
self._lines = nil
end
end
-- XXX
-- subclass for entities
-- query entity for icon, name, family, kind, and loop through a list of properties
-- then build tooltip based on these
-- so this class need methods for building the tooltip
--[[
all tooltips have this basic structure:
-------------------------------
| ICON TEXT (usually Name) | }
| TEXT or BLANK SPACE | }- This whole header area is optional
| BLANK SPACE | }
| TEXT or BAR |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| ... |
| TEXT or BAR |
-------------------------------
]]--
-- set icon
function Tooltip:setIcon(icon)
verifyClass('pud.ui.Frame', icon)
if self._icon then self._icon:destroy() end
self._icon = icon
self:_adjustLayout()
self:_drawFB()
end
-- set header line 1
function Tooltip:setHeader1(text)
verifyClass('pud.ui.Text', text)
if self._header1 then self._header1:destroy() end
self._header1 = text
self:_adjustLayout()
self:_drawFB()
end
-- set header line 2
function Tooltip:setHeader2(text)
verifyClass('pud.ui.Text', text)
if self._header2 then self._header2:destroy() end
self._header2 = text
self:_adjustLayout()
self:_drawFB()
end
-- add a Text
function Tooltip:addText(text)
verifyClass('pud.ui.Text', text)
self._addLine(text)
end
-- add a Bar
function Tooltip:addBar(bar)
verifyClass('pud.ui.Bar', bar)
self._addLine(bar)
end
-- add a blank space
function Tooltip:addSpace()
local spacing = self:getSpacing()
if spacing then
local space = Frame(0, 0, 0, spacing)
self:_addLine(space)
end
end
-- add a line to the tooltip
function Tooltip:_addLine(frame)
verifyClass('pud.ui.Frame', frame)
self._lines = self._lines or {}
self._lines[#self._lines + 1] = frame
self:_adjustLayout()
self:_drawFB()
end
-- set the margin between the frame edge and the contents
function Tooltip:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_adjustLayout()
self:_drawFB()
end
function Tooltip:_adjustLayout()
local numLines = self._lines and #self._lines or 0
if self._icon or self._header1 or self._header2 or numLines > 0 then
local width, height = self._margin, self._margin
local x, y = self._x + width, self._y + height
local spacing = self:getSpacing()
if spacing then
if self._icon then
self._icon:setPosition(x, y)
width = width + self._icon:getWidth()
x = self._x + width + spacing
end
local headerWidth = 0
if self._header1 then
self._header1:setPosition(x, y)
headerWidth = self._header1:getWidth()
y = y + spacing
end
if self._header2 then
self._header2:setPosition(x, y)
local h2width = self._header2:getWidth()
headerWidth = headerWidth > h2width and headerWidth or h2width
y = y + spacing
end
width = width + headerWidth
if numLines > 0 then
-- set some blank space if any headers exist
if self._icon or self._header1 or self._header2 then
y = y + spacing
end
x = self._x + self._margin
for i=1,numLines do
local line = self._lines[i]
line:setPosition(x, y)
local lineWidth = line:getWidth()
width = width > lineWidth and width or lineWidth
y = y + spacing
end -- for i=1,num
end -- if self._lines
width = width + self._margin
height = height + self._margin -- XXX: might have an extra spacing
self:setSize(width, height)
end -- if spacing
end -- if self._icon or self._header1 or ...
end
function Tooltip:_getSpacing()
local spacing
local normalStyle = self:getNormalStyle()
if normalStyle then
local font = normalStyle:getFont()
if font then spacing = font:getHeight() end
end
if nil == spacing then warning('Please set Tooltip normal font style.') end
return spacing
end
-- draw in the foreground layer
-- draws over any foreground set in the Style. Usually, you just don't want to
-- set a foreground in the Style.
function Tooltip:_drawForeground()
Frame._drawForeground(self)
if self._icon then self._icon:draw() end
if self._header1 then self._header1:draw() end
if self._header2 then self._header2:draw() end
local numLines = self._lines and #self._lines or 0
if numLines > 0 then
for i=1,numLines do
local line = self._lines[i]
line:draw()
end
end
end
-- the class
return Tooltip
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Bar = getClass 'pud.ui.Bar'
-- Tooltip
--
local Tooltip = Class{name='Tooltip',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self._margin = 0
end
}
-- destructor
function Tooltip:destroy()
self:clear()
self._margin = nil
Frame.destroy(self)
end
-- clear the tooltip
function Tooltip:clear()
if self._header1 then
self._header1:destroy()
self._header1 = nil
end
if self._header2 then
self._header2:destroy()
self._header2 = nil
end
if self._icon then
self._icon:destroy()
self._icon = nil
end
if self._lines then
local numLines = #self._lines
for i=1,numLines do
self._lines[i]:destroy()
self._lines[i] = nil
end
self._lines = nil
end
end
-- XXX
-- subclass for entities
-- query entity for icon, name, family, kind, and loop through a list of properties
-- then build tooltip based on these
-- so this class need methods for building the tooltip
--[[
all tooltips have this basic structure:
-------------------------------
| ICON TEXT (usually Name) | }
| TEXT or BLANK SPACE | }- This whole header area is optional
| BLANK SPACE | }
| TEXT or BAR |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| ... |
| TEXT or BAR |
-------------------------------
]]--
-- set icon
function Tooltip:setIcon(icon)
verifyClass('pud.ui.Frame', icon)
if self._icon then self._icon:destroy() end
self._icon = icon
self:_adjustLayout()
self:_drawFB()
end
-- set header line 1
function Tooltip:setHeader1(text)
verifyClass('pud.ui.Text', text)
if self._header1 then self._header1:destroy() end
self._header1 = text
self:_adjustLayout()
self:_drawFB()
end
-- set header line 2
function Tooltip:setHeader2(text)
verifyClass('pud.ui.Text', text)
if self._header2 then self._header2:destroy() end
self._header2 = text
self:_adjustLayout()
self:_drawFB()
end
-- add a Text
function Tooltip:addText(text)
verifyClass('pud.ui.Text', text)
self._addLine(text)
end
-- add a Bar
function Tooltip:addBar(bar)
verifyClass('pud.ui.Bar', bar)
self._addLine(bar)
end
-- add a blank space
function Tooltip:addSpace()
local spacing = self:getSpacing()
if spacing then
local space = Frame(0, 0, 0, spacing)
self:_addLine(space)
end
end
-- add a line to the tooltip
function Tooltip:_addLine(frame)
verifyClass('pud.ui.Frame', frame)
self._lines = self._lines or {}
self._lines[#self._lines + 1] = frame
self:_adjustLayout()
self:_drawFB()
end
-- set the margin between the frame edge and the contents
function Tooltip:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_adjustLayout()
self:_drawFB()
end
function Tooltip:_adjustLayout()
local numLines = self._lines and #self._lines or 0
if self._icon or self._header1 or self._header2 or numLines > 0 then
local x, y = self._margin, self._margin
local width, height = 0, 0
local spacing = self:getSpacing()
if spacing then
if self._icon then
self._icon:setPosition(x, y)
width = self._icon:getWidth()
x = width + spacing
end
local headerWidth = 0
if self._header1 then
self._header1:setPosition(x, y)
headerWidth = self._header1:getWidth()
y = y + spacing
end
if self._header2 then
self._header2:setPosition(x, y)
local h2width = self._header2:getWidth()
headerWidth = headerWidth > h2width and headerWidth or h2width
y = y + spacing
end
width = width + headerWidth
if numLines > 0 then
-- set some blank space if any headers exist
if self._icon or self._header1 or self._header2 then
y = y + spacing
end
x = self._margin
for i=1,numLines do
local line = self._lines[i]
line:setPosition(x, y)
local lineWidth = line:getWidth()
width = width > lineWidth and width or lineWidth
y = y + spacing
end -- for i=1,num
end -- if self._lines
width = width + self._margin*2
height = height + self._margin*2 -- XXX: might have an extra spacing
self:setSize(width, height)
end -- if spacing
end -- if self._icon or self._header1 or ...
end
function Tooltip:_getSpacing()
local spacing
local normalStyle = self:getNormalStyle()
if normalStyle then
local font = normalStyle:getFont()
if font then spacing = font:getHeight() end
end
if nil == spacing then warning('Please set Tooltip normal font style.') end
return spacing
end
-- draw in the foreground layer
-- draws over any foreground set in the Style. Usually, you just don't want to
-- set a foreground in the Style.
function Tooltip:_drawForeground()
Frame._drawForeground(self)
if self._icon then self._icon:draw() end
if self._header1 then self._header1:draw() end
if self._header2 then self._header2:draw() end
local numLines = self._lines and #self._lines or 0
if numLines > 0 then
for i=1,numLines do
local line = self._lines[i]
line:draw()
end
end
end
-- the class
return Tooltip
|
Revert "fix tooltip drawing relative to position"
|
Revert "fix tooltip drawing relative to position"
This reverts commit e0e5cad0caf3c9dcdbb429c9d0cbc58457b66f33.
|
Lua
|
mit
|
scottcs/wyx
|
956a77911badbe2e7836fdb0b56d5cf8379b0a11
|
server/lua/duplicateMsgFilter.lua
|
server/lua/duplicateMsgFilter.lua
|
--
-- Copyright 2015 Ilkka Oksanen <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an "AS
-- IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
-- express or implied. See the License for the specific language
-- governing permissions and limitations under the License.
--
local reporterUserId = ARGV[1]
local conversationId = ARGV[2]
local msgUserId = ARGV[3]
local msgBody = ARGV[4]
local key = 'conversationbuffer:' .. conversationId
-- Remove trailing whitespace, IRC servers may not conserve it. In
-- that case duplicates would pass the check.
msgBody = string.gsub(msgBody, "^(.-)%s*$", "%1")
local msgFingerprint = msgUserId .. ':' .. msgBody
local existingReporter = redis.call('HGET', key, msgFingerprint)
if (not existingReporter) or existingReporter == reporterUserId then
redis.call('HSET', key, msgFingerprint, reporterUserId)
redis.call('EXPIRE', key, 45)
return false
else
return true
end
|
--
-- Copyright 2015 Ilkka Oksanen <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an "AS
-- IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
-- express or implied. See the License for the specific language
-- governing permissions and limitations under the License.
--
local reporterUserId = ARGV[1]
local conversationId = ARGV[2]
local msgUserId = ARGV[3]
local msgBody = ARGV[4]
local key = 'conversationbuffer:' .. conversationId
-- Remove trailing whitespace, IRC servers may not conserve it. In
-- that case duplicates would pass the check.
msgBody = string.gsub(msgBody, "^(.-)%s*$", "%1")
-- Undo the multiline to single line conversion that IRC backend does
msgBody = string.gsub(msgBody, "\n", " ")
local msgFingerprint = msgUserId .. ':' .. msgBody
local existingReporter = redis.call('HGET', key, msgFingerprint)
if (not existingReporter) or existingReporter == reporterUserId then
redis.call('HSET', key, msgFingerprint, reporterUserId)
redis.call('EXPIRE', key, 45)
return false
else
return true
end
|
Fix the duplicate detection of multi-line IRC messages
|
Fix the duplicate detection of multi-line IRC messages
|
Lua
|
apache-2.0
|
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
|
253215b1ed0d84153c2e7277025596c376c615a0
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm.lua
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm.lua
|
require "lmclient"
local json = require("luci.json")
local lmcf = json.decode(LmClient():query("$LMCF"))
local m, s, v
m = Map("linkmeter", "Alarm Settings",
[[ Select the types of notifications to receive when the alarm is trigged.
Enable an alarm by setting
its threshold to a positive value, or using the button beside it.
Inputting a 'Setpoint' will adjust the Pit setpoint.
Test results can be seen in the <a href="]] ..
luci.dispatcher.build_url("admin/status/syslog/") ..
[[">System Log</a>.
<strong>'Save & Apply' before testing.</strong>
]])
local ESCAPE_HELP = "All special characters (e.g. parens) must be escaped"
if lmcf == nil then
s = m:section(SimpleSection, "_noconfig")
s.template = "linkmeter/noconfig"
return m
end
--
-- Alarm Values
--
s = m:section(TypedSection, "_hmconfig")
s.template = "linkmeter/alarm-section"
s.cfgsections = function(a,b,c)
local retVal = {}
for probe = 1,4 do
retVal[probe] = tostring(probe-1)
end
return retVal
end
s.field = function(self, name)
for k,v in pairs(self.fields) do
if k == name then return v end
end
end
-- probe_lm_* values that are stored in HeaterMeter
local probe_lm_alvals = {}
local function probe_lm_value(self, section)
local retVal = lmcf[self.option .. section]
return retVal and tostring(retVal)
end
local function probe_lm_write(self, section, value)
-- Alarm high/low
if self.option:sub(1,3) == "pal" then
local idx = self.option:sub(-1) == "l" and 1 or 2
idx = idx + 2 * tonumber(section)
while #probe_lm_alvals < idx do
probe_lm_alvals[#probe_lm_alvals+1] = ""
end
probe_lm_alvals[idx] = value
end
lmcf[self.option .. section] = value
end
local PROBE_LM = { "pn", "pcurr", "pall", "palh" }
for _,kv in ipairs(PROBE_LM) do
v = s:option(Value, kv, kv)
v.value = probe_lm_value
v.cfgvalue = probe_lm_value
v.write = probe_lm_write
end
local function saveProbeLm()
if #probe_lm_alvals > 0 then
local alvals = "$LMST,al," .. table.concat(probe_lm_alvals, ",")
LmClient():query(alvals)
end
end
-- probe_conf_* values that are stored in uci
local function probe_conf_value(self, section)
return m:get("alarms", self.option .. section)
end
local function probe_conf_write(self, section, value)
return m:set("alarms", self.option .. section, value)
end
local function probe_conf_remove(self, section)
return m:del("alarms", self.option .. section)
end
local PROBE_CONF = { "emaill", "smsl", "spl", "emailh", "smsh", "sph" }
for _,kv in ipairs(PROBE_CONF) do
v = s:option(Value, kv, kv)
v.cfgvalue = probe_conf_value
v.write = probe_conf_write
v.remove = probe_conf_remove
end
--
-- Email Notifications
--
s = m:section(NamedSection, "alarms", "email", "Email Notifications",
[[Email notifications only work if <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured.]])
v = s:option(Value, "emailtoname", "Recipient name (optional)")
v = s:option(Value, "emailtoaddress", "To email address")
v = s:option(Value, "emailsubject", "Subject")
local msg = s:option(TextValue, "_msg", "Message")
msg.wrap = "off"
msg.rows = 5
msg.rmempty = false
msg.description = ESCAPE_HELP
local MSG_TEMPLATE = "/usr/share/linkmeter/email.txt"
function msg.cfgvalue()
return nixio.fs.readfile(MSG_TEMPLATE) or ""
end
function msg.write(self, section, value)
if value then
value = value:gsub("\r\n", "\n")
if value ~= msg.cfgvalue() then
nixio.fs.writefile(MSG_TEMPLATE, value)
end
end
end
--
-- SMS Notifications
--
s = m:section(NamedSection, "alarms", "sms", "SMS Notifications",
[[SMS notifications only work if <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured.]])
local PROVIDERS = {
{ "AT&T", "txt.att.net", "ATT" },
{ "Bell / Solo", "txt.bellmobility.ca" },
{ "Fido", "sms.fido.ca" },
{ "MTS", "text.mtsmobility.com" },
{ "Nextel", "messaging.nextel.com" },
{ "Plateau", "smsx.plateaugsm.com" },
{ "Rogers", "sms.rogers.com" },
{ "Sprint", "messaging.sprintpcs.com" },
{ "T-Mobile", "tmomail.net" },
{ "Telus / Koodo", "msg.telus.com" },
{ "Verizon", "vtext.com" },
{ "Virgin US", "vmobl.com" },
{ "Virgin Canada", "vmobl.ca" },
{ "Wind Mobile", "txt.windmobile.ca" },
}
local smsto = m:get("alarms", "smstoaddress")
local smsphone, smsprovider = smsto:match("^(%d+)@(.+)$")
v = s:option(Value, "_phone", "Phone number")
v.cfgvalue = function() return smsphone end
v.datatype = "phonedigit"
v = s:option(ListValue, "_provider", "Provider")
for i,p in ipairs(PROVIDERS) do
local key = p[3] or p[1]
v:value(key, p[1])
-- convert the @addr to the provider name
if p[2] == smsprovider then
v.cfgvalue = function () return key end
end
end
v = s:option(Value, "smsmessage", "Message")
v.description = ESCAPE_HELP
--
-- Map Functions
--
m.on_save = function (self)
saveProbeLm()
end
return m
|
require "lmclient"
local json = require("luci.json")
local lmcf = json.decode(LmClient():query("$LMCF"))
local m, s, v
m = Map("linkmeter", "Alarm Settings",
[[ Select the types of notifications to receive when the alarm is trigged.
Enable an alarm by setting
its threshold to a positive value, or using the button beside it.
Inputting a 'Setpoint' will adjust the Pit setpoint.
Test results can be seen in the <a href="]] ..
luci.dispatcher.build_url("admin/status/syslog/") ..
[[">System Log</a>.
<strong>'Save & Apply' before testing.</strong>
]])
local ESCAPE_HELP = "All special characters (e.g. parens) must be escaped"
if lmcf == nil then
s = m:section(SimpleSection, "_noconfig")
s.template = "linkmeter/noconfig"
return m
end
--
-- Alarm Values
--
s = m:section(TypedSection, "_hmconfig")
s.template = "linkmeter/alarm-section"
s.cfgsections = function(a,b,c)
local retVal = {}
for probe = 1,4 do
retVal[probe] = tostring(probe-1)
end
return retVal
end
s.field = function(self, name)
for k,v in pairs(self.fields) do
if k == name then return v end
end
end
-- probe_lm_* values that are stored in HeaterMeter
local probe_lm_alvals = {}
local function probe_lm_value(self, section)
local retVal = lmcf[self.option .. section]
return retVal and tostring(retVal)
end
local function probe_lm_write(self, section, value)
-- Alarm high/low
if self.option:sub(1,3) == "pal" then
local idx = self.option:sub(-1) == "l" and 1 or 2
idx = idx + 2 * tonumber(section)
while #probe_lm_alvals < idx do
probe_lm_alvals[#probe_lm_alvals+1] = ""
end
probe_lm_alvals[idx] = value
end
lmcf[self.option .. section] = value
end
local PROBE_LM = { "pn", "pcurr", "pall", "palh" }
for _,kv in ipairs(PROBE_LM) do
v = s:option(Value, kv, kv)
v.value = probe_lm_value
v.cfgvalue = probe_lm_value
v.write = probe_lm_write
end
local function saveProbeLm()
if #probe_lm_alvals > 0 then
local alvals = "$LMST,al," .. table.concat(probe_lm_alvals, ",")
LmClient():query(alvals)
end
end
-- probe_conf_* values that are stored in uci
local function probe_conf_value(self, section)
return m:get("alarms", self.option .. section)
end
local function probe_conf_write(self, section, value)
return m:set("alarms", self.option .. section, value)
end
local function probe_conf_remove(self, section)
return m:del("alarms", self.option .. section)
end
local PROBE_CONF = { "emaill", "smsl", "spl", "emailh", "smsh", "sph" }
for _,kv in ipairs(PROBE_CONF) do
v = s:option(Value, kv, kv)
v.cfgvalue = probe_conf_value
v.write = probe_conf_write
v.remove = probe_conf_remove
end
--
-- Email Notifications
--
s = m:section(NamedSection, "alarms", "email", "Email Notifications",
[[Email notifications only work if <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured.]])
v = s:option(Value, "emailtoname", "Recipient name (optional)")
v = s:option(Value, "emailtoaddress", "To email address")
v = s:option(Value, "emailsubject", "Subject")
local msg = s:option(TextValue, "_msg", "Message")
msg.wrap = "off"
msg.rows = 5
msg.rmempty = false
msg.description = ESCAPE_HELP
local MSG_TEMPLATE = "/usr/share/linkmeter/email.txt"
function msg.cfgvalue()
return nixio.fs.readfile(MSG_TEMPLATE) or ""
end
function msg.write(self, section, value)
if value then
value = value:gsub("\r\n", "\n")
if value ~= msg.cfgvalue() then
nixio.fs.writefile(MSG_TEMPLATE, value)
end
end
end
--
-- SMS Notifications
--
s = m:section(NamedSection, "alarms", "sms", "SMS Notifications",
[[SMS notifications only work if <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured.]])
local PROVIDERS = {
{ "AT&T", "txt.att.net" },
{ "Bell / Solo", "txt.bellmobility.ca" },
{ "Fido", "sms.fido.ca" },
{ "MTS", "text.mtsmobility.com" },
{ "Nextel", "messaging.nextel.com" },
{ "Plateau", "smsx.plateaugsm.com" },
{ "Rogers", "sms.rogers.com" },
{ "Sprint", "messaging.sprintpcs.com" },
{ "T-Mobile", "tmomail.net" },
{ "Telus / Koodo", "msg.telus.com" },
{ "Verizon", "vtext.com" },
{ "Virgin US", "vmobl.com" },
{ "Virgin Canada", "vmobl.ca" },
{ "Wind Mobile", "txt.windmobile.ca" },
{ "Other", "other" }
}
local function split_smsto()
local smsto = m:get("alarms", "smstoaddress")
return smsto:match("^(%d+)@(.+)$")
end
local smsprovider_write = function(self, section, value)
if value ~= "other" then
local smsphone, _ = split_smsto()
m:set("alarms", "smstoaddress", smsphone .. "@" .. value)
end
end
v = s:option(Value, "_phone", "Phone number")
v.datatype = "phonedigit"
v.cfgvalue = function()
local smsphone, _ = split_smsto()
return smsphone
end
v.write = function(self, section, value)
local _, smsprovider = split_smsto()
m:set("alarms", "smstoaddress", value .. "@" .. smsprovider)
end
v = s:option(ListValue, "_provider", "Provider")
for _,p in ipairs(PROVIDERS) do
v:value(p[2], p[1])
end
v.cfgvalue = function ()
local _, smsprovider = split_smsto()
for _,p in ipairs(PROVIDERS) do
if p[2] == smsprovider then
return smsprovider
end
end
return "other"
end
v.write = smsprovider_write
v = s:option(Value, "_provider_other", "Other Provider")
v:depends("linkmeter.alarms._provider", "other")
v.cfgvalue = function ()
local _, smsprovider = split_smsto()
return smsprovider
end
v.write = smsprovider_write
v = s:option(Value, "smsmessage", "Message")
v.description = ESCAPE_HELP
--
-- Map Functions
--
m.on_save = function (self)
saveProbeLm()
end
return m
|
[lm] Fix provider not saving properly and add Other provider
|
[lm] Fix provider not saving properly and add Other provider
|
Lua
|
mit
|
kdakers80/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter
|
6880b634eea062e042555c2baa7883cc79e50444
|
UCDsql/mysql.lua
|
UCDsql/mysql.lua
|
-- Have to make this a normal person with ability to do everything but delete, truncate, drop, empty etc
local dbname = "mta"
local host = "ucdmta.com"
local usr = "root"
local passwd = "Network.114"
db = Connection("mysql", "dbname="..dbname..";host="..host..";port=3306", usr, passwd)
forum = Connection("mysql", "dbname=forum;host="..host..";port=3306", usr, passwd)
function returnConnection()
if (not db) then
outputDebugString("Connection to the MySQL database [via ucdmta.com:3306] failed! Trying noki.zorque.xyz:3306...")
db = dbConnect("mysql", "dbname=mta;host=noki.zorque.xyz;port=3306", "root", "Network.114")
if (not db) then
outputDebugString("Connection to the MySQL database [via noki.zorque.xyz:3306] failed! Trying 192.168.0.2:3306...")
else
outputDebugString("Connection to the MySQL database [via 192.168.0.2:3306] successful!")
end
return
end
outputDebugString("Connection to the MySQL database [via ucdmta.com:3306] successful!")
end
addEventHandler("onResourceStart", resourceRoot, returnConnection)
function getConnection()
if (db) then
return db
end
return false
end
function getForumDatabase()
return forum
end
|
-- Have to make this a normal person with ability to do everything but delete, truncate, drop, empty etc
local dbname = "mta"
local host = "ucdmta.com"
local usr = "root"
local passwd = "Network.114"
db = Connection("mysql", "dbname="..dbname..";host="..host..";port=3306", usr, passwd)
forum = Connection("mysql", "dbname=forum;host="..host..";port=3306", usr, passwd)
function returnConnection()
if (not db) then
outputDebugString("Connection to the MySQL database [via ucdmta.com:3306] failed! Trying noki.zorque.xyz:3306...")
db = Connection("mysql", "dbname=mta;host=noki.zorque.xyz;port=3306", "root", "Network.114")
if (not db) then
outputDebugString("Connection to the MySQL database [via noki.zorque.xyz:3306] failed! Trying 192.168.0.2:3306...")
db = Connection("mysql", "dbname=mta;host=192.168.0.2;port=3306", "root", "Network.114")
if (not db) then
outputDebugString("Connection to the MySQL database [via 192.168.0.2:3306] failed!")
else
outputDebugString("Connection to the MySQL database [via 192.168.0.2:3306] successful!")
end
return
else
outputDebugString("Connection to the MySQL database [via noki.zorque.xyz:3306] successful!")
end
return
end
outputDebugString("Connection to the MySQL database [via ucdmta.com:3306] successful!")
end
addEventHandler("onResourceStart", resourceRoot, returnConnection)
function getConnection()
if (db) then
return db
end
return false
end
function getForumDatabase()
return forum
end
|
UCDsql
|
UCDsql
- Fixed it again lol
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
7ba3a1695fb6bdad14ad445fcc25e060b4f4fa35
|
entities/mouse_action.lua
|
entities/mouse_action.lua
|
local MouseAction = Class('MouseAction')
function MouseAction:initialize(game)
self.hoverX = 0
self.hoverY = 0
self.canvasX = 0
self.canvasY = 0
self.game = game
end
function MouseAction:mousemoved(mx, my, dx, dy, istouch)
local game = self.game
mx, my = game.camera:worldCoords(mx, my, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
self.canvasX, self.canvasY = -mx, -my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight * (3/2)
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end
-- @Cleanup This shouldn't be in here, send help
function MouseAction:clickEnemy(x, y)
local game = self.game
local enemy = game:getEnemy(x, y)
local upX, upY = x, y + 1
local downX, downY = x, y - 1
local leftX, leftY = x - 1, y
local rightX, rightY = x + 1, y
local isDead = enemy:hurt()
if isDead then
if enemy.stage == enemy.stages.LARGE then
if game:isShipTile(upX, upY) then
game:addEnemy(upX, upY)
end
if game:isShipTile(downX, downY) then
game:addEnemy(downX, downY)
end
if game:isShipTile(leftX, leftY) then
game:addEnemy(leftX, leftY)
end
if game:isShipTile(rightX, rightY) then
game:addEnemy(rightX, rightY)
end
end
game.enemies[x][y] = nil
local ex, ey = game:gridToScreen(x, y)
local cx, cy = game.camera:cameraCoords(ex, ey)
Signal.emit('enemyDeath', enemy.stage, Vector(cx, cy))
else
Signal.emit("Enemy Hurt")
end
end
function MouseAction:mousepressed(mx, my)
local game = self.game
-- Clicking on enemy
if game:hasEnemy(self.hoverX, self.hoverY) and game.currentRoom == game:getRoom(self.hoverX, self.hoverY) then
self:clickEnemy(self.hoverX, self.hoverY)
end
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local powerGrid = game:getPowerGrid(x, y)
if powerGrid then
local isHovered = game:pointInsideRect(self.canvasX, self.canvasY, powerGrid.screenX + powerGrid.hitboxX, powerGrid.screenY + powerGrid.hitboxY, powerGrid.hitboxWidth, powerGrid.hitboxHeight)
if isHovered then
if powerGrid.roomHash == game.currentRoom then
powerGrid:activate()
end
end
end
local turret = game:getTurret(x, y)
if turret then
local isHovered = game:pointInsideRect(self.canvasX, self.canvasY, turret.screenX + turret.hitboxX, turret.screenY + turret.hitboxY, turret.hitboxWidth, turret.hitboxHeight)
if isHovered then
if turret.roomHash == game.currentRoom then
turret:activate()
end
end
end
end
end
end
return MouseAction
|
local MouseAction = Class('MouseAction')
function MouseAction:initialize(game)
self.hoverX = 0
self.hoverY = 0
self.canvasX = 0
self.canvasY = 0
self.game = game
end
function MouseAction:mousemoved(mx, my, dx, dy, istouch)
local game = self.game
mx, my = game.camera:worldCoords(mx, my, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
self.canvasX, self.canvasY = -mx, -my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight * (3/2)
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end
-- @Cleanup This shouldn't be in here, send help
function MouseAction:clickEnemy(x, y)
local game = self.game
local enemy = game:getEnemy(x, y)
local upX, upY = x, y + 1
local downX, downY = x, y - 1
local leftX, leftY = x - 1, y
local rightX, rightY = x + 1, y
local isDead = enemy:hurt()
if isDead then
if enemy.stage == enemy.stages.LARGE then
if game:isShipTile(upX, upY) then
game:addEnemy(upX, upY)
end
if game:isShipTile(downX, downY) then
game:addEnemy(downX, downY)
end
if game:isShipTile(leftX, leftY) then
game:addEnemy(leftX, leftY)
end
if game:isShipTile(rightX, rightY) then
game:addEnemy(rightX, rightY)
end
end
game.enemies[x][y] = nil
-- do transformations from room bounding box function
-- then subtract camera position, and add half canvas size
local screenX, screenY = game:gridToScreen(x-1, y-1)
-- move screenX and screenY to the center of the tile face
screenX = screenX + game.emptyTile:getWidth()/2
screenY = screenY + game.emptyTile:getHeight()*3/2
--local ex, ey = game:gridToScreen(x, y)
--local cx, cy = game.camera:cameraCoords(ex, ey)
screenX = screenX - game.camera.x + CANVAS_WIDTH/2
screenY = screenY - game.camera.y + CANVAS_HEIGHT/2
-- fudge
screenX = screenX + CANVAS_WIDTH/2 - 15
screenY = screenY - 65
Signal.emit('enemyDeath', enemy.stage, Vector(screenX, screenY))
else
Signal.emit("Enemy Hurt")
end
end
function MouseAction:mousepressed(mx, my)
local game = self.game
-- Clicking on enemy
if game:hasEnemy(self.hoverX, self.hoverY) and game.currentRoom == game:getRoom(self.hoverX, self.hoverY) then
self:clickEnemy(self.hoverX, self.hoverY)
end
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local powerGrid = game:getPowerGrid(x, y)
if powerGrid then
local isHovered = game:pointInsideRect(self.canvasX, self.canvasY, powerGrid.screenX + powerGrid.hitboxX, powerGrid.screenY + powerGrid.hitboxY, powerGrid.hitboxWidth, powerGrid.hitboxHeight)
if isHovered then
if powerGrid.roomHash == game.currentRoom then
powerGrid:activate()
end
end
end
local turret = game:getTurret(x, y)
if turret then
local isHovered = game:pointInsideRect(self.canvasX, self.canvasY, turret.screenX + turret.hitboxX, turret.screenY + turret.hitboxY, turret.hitboxWidth, turret.hitboxHeight)
if isHovered then
if turret.roomHash == game.currentRoom then
turret:activate()
end
end
end
end
end
end
return MouseAction
|
fixed gibs positioning
|
fixed gibs positioning
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
734c5489da65b15cae2c9a25184af0ab67703f2c
|
src/tbox/micro.lua
|
src/tbox/micro.lua
|
-- add target
target("tbox")
-- make as a static library
set_kind("static")
-- add defines
add_defines("__tb_prefix__=\"tbox\"")
-- set the auto-generated config.h
set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)")
add_configfiles("tbox.config.h.in")
-- add include directories
add_includedirs("..", {public = true})
add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true})
-- add the header files for installing
add_headerfiles("../(tbox/**.h)|**/impl/**.h")
add_headerfiles("../(tbox/prefix/**/prefix.S)")
add_headerfiles("../(tbox/math/impl/*.h)")
add_headerfiles("../(tbox/utils/impl/*.h)")
add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"})
-- add options
add_options("info", "float", "wchar", "micro", "coroutine")
-- add the source files
add_files("tbox.c")
add_files("libc/string/memset.c")
add_files("libc/string/memmov.c")
add_files("libc/string/memcpy.c")
add_files("libc/string/strstr.c")
add_files("libc/string/strdup.c")
add_files("libc/string/strlen.c")
add_files("libc/string/strnlen.c")
add_files("libc/string/strcmp.c")
add_files("libc/string/strncmp.c")
add_files("libc/string/stricmp.c")
add_files("libc/string/strnicmp.c")
add_files("libc/string/strlcpy.c")
add_files("libc/string/strncpy.c")
add_files("libc/stdio/vsnprintf.c")
add_files("libc/stdio/snprintf.c")
add_files("libc/stdio/printf.c")
add_files("libc/stdlib/stdlib.c")
add_files("libc/impl/libc.c")
add_files("libm/impl/libm.c")
add_files("math/impl/math.c")
add_files("utils/used.c")
add_files("utils/bits.c")
add_files("utils/trace.c")
add_files("utils/singleton.c")
add_files("memory/allocator.c")
add_files("memory/native_allocator.c")
add_files("memory/static_allocator.c")
add_files("memory/impl/static_large_allocator.c")
add_files("memory/impl/memory.c")
add_files("network/ipv4.c")
add_files("network/ipv6.c")
add_files("network/ipaddr.c")
add_files("network/impl/network.c")
add_files("platform/page.c")
add_files("platform/time.c")
add_files("platform/file.c")
add_files("platform/path.c")
add_files("platform/sched.c")
add_files("platform/print.c")
add_files("platform/thread.c")
add_files("platform/socket.c")
add_files("platform/addrinfo.c")
add_files("platform/poller.c")
add_files("platform/native_memory.c")
add_files("platform/impl/sockdata.c")
add_files("platform/impl/platform.c")
add_files("container/iterator.c")
add_files("container/list_entry.c")
add_files("container/single_list_entry.c")
-- add the source files for debug mode
if is_mode("debug") then
add_files("utils/dump.c")
add_files("memory/impl/prefix.c")
add_files("platform/backtrace.c")
end
-- add the source files for float
if has_config("float") then
add_files("libm/isinf.c")
add_files("libm/isinff.c")
add_files("libm/isnan.c")
add_files("libm/isnanf.c")
end
-- add the source for the windows
if is_os("windows") then
add_files("libc/stdlib/mbstowcs.c")
add_files("platform/dynamic.c")
add_files("platform/windows/interface/ws2_32.c")
add_files("platform/windows/interface/mswsock.c")
add_files("platform/windows/interface/kernel32.c")
if is_mode("debug") then
add_files("platform/windows/interface/dbghelp.c")
end
end
-- add the source files for coroutine
if has_config("coroutine") then
add_files("coroutine/stackless/*.c")
add_files("coroutine/impl/stackless/*.c")
end
-- check interfaces
check_interfaces()
|
-- add target
target("tbox")
-- make as a static library
set_kind("static")
-- add defines
add_defines("__tb_prefix__=\"tbox\"")
-- set the auto-generated config.h
set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)")
add_configfiles("tbox.config.h.in")
-- add include directories
add_includedirs("..", {public = true})
add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true})
-- add the header files for installing
add_headerfiles("../(tbox/**.h)|**/impl/**.h")
add_headerfiles("../(tbox/prefix/**/prefix.S)")
add_headerfiles("../(tbox/math/impl/*.h)")
add_headerfiles("../(tbox/utils/impl/*.h)")
add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"})
-- add options
add_options("info", "float", "wchar", "micro", "coroutine")
-- add the source files
add_files("tbox.c")
add_files("libc/string/memset.c")
add_files("libc/string/memmov.c")
add_files("libc/string/memcpy.c")
add_files("libc/string/strstr.c")
add_files("libc/string/strdup.c")
add_files("libc/string/strlen.c")
add_files("libc/string/strnlen.c")
add_files("libc/string/strcmp.c")
add_files("libc/string/strncmp.c")
add_files("libc/string/stricmp.c")
add_files("libc/string/strnicmp.c")
add_files("libc/string/strlcpy.c")
add_files("libc/string/strncpy.c")
add_files("libc/stdio/vsnprintf.c")
add_files("libc/stdio/snprintf.c")
add_files("libc/stdio/printf.c")
add_files("libc/stdlib/stdlib.c")
add_files("libc/impl/libc.c")
add_files("libm/impl/libm.c")
add_files("math/impl/math.c")
add_files("utils/used.c")
add_files("utils/bits.c")
add_files("utils/trace.c")
add_files("utils/singleton.c")
add_files("memory/allocator.c")
add_files("memory/native_allocator.c")
add_files("memory/static_allocator.c")
add_files("memory/impl/static_large_allocator.c")
add_files("memory/impl/memory.c")
add_files("network/ipv4.c")
add_files("network/ipv6.c")
add_files("network/ipaddr.c")
add_files("network/impl/network.c")
add_files("platform/page.c")
add_files("platform/time.c")
add_files("platform/file.c")
add_files("platform/path.c")
add_files("platform/sched.c")
add_files("platform/print.c")
add_files("platform/thread.c")
add_files("platform/socket.c")
add_files("platform/addrinfo.c")
add_files("platform/poller.c")
add_files("platform/native_memory.c")
add_files("platform/impl/sockdata.c")
add_files("platform/impl/platform.c")
add_files("container/iterator.c")
add_files("container/list_entry.c")
add_files("container/single_list_entry.c")
-- add the source files for debug mode
if is_mode("debug") then
add_files("utils/dump.c")
add_files("memory/impl/prefix.c")
add_files("platform/backtrace.c")
end
-- add the source files for float
if has_config("float") then
add_files("libm/isinf.c")
add_files("libm/isinff.c")
add_files("libm/isnan.c")
add_files("libm/isnanf.c")
end
-- add the source for the windows
if is_os("windows") then
add_files("libc/stdlib/mbstowcs.c")
add_files("platform/dynamic.c")
add_files("platform/atomic64.c")
add_files("platform/windows/windows.c")
add_files("platform/windows/interface/ws2_32.c")
add_files("platform/windows/interface/mswsock.c")
add_files("platform/windows/interface/kernel32.c")
if is_mode("debug") then
add_files("platform/windows/interface/dbghelp.c")
end
end
-- add the source files for coroutine
if has_config("coroutine") then
add_files("coroutine/stackless/*.c")
add_files("coroutine/impl/stackless/*.c")
end
-- check interfaces
check_interfaces()
|
fix xmake.lua for micro mode
|
fix xmake.lua for micro mode
|
Lua
|
apache-2.0
|
waruqi/tbox,tboox/tbox,waruqi/tbox,tboox/tbox
|
6c0c4ada9d447cd3e1cc344e14ca02bac2578266
|
stdlib/gui/gui.lua
|
stdlib/gui/gui.lua
|
--- Gui module
-- @module Gui
require 'stdlib/event/event'
Gui = {}
-- Factorio's gui events are so monolithic we need a special event system for it.
Gui.Event = {
_registry = {}
}
--- Registers a function for a given event and matching gui element pattern
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when event is triggered
-- @return #Gui.Event
function Gui.Event.register(event, gui_element_pattern, handler)
fail_if_missing(event, "missing event name argument")
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
if type(gui_element_pattern) == "string" then
gui_element_pattern = tostring(gui_element_pattern)
end
if not Gui.Event._registry[event] then
Gui.Event._registry[event] = {}
end
Gui.Event._registry[event][gui_element_pattern] = handler;
-- Use custom Gui event dispatcher to pass off the event to the correct sub-handler
Event.register(event, Gui.Event.dispatch)
return Gui.Event
end
--- Calls the registered handlers
-- @param event LuaEvent as created by game.raise_event
function Gui.Event.dispatch(event)
fail_if_missing(event, "missing event argument")
local gui_element = event.element
if gui_element and gui_element.valid then
for gui_element_pattern, handler in pairs(Gui.Event._registry[event.name]) do
local match_str = string.match(gui_element.name, gui_element_pattern)
if match_str ~= nil then
local new_event = { tick = event.tick, name = event.name, _handler = handler, match = match_str, element = gui_element, player_index = event.player_index , _event = event}
if event.name == defines.events.on_gui_checked_state_changed then new_event.state = gui_element.state end
if event.name == defines.events.on_gui_text_changed then new_event.text = gui_element.text end
local success, err = pcall(handler, new_event)
if not success then
Game.print_all(err)
end
end
end
end
end
--- Removes the handler with matching gui element pattern from the event
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to remove the handler for
-- @return #Gui
function Gui.Event.remove(event, gui_element_pattern)
fail_if_missing(event, "missing event argument")
fail_if_missing(gui_element_pattern, "missing gui_element_pattern argument")
if Gui.Event._registry[event] then
if Gui.Event._registry[event][gui_element_pattern] then
table.remove(Gui.Event._registry[event], gui_element_pattern)
end
if #Gui.Event._registry[event] == 0 then
Gui.Event._registry[event] = nil
script.on_event(event, nil)
end
end
return Gui
end
--- Registers a function for a given gui element name or pattern when the element is clicked
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element is clicked
-- @return #Gui
function Gui.on_click(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_click, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element checked state changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element checked state changes
-- @return #Gui
function Gui.on_checked_state_changed(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_checked_state_changed, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element text changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element text changes
-- @return #Gui
function Gui.on_text_changed(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_text_changed, gui_element_pattern, handler)
return Gui
end
|
--- Gui module
-- @module Gui
require 'stdlib/event/event'
Gui = {}
-- Factorio's gui events are so monolithic we need a special event system for it.
Gui.Event = {
_registry = {}
}
--- Registers a function for a given event and matching gui element pattern
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when event is triggered
-- @return #Gui.Event
function Gui.Event.register(event, gui_element_pattern, handler)
fail_if_missing(event, "missing event name argument")
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
if type(gui_element_pattern) == "string" then
gui_element_pattern = tostring(gui_element_pattern)
end
if not Gui.Event._registry[event] then
Gui.Event._registry[event] = {}
end
Gui.Event._registry[event][gui_element_pattern] = handler;
-- Use custom Gui event dispatcher to pass off the event to the correct sub-handler
Event.register(event, Gui.Event.dispatch)
return Gui.Event
end
--- Calls the registered handlers
-- @param event LuaEvent as created by game.raise_event
function Gui.Event.dispatch(event)
fail_if_missing(event, "missing event argument")
local gui_element = event.element
if gui_element and gui_element.valid then
for gui_element_pattern, handler in pairs(Gui.Event._registry[event.name]) do
local match_str = string.match(gui_element.name, gui_element_pattern)
if match_str ~= nil then
local new_event = { tick = event.tick, name = event.name, _handler = handler, match = match_str, element = gui_element, player_index = event.player_index , _event = event}
if event.name == defines.events.on_gui_checked_state_changed then new_event.state = gui_element.state end
if event.name == defines.events.on_gui_text_changed then new_event.text = gui_element.text end
local success, err = pcall(handler, new_event)
if not success then
Game.print_all(err)
end
end
end
end
end
--- Removes the handler with matching gui element pattern from the event
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to remove the handler for
-- @return #Gui
function Gui.Event.remove(event, gui_element_pattern)
fail_if_missing(event, "missing event argument")
fail_if_missing(gui_element_pattern, "missing gui_element_pattern argument")
local function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
if Gui.Event._registry[event] then
if Gui.Event._registry[event][gui_element_pattern] then
Gui.Event._registry[event][gui_element_pattern] = nil
end
if tablelength(Gui.Event._registry[event]) == 0 then
Gui.Event._registry[event] = nil
script.on_event(event, nil)
end
end
return Gui
end
--- Registers a function for a given gui element name or pattern when the element is clicked
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element is clicked
-- @return #Gui
function Gui.on_click(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_click, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element checked state changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element checked state changes
-- @return #Gui
function Gui.on_checked_state_changed(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_checked_state_changed, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element text changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element text changes
-- @return #Gui
function Gui.on_text_changed(gui_element_pattern, handler)
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
fail_if_missing(handler, "missing function handler argument")
Gui.Event.register(defines.events.on_gui_text_changed, gui_element_pattern, handler)
return Gui
end
|
Fixed incorrect behavior in Gui.Event.remove
|
Fixed incorrect behavior in Gui.Event.remove
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
dcc3a22759f59aa70d79f29978824241f0129ef4
|
stdlib/gui/gui.lua
|
stdlib/gui/gui.lua
|
--- Gui module
-- @module Gui
require 'stdlib/event/event'
Gui = {}
-- Factorio's gui events are so monolithic we need a special event system for it.
Gui.Event = {
_registry = {}
}
--- Registers a function for a given event and matching gui element pattern
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when event is triggered
-- @return #Gui.Event
function Gui.Event.register(event, gui_element_pattern, handler)
fail_if_missing(event, "missing event name argument")
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
if type(gui_element_pattern) ~= "string" then
error("gui_element_pattern argument must be a string")
end
if handler == nil then
Gui.Event.remove(event, gui_element_pattern)
return Gui.Event
end
if not Gui.Event._registry[event] then
Gui.Event._registry[event] = {}
end
Gui.Event._registry[event][gui_element_pattern] = handler
-- Use custom Gui event dispatcher to pass off the event to the correct sub-handler
Event.register(event, Gui.Event.dispatch)
return Gui.Event
end
--- Calls the registered handlers
-- @param event LuaEvent as created by game.raise_event
function Gui.Event.dispatch(event)
fail_if_missing(event, "missing event argument")
local gui_element = event.element
if gui_element and gui_element.valid then
for gui_element_pattern, handler in pairs(Gui.Event._registry[event.name]) do
local match_str = string.match(gui_element.name, gui_element_pattern)
if match_str ~= nil then
local new_event = { tick = event.tick, name = event.name, _handler = handler, match = match_str, element = gui_element, player_index = event.player_index , _event = event}
if event.name == defines.events.on_gui_checked_state_changed then new_event.state = gui_element.state end
if event.name == defines.events.on_gui_text_changed then new_event.text = gui_element.text end
local success, err = pcall(handler, new_event)
if not success then
Game.print_all(err)
end
end
end
end
end
--- Removes the handler with matching gui element pattern from the event
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to remove the handler for
-- @return #Gui.Event
function Gui.Event.remove(event, gui_element_pattern)
fail_if_missing(event, "missing event argument")
fail_if_missing(gui_element_pattern, "missing gui_element_pattern argument")
if type(gui_element_pattern) ~= "string" then
error("gui_element_pattern argument must be a string")
end
local function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
if Gui.Event._registry[event] then
if Gui.Event._registry[event][gui_element_pattern] then
Gui.Event._registry[event][gui_element_pattern] = nil
end
if tablelength(Gui.Event._registry[event]) == 0 then
Gui.Event._registry[event] = nil
script.on_event(event, nil)
end
end
return Gui.Event
end
--- Registers a function for a given gui element name or pattern when the element is clicked
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element is clicked
-- @return #Gui
function Gui.on_click(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_click, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element checked state changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element checked state changes
-- @return #Gui
function Gui.on_checked_state_changed(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_checked_state_changed, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element text changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element text changes
-- @return #Gui
function Gui.on_text_changed(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_text_changed, gui_element_pattern, handler)
return Gui
end
|
--- Gui module
-- @module Gui
require 'stdlib/event/event'
Gui = {}
-- Factorio's gui events are so monolithic we need a special event system for it.
Gui.Event = {
_registry = {}
}
--- Registers a function for a given event and matching gui element pattern
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when event is triggered
-- @return #Gui.Event
function Gui.Event.register(event, gui_element_pattern, handler)
fail_if_missing(event, "missing event name argument")
fail_if_missing(gui_element_pattern, "missing gui name or pattern argument")
if type(gui_element_pattern) ~= "string" then
error("gui_element_pattern argument must be a string")
end
if handler == nil then
Gui.Event.remove(event, gui_element_pattern)
return Gui.Event
end
if not Gui.Event._registry[event] then
Gui.Event._registry[event] = {}
end
Gui.Event._registry[event][gui_element_pattern] = handler
-- Use custom Gui event dispatcher to pass off the event to the correct sub-handler
Event.register(event, Gui.Event.dispatch)
return Gui.Event
end
--- Calls the registered handlers
-- @param event LuaEvent as created by game.raise_event
function Gui.Event.dispatch(event)
fail_if_missing(event, "missing event argument")
local gui_element = event.element
if gui_element and gui_element.valid then
local gui_element_name = gui_element.name;
local gui_element_state = nil;
local gui_element_text = nil;
if event.name == defines.events.on_gui_checked_state_changed then
gui_element_state = gui_element.state
end
if event.name == defines.events.on_gui_text_changed then
gui_element_text = gui_element.text
end
for gui_element_pattern, handler in pairs(Gui.Event._registry[event.name]) do
local match_str = string.match(gui_element_name, gui_element_pattern)
if match_str ~= nil then
local new_event = { tick = event.tick, name = event.name, _handler = handler, match = match_str, element = gui_element, state=gui_element_state, text=gui_element_text, player_index = event.player_index , _event = event}
local success, err = pcall(handler, new_event)
if not success then
Game.print_all(err)
end
end
end
end
end
--- Removes the handler with matching gui element pattern from the event
-- @param event Valid values are defines.event.on_gui_*
-- @param gui_element_pattern the name or string regular expression to remove the handler for
-- @return #Gui.Event
function Gui.Event.remove(event, gui_element_pattern)
fail_if_missing(event, "missing event argument")
fail_if_missing(gui_element_pattern, "missing gui_element_pattern argument")
if type(gui_element_pattern) ~= "string" then
error("gui_element_pattern argument must be a string")
end
local function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
if Gui.Event._registry[event] then
if Gui.Event._registry[event][gui_element_pattern] then
Gui.Event._registry[event][gui_element_pattern] = nil
end
if tablelength(Gui.Event._registry[event]) == 0 then
Gui.Event._registry[event] = nil
script.on_event(event, nil)
end
end
return Gui.Event
end
--- Registers a function for a given gui element name or pattern when the element is clicked
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element is clicked
-- @return #Gui
function Gui.on_click(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_click, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element checked state changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element checked state changes
-- @return #Gui
function Gui.on_checked_state_changed(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_checked_state_changed, gui_element_pattern, handler)
return Gui
end
--- Registers a function for a given gui element name or pattern when the element text changes
-- @param gui_element_pattern the name or string regular expression to match the gui element
-- @param handler Function to call when gui element text changes
-- @return #Gui
function Gui.on_text_changed(gui_element_pattern, handler)
Gui.Event.register(defines.events.on_gui_text_changed, gui_element_pattern, handler)
return Gui
end
|
Fixed error if GUI element is destroyed by any of it's handlers during the event dispatch loop.
|
Fixed error if GUI element is destroyed by any of it's handlers during the event dispatch loop.
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
e0f51dd5e9e67f52e32d585f966853ab562554a4
|
profile.lua
|
profile.lua
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = true;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = true;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes issue #366
|
Fixes issue #366
|
Lua
|
bsd-2-clause
|
chaupow/osrm-backend,bjtaylor1/osrm-backend,Project-OSRM/osrm-backend,yuryleb/osrm-backend,keesklopt/matrix,raymond0/osrm-backend,atsuyim/osrm-backend,agruss/osrm-backend,stevevance/Project-OSRM,arnekaiser/osrm-backend,stevevance/Project-OSRM,arnekaiser/osrm-backend,ammeurer/osrm-backend,keesklopt/matrix,prembasumatary/osrm-backend,Tristramg/osrm-backend,bjtaylor1/Project-OSRM-Old,beemogmbh/osrm-backend,keesklopt/matrix,frodrigo/osrm-backend,ammeurer/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,agruss/osrm-backend,bitsteller/osrm-backend,frodrigo/osrm-backend,ibikecph/osrm-backend,raymond0/osrm-backend,Project-OSRM/osrm-backend,yuryleb/osrm-backend,tkhaxton/osrm-backend,KnockSoftware/osrm-backend,neilbu/osrm-backend,ramyaragupathy/osrm-backend,antoinegiret/osrm-backend,beemogmbh/osrm-backend,chaupow/osrm-backend,Tristramg/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,alex85k/Project-OSRM,arnekaiser/osrm-backend,oxidase/osrm-backend,ibikecph/osrm-backend,Carsten64/OSRM-aux-git,oxidase/osrm-backend,deniskoronchik/osrm-backend,arnekaiser/osrm-backend,tkhaxton/osrm-backend,ramyaragupathy/osrm-backend,antoinegiret/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,antoinegiret/osrm-geovelo,bjtaylor1/osrm-backend,raymond0/osrm-backend,stevevance/Project-OSRM,beemogmbh/osrm-backend,Tristramg/osrm-backend,KnockSoftware/osrm-backend,hydrays/osrm-backend,yuryleb/osrm-backend,nagyistoce/osrm-backend,neilbu/osrm-backend,Carsten64/OSRM-aux-git,deniskoronchik/osrm-backend,yuryleb/osrm-backend,nagyistoce/osrm-backend,duizendnegen/osrm-backend,atsuyim/osrm-backend,prembasumatary/osrm-backend,skyborla/osrm-backend,ammeurer/osrm-backend,frodrigo/osrm-backend,bitsteller/osrm-backend,hydrays/osrm-backend,Conggge/osrm-backend,jpizarrom/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/Project-OSRM-Old,skyborla/osrm-backend,Conggge/osrm-backend,frodrigo/osrm-backend,felixguendling/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-geovelo,deniskoronchik/osrm-backend,ammeurer/osrm-backend,neilbu/osrm-backend,Conggge/osrm-backend,stevevance/Project-OSRM,jpizarrom/osrm-backend,chaupow/osrm-backend,alex85k/Project-OSRM,KnockSoftware/osrm-backend,KnockSoftware/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,oxidase/osrm-backend,prembasumatary/osrm-backend,bjtaylor1/Project-OSRM-Old,bjtaylor1/osrm-backend,ammeurer/osrm-backend,Conggge/osrm-backend,Carsten64/OSRM-aux-git,ibikecph/osrm-backend,antoinegiret/osrm-backend,agruss/osrm-backend,duizendnegen/osrm-backend,Project-OSRM/osrm-backend,neilbu/osrm-backend,oxidase/osrm-backend,bitsteller/osrm-backend,keesklopt/matrix,felixguendling/osrm-backend,jpizarrom/osrm-backend,tkhaxton/osrm-backend,antoinegiret/osrm-geovelo,deniskoronchik/osrm-backend,Project-OSRM/osrm-backend,duizendnegen/osrm-backend,felixguendling/osrm-backend,alex85k/Project-OSRM,bjtaylor1/osrm-backend,duizendnegen/osrm-backend,nagyistoce/osrm-backend,bjtaylor1/Project-OSRM-Old
|
098b5c1560a8d5ce0a81abd5c149d996203852f1
|
interface/options/uid.lua
|
interface/options/uid.lua
|
local option = {}
option.description = "Overwrite uid used for this flow. Useful to receive flows"
.. " sent by another instance."
option.configHelp = "Will also accept number values. Same restrictions as explained above."
function option.getHelp()
return {
{ "<number>", "Set the uid of this flow to <number>. Needs to be a unique integer greater than zero."},
}
end
local uids = {}
local function next_uid() -- simulating pure lua # operator + 1
local i = 1
while uids[i] do i = i + 1 end
return i
end
function option.parse(flow, number, error)
if flow.results.uid then return flow.results.uid end
local t = type(number)
if type(number) == "string" then
number = error:assert(tonumber(number), "Invalid string. Needs to be convertible to a number.")
elseif t ~= "number" and t ~= "nil" then
error("Invalid argument. String or number expected, got %s.", t)
number = nil
end
if not number or not assert(number > 0 and not uids[number],
"Invalid value. Needs to be a unique positive integer.") then
number = next_uid()
end
uids[number] = true
return number
end
return option
|
local option = {}
option.description = "Overwrite uid used for this flow. Useful to receive flows"
.. " sent by another instance."
option.configHelp = "Will also accept number values. Same restrictions as explained above."
function option.getHelp()
return {
{ "<number>", "Set the uid of this flow to <number>. Needs to be a unique integer greater than zero."},
}
end
local uids = {}
local function next_uid() -- simulating pure lua # operator + 1
local i = 1
while uids[i] do i = i + 1 end
return i
end
function option.parse(flow, number, error)
if flow:property "uid" then return flow:property "uid" end
local t = type(number)
if type(number) == "string" then
number = error:assert(tonumber(number), "Invalid string. Needs to be convertible to a number.")
elseif t ~= "number" and t ~= "nil" then
error("Invalid argument. String or number expected, got %s.", t)
number = nil
end
if not number or not assert(number > 0 and not uids[number],
"Invalid value. Needs to be a unique positive integer.") then
number = next_uid()
end
uids[number] = true
flow:setProperty("uid", number)
return number
end
return option
|
Fix uid passing.
|
Fix uid passing.
|
Lua
|
mit
|
emmericp/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,scholzd/MoonGen
|
7654fc639a14d75f5e260e51933811f4e0904b78
|
deps/coro-split.lua
|
deps/coro-split.lua
|
--[[lit-meta
name = "creationix/coro-split"
version = "2.0.1"
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-split.lua"
description = "An coro style helper for running tasks concurrently."
tags = {"coro", "split"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
-- Split takes several functions as input and runs them in concurrent coroutines.
-- The split function will itself block and wait for all three to finish.
-- The results of the functions will be returned from split.
local function assertResume(thread, ...)
local success, err = coroutine.resume(thread, ...)
if not success then
error(debug.traceback(thread, err), 0)
end
end
return function (...)
local tasks = {...}
for i = 1, #tasks do
assert(type(tasks[i]) == "function", "all tasks must be functions")
end
local thread = coroutine.running()
local left = #tasks
local results = {}
local function check()
left = left - 1
if left == 0 then
assertResume(thread, unpack(results))
end
end
for i = 1, #tasks do
coroutine.wrap(function ()
results[i] = tasks[i]()
check()
end)()
end
return coroutine.yield()
end
|
--[[lit-meta
name = "creationix/coro-split"
version = "2.0.1"
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-split.lua"
description = "An coro style helper for running tasks concurrently."
tags = {"coro", "split"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
-- Split takes several functions as input and runs them in concurrent coroutines.
-- The split function will itself block and wait for all three to finish.
-- The results of the functions will be returned from split.
local function assertResume(thread, ...)
local success, err = coroutine.resume(thread, ...)
if not success then
error(debug.traceback(thread, err), 0)
end
end
return function (...)
local tasks = {...}
for i = 1, #tasks do
assert(type(tasks[i]) == "function", "all tasks must be functions")
end
local thread = coroutine.running()
local left = #tasks
local results = {}
local yielded = false
local function check()
left = left - 1
if left == 0 and yielded then
assertResume(thread, unpack(results))
end
end
for i = 1, #tasks do
coroutine.wrap(function ()
results[i] = tasks[i]()
check()
end)()
end
if left <= 0 then
return unpack(results)
end
yielded = true
return coroutine.yield()
end
|
coro-split: fixing resume before yielding
|
coro-split: fixing resume before yielding
|
Lua
|
apache-2.0
|
luvit/lit,zhaozg/lit
|
5e8bd7f6cf5da28867d4902003a1d29751b1a028
|
hostinfo/login.lua
|
hostinfo/login.lua
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local fs = require('fs');
local string = require('string')
local table = require('table')
--[[ Login ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
local obj = {}
local filename = "/etc/login.defs"
obj['login.defs'] = {}
-- open /etc/login.defs
fs.readFile(filename, function (err, data)
if (err) then
return
end
-- split and assign key/values
for line in data:gmatch("[^\r\n]+") do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
-- find defs
if not iscomment and not isblank then
local items = {}
local i = 0
-- split and assign key/values
for item in line:gmatch("%S+") do
i = i + 1
items[i] = item;
end
local key = items[1]
local value = items[2]
-- add def
obj['login.defs'][key] = value
end
end
table.insert(self._params, obj)
callback()
end)
end
function Info:getType()
return 'LOGIN'
end
return Info
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local fs = require('fs');
local string = require('string')
local table = require('table')
local os = require('os')
--[[ Login ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
if os.type() ~= 'Linux' then
self._error = 'Unsupported OS for Login Definitions'
callback()
return
end
local obj = {}
local filename = "/etc/login.defs"
obj['login.defs'] = {}
-- open /etc/login.defs
fs.readFile(filename, function (err, data)
if (err) then
return
end
-- split and assign key/values
for line in data:gmatch("[^\r\n]+") do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
-- find defs
if not iscomment and not isblank then
local items = {}
local i = 0
-- split and assign key/values
for item in line:gmatch("%S+") do
i = i + 1
items[i] = item;
end
local key = items[1]
local value = items[2]
-- add def
obj['login.defs'][key] = value
end
end
table.insert(self._params, obj)
callback()
end)
end
function Info:getType()
return 'LOGIN'
end
return Info
|
fix(Hostinfo): login.defs checks for os.type()
|
fix(Hostinfo): login.defs checks for os.type()
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent
|
aaa46718b4243c364320b4ccf277533dba68bbc2
|
src/grpc_lua/impl/ServiceStub.lua
|
src/grpc_lua/impl/ServiceStub.lua
|
--- Service stub.
-- Wraps C `ServiceStub` class.
-- @classmod grpc_lua.impl.ServiceStub
local ServiceStub = {}
local c = require("grpc_lua.c") -- from grpc_lua.so
local pb = require("luapbintf")
local MethodInfo = require("grpc_lua.impl.MethodInfo")
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New `ServiceStub` object.
-- Do not call it directly, use `grpc_lua.ServiceStub(ch)` instead.
-- @tparam userdata c_channel C `Channel` object
-- @string service_name full service name like "helloworld.Greeter"
-- @treturn table `ServiceStub` object
function ServiceStub:new(c_channel, service_name)
assert("userdata" == type(c_channel))
local stub = {
-- private:
_c_stub = c.ServiceStub(c_channel),
-- channel = c_channel, -- to new other ServiceStubs
_service_name = service_name,
_method_info_map = {} -- map { [method_name] = MethodInfo }
}
setmetatable(stub, self)
self.__index = self
return stub
end -- new()
-- Todo: get_channel() to new other stub.
--- Set timeout seconds like 0.5s.
-- @tparam number|nil timeout_sec timeout seconds, nil means no timeout.
function ServiceStub:set_timeout_sec(timeout_sec)
self.timeout_sec = timeout_sec
end -- set_timeout_sec()
--- Get request name.
-- @string method_name method name, like "/helloworld.Greeter/SayHello"
function ServiceStub:get_request_name(method_name)
return "/" .. self._service_name .. "/" .. method_name
end -- get_request_name()
--- Set error callback for async request.
-- @tparam function|nil on_error error callback
-- `on_error` is `function(error_str, status_code)`
-- `on_error` may be nil to ignore all errors.
function ServiceStub:set_on_error(on_error)
assert(nil == on_error or "function" == type(on_error))
self.on_error = on_error
end -- set_on_error()
--- Sync request.
-- @string method_name
-- @tab request request message
-- @treturn string|(nil, string, int) response string or
-- `(nil, error_string, grpc_status_code)`.
-- @usage request("SayHello", { name = "Jq" })
function ServiceStub:sync_request(method_name, request)
assert("table" == type(request))
local request_name = self:get_request_name(method_name)
local request_str = self:_encode_request(method_name, request)
local response_str, error_str, status_code =
self._c_stub:sync_request(request_name, request_str)
local response = self:_decode_response(method_name, response_str)
return response, error_str, status_code
end -- request()
--- Async request.
-- @string method_name method name
-- @tab request request message
-- @func[opt] on_response response callback, `function(response_message_table)`
function ServiceStub:async_request(method_name, request, on_response)
assert("table" == type(request))
assert(nil == on_response or "function" == type(on_response))
local request_name = self:get_request_name(method_name)
local request_str = self:_encode_request(method_name, request)
-- Need to wrap the response callback.
self._c_stub:async_request(request_name, request_str,
self:_get_response_callback(method_name, on_response),
self.on_error)
end -- async_request()
--- Blocking run.
function ServiceStub:run()
self._c_stub:run()
end -- run()
--- Shutdown the stub.
-- To end run().
function ServiceStub:shutdown()
self._c_stub:shutdown()
end -- shutdown()
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
--- Encode request table to string.
function ServiceStub:_encode_request(method_name, request)
local request_type = self:_get_request_type(method_name)
return pb.encode(request_type, request)
end -- _encode_request()
--- Decode response string to message table.
function ServiceStub:_decode_response(method_name, response_str)
if not response_str then return nil end
assert("string" == type(response_str))
local response_type = self:_get_response_type(method_name)
return pb.decode(response_type, response_str)
end -- _decode_response()
--- Async request callback.
local function on_response_str(service_name, method_name, response_str,
on_response, on_error)
assert(on_response) -- while on_error may be nil
local response_type = self:_get_response_type(method_name)
local response = pb.decode(response_type, response_str)
if response then
on_response(response)
return
end
if on_error then
-- GRPC_STATUS_INTERNAL = 13
on_error("Failed to decode response.", 13)
end
end -- on_response_str()
--- Wrap a response callback.
function ServiceStub:_get_response_callback(method_name, on_response)
if not on_response then return nil end
return function(response_str)
on_response_str(self._service_name, method_name, response_str,
on_response, self.on_error)
end
end -- _get_response_callback()
--- Get request type.
-- @string method_name
-- @treturn string
function ServiceStub:_get_request_type(method_name)
return self:_get_method_info(method_name).request_type
end -- _get_request_type()
function ServiceStub:_get_response_type(method_name)
return self:_get_method_info(method_name).response_type
end -- _get_response_type()
--- Get method information.
-- Load it if not.
-- @string method_name
-- @treturn MethodInfo
function ServiceStub:_get_method_info(method_name)
local method = self._method_info_map[method_name]
if method then return method end
method = MethodInfo:new(self._service_name, method_name)
self._method_info_map[method_name] = method
return method
end -- _get_method_info()
return ServiceStub
|
--- Service stub.
-- Wraps C `ServiceStub` class.
-- @classmod grpc_lua.impl.ServiceStub
local ServiceStub = {}
local c = require("grpc_lua.c") -- from grpc_lua.so
local pb = require("luapbintf")
local MethodInfo = require("grpc_lua.impl.MethodInfo")
-------------------------------------------------------------------------------
--- Public functions.
-- @section public
--- New `ServiceStub` object.
-- Do not call it directly, use `grpc_lua.ServiceStub(ch)` instead.
-- @tparam userdata c_channel C `Channel` object
-- @string service_name full service name like "helloworld.Greeter"
-- @treturn table `ServiceStub` object
function ServiceStub:new(c_channel, service_name)
assert("userdata" == type(c_channel))
local stub = {
-- private:
_c_stub = c.ServiceStub(c_channel),
-- channel = c_channel, -- to new other ServiceStubs
_service_name = service_name,
_method_info_map = {} -- map { [method_name] = MethodInfo }
}
setmetatable(stub, self)
self.__index = self
return stub
end -- new()
-- Todo: get_channel() to new other stub.
--- Set timeout seconds like 0.5s.
-- @tparam number|nil timeout_sec timeout seconds, nil means no timeout.
function ServiceStub:set_timeout_sec(timeout_sec)
self.timeout_sec = timeout_sec
end -- set_timeout_sec()
--- Get request name.
-- @string method_name method name, like "/helloworld.Greeter/SayHello"
function ServiceStub:get_request_name(method_name)
return "/" .. self._service_name .. "/" .. method_name
end -- get_request_name()
--- Set error callback for async request.
-- @tparam function|nil on_error error callback
-- `on_error` is `function(error_str, status_code)`
-- `on_error` may be nil to ignore all errors.
function ServiceStub:set_on_error(on_error)
assert(nil == on_error or "function" == type(on_error))
self.on_error = on_error
end -- set_on_error()
--- Sync request.
-- @string method_name
-- @tab request request message
-- @treturn string|(nil, string, int) response string or
-- `(nil, error_string, grpc_status_code)`.
-- @usage request("SayHello", { name = "Jq" })
function ServiceStub:sync_request(method_name, request)
assert("table" == type(request))
local request_name = self:get_request_name(method_name)
local request_str = self:_encode_request(method_name, request)
local response_str, error_str, status_code =
self._c_stub:sync_request(request_name, request_str)
local response = self:_decode_response(method_name, response_str)
return response, error_str, status_code
end -- request()
--- Async request.
-- @string method_name method name
-- @tab request request message
-- @func[opt] on_response response callback, `function(response_message_table)`
function ServiceStub:async_request(method_name, request, on_response)
assert("table" == type(request))
assert(nil == on_response or "function" == type(on_response))
local request_name = self:get_request_name(method_name)
local request_str = self:_encode_request(method_name, request)
-- Need to wrap the response callback.
self._c_stub:async_request(request_name, request_str,
self:_get_response_callback(method_name, on_response),
self.on_error)
end -- async_request()
--- Blocking run.
function ServiceStub:run()
self._c_stub:run()
end -- run()
--- Shutdown the stub.
-- To end run().
function ServiceStub:shutdown()
self._c_stub:shutdown()
end -- shutdown()
-------------------------------------------------------------------------------
--- Private functions.
-- @section private
--- Encode request table to string.
function ServiceStub:_encode_request(method_name, request)
local request_type = self:_get_request_type(method_name)
return pb.encode(request_type, request)
end -- _encode_request()
--- Decode response string to message table.
function ServiceStub:_decode_response(method_name, response_str)
if not response_str then return nil end
assert("string" == type(response_str))
local response_type = self:_get_response_type(method_name)
return pb.decode(response_type, response_str)
end -- _decode_response()
--- Async request callback.
-- @string response_type
-- @string response_str
-- @func[opt] on_response
-- @func[opt] on_error
local function on_response_str(
response_type, response_str, on_response, on_error)
assert(on_response) -- while on_error may be nil
local response = pb.decode(response_type, response_str)
if response then
on_response(response)
return
end
if on_error then
-- GRPC_STATUS_INTERNAL = 13
on_error("Failed to decode response.", 13)
end
end -- on_response_str()
--- Wrap a response callback.
function ServiceStub:_get_response_callback(method_name, on_response)
if not on_response then return nil end
local response_type = self:_get_response_type(method_name)
return function(response_str)
on_response_str(response_type, response_str,
on_response, self.on_error)
end
end -- _get_response_callback()
--- Get request type.
-- @string method_name
-- @treturn string
function ServiceStub:_get_request_type(method_name)
return self:_get_method_info(method_name).request_type
end -- _get_request_type()
function ServiceStub:_get_response_type(method_name)
return self:_get_method_info(method_name).response_type
end -- _get_response_type()
--- Get method information.
-- Load it if not.
-- @string method_name
-- @treturn MethodInfo
function ServiceStub:_get_method_info(method_name)
local method = self._method_info_map[method_name]
if method then return method end
method = MethodInfo:new(self._service_name, method_name)
self._method_info_map[method_name] = method
return method
end -- _get_method_info()
return ServiceStub
|
Fix on_response_str().
|
Fix on_response_str().
|
Lua
|
bsd-3-clause
|
jinq0123/grpc-lua,jinq0123/grpc-lua,jinq0123/grpc-lua
|
d9cad3292ed9fa48bbb9f948d3e7db5efe743479
|
tests/test-tcp.lua
|
tests/test-tcp.lua
|
--[[
Copyright 2012 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 net = require('net')
local PORT = 10082
require('tap')(function(test)
test("server", function(expect)
local server, client, onServerConnection, onConnect
function onServerConnection(client)
local onData
function onData(chunk)
local onWrite
function onWrite(err)
p("server:client:write")
assert(err == nil)
client:destroy()
end
p('server:client:on("data")', chunk)
assert(chunk == "ping")
client:write("pong", onWrite)
end
client:on("data", expect(onData))
end
function onConnect()
p('client:on("complete")')
local onData, onWrite
function onData(data)
p('client:on("data")', data)
assert(data == "pong")
client:destroy()
server:close()
end
function onWrite(err)
p("client:write")
assert(err == nil)
end
client:on('data', expect(onData))
client:write("ping", expect(onWrite))
end
server = net.createServer(onServerConnection)
server:listen(PORT, "127.0.0.1")
client = net.Socket:new()
client:connect(PORT, "127.0.0.1", onConnect)
end)
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 net = require('net')
local HOST = '127.0.0.1'
local PORT = 10082
require('tap')(function(test)
test("server", function(expect)
local server, client, onServerConnection, onConnect
function onServerConnection(client)
local onData
function onData(chunk)
local onWrite
function onWrite(err)
p("server:client:write")
assert(err == nil)
client:destroy()
end
p('server:client:on("data")', chunk)
assert(chunk == "ping")
client:write("pong", onWrite)
end
client:on("data", expect(onData))
end
function onConnect()
p('client:on("complete")')
local onData, onWrite
function onData(data)
p('client:on("data")', data)
assert(data == "pong")
client:destroy()
server:close()
end
function onWrite(err)
p("client:write")
assert(err == nil)
end
client:on('data', expect(onData))
client:write("ping", expect(onWrite))
end
server = net.createServer(onServerConnection)
server:listen(PORT, HOST)
client = net.Socket:new()
client:connect(PORT, HOST, onConnect)
end)
end)
|
fix copyright and make host var
|
fix copyright and make host var
|
Lua
|
apache-2.0
|
GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,rjeli/luvit,zhaozg/luvit,kaustavha/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,rjeli/luvit,bsn069/luvit,DBarney/luvit,DBarney/luvit,bsn069/luvit,rjeli/luvit,rjeli/luvit,DBarney/luvit,kaustavha/luvit,kaustavha/luvit,DBarney/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream
|
ad623bcfee4d12c029204cff8fe8f20198dd98b3
|
server/lualib/gameserver/gameserver.lua
|
server/lualib/gameserver/gameserver.lua
|
local skynet = require "skynet"
local gateserver = require "gameserver.gateserver"
local logger = require "logger"
local protoloader = require "protoloader"
local gameserver = {}
local handshake = {}
function gameserver.forward (fd, agent)
gateserver.forward (fd, agent)
end
function gameserver.kick (fd)
gateserver.close_client (fd)
end
function gameserver.start (gamed)
local handler = {}
local host, send_request = protoloader.load (protoloader.LOGIN)
function handler.open (source, conf)
return gamed.open (conf)
end
function handler.connect (fd, addr)
logger.logf ("connect from %s (fd = %d)", addr, fd)
handshake[fd] = addr
gateserver.open_client (fd)
end
function handler.disconnect (fd)
logger.logf ("fd (%d) disconnected", fd)
end
local function do_login (msg, sz)
local type, name, args, response = host:dispatch (msg, sz)
assert (type == "REQUEST")
assert (name == "login")
local session = assert (tonumber (args.session))
local token = assert (args.token)
local account = gamed.auth_handler (session, token)
assert (account)
return account
end
local traceback = debug.traceback
function handler.message (fd, msg, sz)
local addr = handshake[fd]
if addr then
handshake[fd] = nil
local ok, account = xpcall (do_login, traceback, msg, sz)
if not ok then
logger.warningf ("%s login failed : %s", addr, account)
gateserver.close_client (fd)
else
logger.logf ("account %d login success", account)
gamed.login_handler (fd, account)
end
else
gamed.message_handler (fd, msg, sz)
end
end
local CMD = {}
function CMD.token (id, secret)
local id = tonumber (id)
login_token[id] = secret
skynet.timeout (10 * 100, function ()
if login_token[id] == secret then
logger.logf ("account %d token timeout", id)
login_token[id] = nil
end
end)
end
function handler.command (cmd, ...)
local f = CMD[cmd]
if f then
return f (...)
else
return gamed.command_handler (cmd, ...)
end
end
return gateserver.start (handler)
end
return gameserver
|
local skynet = require "skynet"
local socketdriver = require "socketdriver"
local gateserver = require "gameserver.gateserver"
local logger = require "logger"
local protoloader = require "protoloader"
local gameserver = {}
local handshake = {}
function gameserver.forward (fd, agent)
gateserver.forward (fd, agent)
end
function gameserver.kick (fd)
gateserver.close_client (fd)
end
function gameserver.start (gamed)
local handler = {}
local host, send_request = protoloader.load (protoloader.LOGIN)
function handler.open (source, conf)
return gamed.open (conf)
end
function handler.connect (fd, addr)
logger.logf ("connect from %s (fd = %d)", addr, fd)
handshake[fd] = addr
gateserver.open_client (fd)
end
function handler.disconnect (fd)
logger.logf ("fd (%d) disconnected", fd)
end
local function do_login (fd, msg, sz)
local type, name, args, response = host:dispatch (msg, sz)
assert (type == "REQUEST")
assert (name == "login")
local session = assert (tonumber (args.session))
local token = assert (args.token)
local account = gamed.auth_handler (session, token)
assert (account)
local package = string.pack (">s2", response { account = account })
socketdriver.send (fd, package)
return account
end
local traceback = debug.traceback
function handler.message (fd, msg, sz)
local addr = handshake[fd]
if addr then
handshake[fd] = nil
local ok, account = xpcall (do_login, traceback, fd, msg, sz)
if not ok then
logger.warningf ("%s login failed : %s", addr, account)
gateserver.close_client (fd)
else
logger.logf ("account %d login success", account)
gamed.login_handler (fd, account)
end
else
gamed.message_handler (fd, msg, sz)
end
end
local CMD = {}
function CMD.token (id, secret)
local id = tonumber (id)
login_token[id] = secret
skynet.timeout (10 * 100, function ()
if login_token[id] == secret then
logger.logf ("account %d token timeout", id)
login_token[id] = nil
end
end)
end
function handler.command (cmd, ...)
local f = CMD[cmd]
if f then
return f (...)
else
return gamed.command_handler (cmd, ...)
end
end
return gateserver.start (handler)
end
return gameserver
|
fix login response
|
fix login response
|
Lua
|
mit
|
hsw625728/some-mmorpg,zj831007/some-mmorpg,catinred2/some-mmorpg,jintiao/some-mmorpg,thinkry/some-mmorpg,jintiao/some-mmorpg,catinred2/some-mmorpg,zj831007/some-mmorpg,jintiao/some-mmorpg,hsw625728/some-mmorpg,jintiao/some-mmorpg,catinred2/some-mmorpg,zj831007/some-mmorpg,thinkry/some-mmorpg,zj831007/some-mmorpg,catinred2/some-mmorpg,hsw625728/some-mmorpg,thinkry/some-mmorpg,thinkry/some-mmorpg,thinkry/some-mmorpg,hsw625728/some-mmorpg
|
f1218aea10604b751206a0584522fd212074918e
|
luagcrypt_test.lua
|
luagcrypt_test.lua
|
--
-- Test suite for luagcrypt.
--
-- Copyright (C) 2016 Peter Wu <[email protected]>
-- Licensed under the MIT license. See the LICENSE file for details.
--
-- Convert a string of hexadecimal numbers to a bytes string
function fromhex(hex)
if string.match(hex, "[^0-9a-fA-F]") then
error("Invalid chars in hex")
end
if string.len(hex) % 2 == 1 then
error("Hex string must be a multiple of two")
end
local s = string.gsub(hex, "..", function(v)
return string.char(tonumber(v, 16))
end)
return s
end
-- Ensure that advertised constants are never removed.
function test_constants()
assert(gcrypt.CIPHER_AES128 == 7)
assert(gcrypt.CIPHER_AES192 == 8)
assert(gcrypt.CIPHER_AES256 == 9)
assert(gcrypt.CIPHER_MODE_CBC == 3)
assert(gcrypt.CIPHER_MODE_CTR == 6)
assert(gcrypt.CIPHER_MODE_GCM == 9)
assert(gcrypt.MD_SHA256 == 8)
assert(gcrypt.MD_FLAG_HMAC == 2)
end
function test_aes_cbc_128()
-- RFC 3602 -- 4. Test Vectors (Case #1)
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CBC)
cipher:setkey(fromhex("06a9214036b8a15b512e03d534120006"))
cipher:setiv(fromhex("3dafba429d9eb430b422da802c9fac41"))
local ciphertext = cipher:encrypt("Single block msg")
assert(ciphertext == fromhex("e353779c1079aeb82708942dbe77181a"))
cipher:reset()
cipher:setiv(fromhex("3dafba429d9eb430b422da802c9fac41"))
local plaintext = cipher:decrypt(fromhex("e353779c1079aeb82708942dbe77181a"))
assert(plaintext == "Single block msg")
end
function test_aes_ctr_192()
-- RFC 3686 -- 6. Test Vectors (Test Vector #6)
local counter_iv_one = fromhex("0007bdfd5cbd60278dcc091200000001")
local plaintexts = {
fromhex("000102030405060708090a0b0c0d0e0f"),
fromhex("101112131415161718191a1b1c1d1e1f"),
fromhex("20212223")
}
local ciphertexts = {
fromhex("96893fc55e5c722f540b7dd1ddf7e758"),
fromhex("d288bc95c69165884536c811662f2188"),
fromhex("abee0935")
}
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES192, gcrypt.CIPHER_MODE_CTR)
cipher:setkey(fromhex("02bf391ee8ecb159b959617b0965279bf59b60a786d3e0fe"))
cipher:setctr(counter_iv_one)
assert(cipher:encrypt(plaintexts[1]) == ciphertexts[1])
assert(cipher:encrypt(plaintexts[2]) == ciphertexts[2])
assert(cipher:encrypt(plaintexts[3]) == ciphertexts[3])
cipher:setctr(counter_iv_one)
assert(cipher:decrypt(ciphertexts[1]) == plaintexts[1])
assert(cipher:decrypt(ciphertexts[2]) == plaintexts[2])
assert(cipher:decrypt(ciphertexts[3]) == plaintexts[3])
end
function test_hmac_sha256()
-- RFC 4231 -- 4.2. Test Case 1
local md = gcrypt.Hash(gcrypt.MD_SHA256, gcrypt.MD_FLAG_HMAC)
md:setkey(fromhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"))
md:write("Hi There")
local digest = md:read()
assert(digest == fromhex("b0344c61d8db38535ca8afceaf0bf12b" ..
"881dc200c9833da726e9376c2e32cff7"))
end
-- Check for SHA256 calculation with optional flags parameter and reset.
function test_sha256()
-- http://csrc.nist.gov/groups/ST/toolkit/examples.html
local md = gcrypt.Hash(gcrypt.MD_SHA256)
md:write("will be reset")
md:reset()
md:write("ab")
md:write("c")
local digest = md:read(gcrypt.MD_SHA256)
assert(digest == fromhex("ba7816bf8f01cfea414140de5dae2223" ..
"b00361a396177a9cb410ff61f20015ad"))
end
function assert_throws(func, message)
local ok, err = pcall(func)
if ok then
error("Expected \"" .. message .. "\", got no error")
end
if not string.find(err, message, 1, true) then
error("Expected \"" .. message .. "\", got \"" .. err .. "\"")
end
end
function test_cipher_bad()
assert_throws(function() gcrypt.Cipher(0, 0) end,
"gcry_cipher_open() failed with Invalid cipher algorithm")
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CBC)
assert_throws(function() cipher:setkey("") end,
"gcry_cipher_setkey() failed with Invalid key length")
-- Must normally be a multiple of block size
assert_throws(function() cipher:encrypt("x") end,
"gcry_cipher_encrypt() failed with Invalid length")
assert_throws(function() cipher:decrypt("y") end,
"gcry_cipher_decrypt() failed with Invalid length")
end
function test_aes_ctr_bad()
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CTR)
-- Counter must be a multiple of block size
assert_throws(function() cipher:setctr("x") end,
"gcry_cipher_setctr() failed with Invalid argument")
end
function test_aes_gcm_bad()
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_GCM)
assert_throws(function() cipher:setiv("") end,
"gcry_cipher_setiv() failed with Invalid length")
end
function test_hash_bad()
-- Not all flags are valid, this should trigger an error. Alternatively, one
-- can set an invalid algorithm (such as -1), but that generates debug spew.
assert_throws(function() gcrypt.Hash(0, -1) end,
"gcry_md_open() failed with Invalid argument")
local md = gcrypt.Hash(gcrypt.MD_SHA256)
-- Not called with MD_FLAG_HMAC, so should fail
assert_throws(function() md:setkey("X") end,
"gcry_md_setkey() failed with Conflicting use")
assert_throws(function() md:read(-1) end,
"Unable to obtain digest for a disabled algorithm")
end
function test_init_once()
-- TODO is this really desired behavior?
assert_throws(function() gcrypt.init() end,
"libgcrypt was already initialized")
end
local all_tests = {
{"test_constants", test_constants},
{"test_aes_cbc_128", test_aes_cbc_128},
{"test_aes_ctr_192", test_aes_ctr_192},
{"test_hmac_sha256", test_hmac_sha256},
{"test_sha256", test_sha256},
{"test_cipher_bad", test_cipher_bad},
{"test_aes_gcm_bad", test_aes_ctr_bad},
{"test_aes_gcm_bad", test_aes_gcm_bad},
{"test_hash_bad", test_hash_bad},
}
function main()
for k, v in pairs(all_tests) do
local name, test = v[1], v[2]
print("Running " .. name .. "...")
test()
-- Trigger GC routines
collectgarbage()
end
print("All tests pass!")
end
gcrypt = require("luagcrypt")
gcrypt.init()
main()
|
--
-- Test suite for luagcrypt.
--
-- Copyright (C) 2016 Peter Wu <[email protected]>
-- Licensed under the MIT license. See the LICENSE file for details.
--
-- Convert a string of hexadecimal numbers to a bytes string
function fromhex(hex)
if string.match(hex, "[^0-9a-fA-F]") then
error("Invalid chars in hex")
end
if string.len(hex) % 2 == 1 then
error("Hex string must be a multiple of two")
end
local s = string.gsub(hex, "..", function(v)
return string.char(tonumber(v, 16))
end)
return s
end
-- Ensure that advertised constants are never removed.
function test_constants()
assert(gcrypt.CIPHER_AES128 == 7)
assert(gcrypt.CIPHER_AES192 == 8)
assert(gcrypt.CIPHER_AES256 == 9)
assert(gcrypt.CIPHER_MODE_CBC == 3)
assert(gcrypt.CIPHER_MODE_CTR == 6)
assert(gcrypt.CIPHER_MODE_GCM == 9)
assert(gcrypt.MD_SHA256 == 8)
assert(gcrypt.MD_FLAG_HMAC == 2)
end
function test_aes_cbc_128()
-- RFC 3602 -- 4. Test Vectors (Case #1)
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CBC)
cipher:setkey(fromhex("06a9214036b8a15b512e03d534120006"))
cipher:setiv(fromhex("3dafba429d9eb430b422da802c9fac41"))
local ciphertext = cipher:encrypt("Single block msg")
assert(ciphertext == fromhex("e353779c1079aeb82708942dbe77181a"))
cipher:reset()
cipher:setiv(fromhex("3dafba429d9eb430b422da802c9fac41"))
local plaintext = cipher:decrypt(fromhex("e353779c1079aeb82708942dbe77181a"))
assert(plaintext == "Single block msg")
end
function test_aes_ctr_192()
-- RFC 3686 -- 6. Test Vectors (Test Vector #6)
local counter_iv_one = fromhex("0007bdfd5cbd60278dcc091200000001")
local plaintexts = {
fromhex("000102030405060708090a0b0c0d0e0f"),
fromhex("101112131415161718191a1b1c1d1e1f"),
fromhex("20212223")
}
local ciphertexts = {
fromhex("96893fc55e5c722f540b7dd1ddf7e758"),
fromhex("d288bc95c69165884536c811662f2188"),
fromhex("abee0935")
}
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES192, gcrypt.CIPHER_MODE_CTR)
cipher:setkey(fromhex("02bf391ee8ecb159b959617b0965279bf59b60a786d3e0fe"))
cipher:setctr(counter_iv_one)
assert(cipher:encrypt(plaintexts[1]) == ciphertexts[1])
assert(cipher:encrypt(plaintexts[2]) == ciphertexts[2])
assert(cipher:encrypt(plaintexts[3]) == ciphertexts[3])
cipher:setctr(counter_iv_one)
assert(cipher:decrypt(ciphertexts[1]) == plaintexts[1])
assert(cipher:decrypt(ciphertexts[2]) == plaintexts[2])
assert(cipher:decrypt(ciphertexts[3]) == plaintexts[3])
end
function test_hmac_sha256()
-- RFC 4231 -- 4.2. Test Case 1
local md = gcrypt.Hash(gcrypt.MD_SHA256, gcrypt.MD_FLAG_HMAC)
md:setkey(fromhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"))
md:write("Hi There")
local digest = md:read()
assert(digest == fromhex("b0344c61d8db38535ca8afceaf0bf12b" ..
"881dc200c9833da726e9376c2e32cff7"))
end
-- Check for SHA256 calculation with optional flags parameter and reset.
function test_sha256()
-- http://csrc.nist.gov/groups/ST/toolkit/examples.html
local md = gcrypt.Hash(gcrypt.MD_SHA256)
md:write("will be reset")
md:reset()
md:write("ab")
md:write("c")
local digest = md:read(gcrypt.MD_SHA256)
assert(digest == fromhex("ba7816bf8f01cfea414140de5dae2223" ..
"b00361a396177a9cb410ff61f20015ad"))
end
function assert_throws(func, message)
local ok, err = pcall(func)
if ok then
error("Expected \"" .. message .. "\", got no error")
end
if not string.find(err, message, 1, true) then
error("Expected \"" .. message .. "\", got \"" .. err .. "\"")
end
end
function test_cipher_bad()
assert_throws(function() gcrypt.Cipher(0, 0) end,
"gcry_cipher_open() failed with Invalid cipher algorithm")
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CBC)
assert_throws(function() cipher:setkey("") end,
"gcry_cipher_setkey() failed with Invalid key length")
-- Must normally be a multiple of block size
assert_throws(function() cipher:encrypt("x") end,
"gcry_cipher_encrypt() failed with Invalid length")
assert_throws(function() cipher:decrypt("y") end,
"gcry_cipher_decrypt() failed with Invalid length")
end
function test_aes_ctr_bad()
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_CTR)
-- Counter must be a multiple of block size
assert_throws(function() cipher:setctr("x") end,
"gcry_cipher_setctr() failed with Invalid argument")
end
function test_aes_gcm_bad()
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES128, gcrypt.CIPHER_MODE_GCM)
assert_throws(function() cipher:setiv("") end,
"gcry_cipher_setiv() failed with Invalid length")
end
function test_hash_bad()
-- Not all flags are valid, this should trigger an error. Alternatively, one
-- can set an invalid algorithm (such as -1), but that generates debug spew.
assert_throws(function() gcrypt.Hash(0, -1) end,
"gcry_md_open() failed with Invalid argument")
local md = gcrypt.Hash(gcrypt.MD_SHA256)
-- Not called with MD_FLAG_HMAC, so should fail
-- 1.6.5: "Conflicting use".
-- 1.7.0: "Invalid digest algorithm"
assert_throws(function() md:setkey("X") end,
"gcry_md_setkey() failed with ")
assert_throws(function() md:read(-1) end,
"Unable to obtain digest for a disabled algorithm")
end
function test_init_once()
-- TODO is this really desired behavior?
assert_throws(function() gcrypt.init() end,
"libgcrypt was already initialized")
end
local all_tests = {
{"test_constants", test_constants},
{"test_aes_cbc_128", test_aes_cbc_128},
{"test_aes_ctr_192", test_aes_ctr_192},
{"test_hmac_sha256", test_hmac_sha256},
{"test_sha256", test_sha256},
{"test_cipher_bad", test_cipher_bad},
{"test_aes_gcm_bad", test_aes_ctr_bad},
{"test_aes_gcm_bad", test_aes_gcm_bad},
{"test_hash_bad", test_hash_bad},
}
function main()
for k, v in pairs(all_tests) do
local name, test = v[1], v[2]
print("Running " .. name .. "...")
test()
-- Trigger GC routines
collectgarbage()
end
print("All tests pass!")
end
gcrypt = require("luagcrypt")
gcrypt.init()
main()
|
test: fix for libgcrypt 1.7.0
|
test: fix for libgcrypt 1.7.0
Tested with libgcrypt-1.6.0-356-gd328095
|
Lua
|
mit
|
Lekensteyn/luagcrypt
|
2e0b05bb3a706aeb555dcdc3a97ee93928e8675d
|
lib/px/block/pxtemplate.lua
|
lib/px/block/pxtemplate.lua
|
---------------------------------------------
-- PerimeterX(www.perimeterx.com) Nginx plugin
----------------------------------------------
local M = {}
function M.load(config_file)
local _M = {}
local px_config = require(config_file)
local lustache = require "lustache"
local px_constants = require "px.utils.pxconstants"
local px_logger = require("px.utils.pxlogger").load(config_file)
local function get_props(px_config, uuid, vid, template)
local logo_css_style = 'visible'
if (px_config.custom_logo == nil) then
logo_css_style = 'hidden'
end
local js_client_src = string.format('//client.perimeterx.net/%s/main.min.js', px_config.px_appId)
local collectorUrl = 'https://collector-' .. string.lower(px_config.px_appId) .. '.perimeterx.net'
local captcha_url_prefix = 'https://' .. px_config.captcha_script_host
if px_config.first_party_enabled then
local reverse_prefix = string.sub(px_config.px_appId, 3, string.len(px_config.px_appId))
js_client_src = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_VENDOR_PATH)
collectorUrl = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_XHR_PATH)
captcha_url_prefix = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_CAPTCHA_PATH)
end
local captcha_src = ''
if template ~= 'ratelimit' then
captcha_src = captcha_url_prefix .. '/' .. template .. '.js'
end
return {
refId = uuid,
vid = vid,
appId = px_config.px_appId,
uuid = uuid,
customLogo = px_config.custom_logo,
cssRef = px_config.css_ref,
jsRef = px_config.js_ref,
logoVisibility = logo_css_style,
hostUrl = collectorUrl,
jsClientSrc = js_client_src,
firstPartyEnabled = px_config.first_party_enabled,
blockScript = captcha_src
}
end
local function get_path()
return string.sub(debug.getinfo(1).source, 2, string.len("/pxtemplate.lua") * -1)
end
local function get_content(template)
local __dirname = get_path()
local path = 'block_template'
if tempalate == 'ratelimit' then
path = 'ratelimit'
end
local template_path = string.format("%stemplates/%s.mustache", __dirname, path)
px_logger.debug("fetching template from: " .. template_path)
local file = io.open(template_path, "r")
if (file == nil) then
px_logger.debug("the template " .. string.format("%s.mustache", template) .. " was not found")
end
local content = file:read("*all")
file:close()
return content
end
function _M.get_template(template, uuid, vid)
local props = get_props(px_config, uuid, vid, template)
local templateStr = get_content(template)
return lustache:render(templateStr, props)
end
return _M
end
return M
|
---------------------------------------------
-- PerimeterX(www.perimeterx.com) Nginx plugin
----------------------------------------------
local M = {}
function M.load(config_file)
local _M = {}
local px_config = require(config_file)
local lustache = require "lustache"
local px_constants = require "px.utils.pxconstants"
local px_logger = require("px.utils.pxlogger").load(config_file)
local function get_props(px_config, uuid, vid, template)
local logo_css_style = 'visible'
if (px_config.custom_logo == nil) then
logo_css_style = 'hidden'
end
local js_client_src = string.format('//client.perimeterx.net/%s/main.min.js', px_config.px_appId)
local collectorUrl = 'https://collector-' .. string.lower(px_config.px_appId) .. '.perimeterx.net'
local captcha_url_prefix = 'https://' .. px_config.captcha_script_host
-- in case we are in first party mode (not relevant for mobile), change the base paths to use first party
if px_config.first_party_enabled and ngx.ctx.px_cookie_origin ~= 'header' then
local reverse_prefix = string.sub(px_config.px_appId, 3, string.len(px_config.px_appId))
js_client_src = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_VENDOR_PATH)
collectorUrl = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_XHR_PATH)
captcha_url_prefix = string.format('/%s%s', reverse_prefix, px_constants.FIRST_PARTY_CAPTCHA_PATH)
end
local captcha_src = ''
if template ~= 'ratelimit' then
captcha_src = captcha_url_prefix .. '/' .. template .. '.js'
end
return {
refId = uuid,
vid = vid,
appId = px_config.px_appId,
uuid = uuid,
customLogo = px_config.custom_logo,
cssRef = px_config.css_ref,
jsRef = px_config.js_ref,
logoVisibility = logo_css_style,
hostUrl = collectorUrl,
jsClientSrc = js_client_src,
firstPartyEnabled = px_config.first_party_enabled,
blockScript = captcha_src
}
end
local function get_path()
return string.sub(debug.getinfo(1).source, 2, string.len("/pxtemplate.lua") * -1)
end
local function get_content(template)
local __dirname = get_path()
local path = 'block_template'
if template == 'ratelimit' then
path = 'ratelimit'
end
local template_path = string.format("%stemplates/%s.mustache", __dirname, path)
px_logger.debug("fetching template from: " .. template_path)
local file = io.open(template_path, "r")
if (file == nil) then
px_logger.debug("the template " .. string.format("%s.mustache", template) .. " was not found")
end
local content = file:read("*all")
file:close()
return content
end
function _M.get_template(template, uuid, vid)
local props = get_props(px_config, uuid, vid, template)
local templateStr = get_content(template)
return lustache:render(templateStr, props)
end
return _M
end
return M
|
fixed mobile using first party paths (#118)
|
fixed mobile using first party paths (#118)
* fixed mobile using first party paths
* changed condition
|
Lua
|
mit
|
PerimeterX/perimeterx-nginx-plugin
|
bf62203c1d735e6c22924d05a7e40b2ed940a4d2
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then
return tag;
end
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
mod_carbons: Fix <private/> handling
|
mod_carbons: Fix <private/> handling
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
e3b567b2b136e3b8fb3da062d2cea26e4e5c5cf0
|
frontend/ui/rendertext.lua
|
frontend/ui/rendertext.lua
|
require "cache"
--[[
TODO: all these functions should probably be methods on Face objects
]]--
function getGlyph(face, charcode)
local hash = "glyph|"..face.hash.."|"..charcode
local glyph = Cache:check(hash)
if glyph then
-- cache hit
return glyph[1]
end
local rendered_glyph = face.ftface:renderGlyph(charcode)
if not rendered_glyph then
DEBUG("error rendering glyph (charcode=", charcode, ") for face", face)
return
end
glyph = CacheItem:new{rendered_glyph}
glyph.size = glyph[1].bb:getWidth() * glyph[1].bb:getHeight() / 2 + 32
Cache:insert(hash, glyph)
return glyph[1]
end
function getSubTextByWidth(text, face, width, kerning)
local pen_x = 0
local prevcharcode = 0
local char_list = {}
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < width then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
end
pen_x = pen_x + glyph.ax
if pen_x <= width then
prevcharcode = charcode
table.insert(char_list, uchar)
else
break
end
end
end
return table.concat(char_list)
end
function sizeUtf8Text(x, width, face, text, kerning)
if text == nil then
DEBUG("sizeUtf8Text called without text");
return
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local pen_y_top = 0
local pen_y_bottom = 0
local prevcharcode = 0
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < (width - x) then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
--DEBUG("prev:"..string.char(prevcharcode).." curr:"..string.char(charcode).." kern:"..kern)
else
--DEBUG("curr:"..string.char(charcode))
end
pen_x = pen_x + glyph.ax
pen_y_top = math.max(pen_y_top, glyph.t)
pen_y_bottom = math.max(pen_y_bottom, glyph.bb:getHeight() - glyph.t)
--DEBUG("ax:"..glyph.ax.." t:"..glyph.t.." r:"..glyph.r.." h:"..glyph.bb:getHeight().." w:"..glyph.bb:getWidth().." yt:"..pen_y_top.." yb:"..pen_y_bottom)
prevcharcode = charcode
end
end
return { x = pen_x, y_top = pen_y_top, y_bottom = pen_y_bottom}
end
function renderUtf8Text(buffer, x, y, face, text, kerning)
if text == nil then
DEBUG("renderUtf8Text called without text");
return 0
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local prevcharcode = 0
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < buffer:getWidth() then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
--DEBUG("prev:"..string.char(prevcharcode).." curr:"..string.char(charcode).." pen_x:"..pen_x.." kern:"..kern)
buffer:addblitFrom(glyph.bb, x + pen_x + glyph.l, y - glyph.t, 0, 0, glyph.bb:getWidth(), glyph.bb:getHeight())
else
--DEBUG(" curr:"..string.char(charcode))
buffer:blitFrom(glyph.bb, x + pen_x + glyph.l, y - glyph.t, 0, 0, glyph.bb:getWidth(), glyph.bb:getHeight())
end
pen_x = pen_x + glyph.ax
prevcharcode = charcode
end
end
return pen_x
end
|
require "cache"
--[[
TODO: all these functions should probably be methods on Face objects
]]--
function getGlyph(face, charcode)
local hash = "glyph|"..face.hash.."|"..charcode
local glyph = Cache:check(hash)
if glyph then
-- cache hit
return glyph[1]
end
local rendered_glyph = face.ftface:renderGlyph(charcode)
if not rendered_glyph then
DEBUG("error rendering glyph (charcode=", charcode, ") for face", face)
return
end
glyph = CacheItem:new{rendered_glyph}
glyph.size = glyph[1].bb:getWidth() * glyph[1].bb:getHeight() / 2 + 32
Cache:insert(hash, glyph)
return glyph[1]
end
function getSubTextByWidth(text, face, width, kerning)
local pen_x = 0
local prevcharcode = 0
local char_list = {}
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < width then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
end
pen_x = pen_x + glyph.ax
if pen_x <= width then
prevcharcode = charcode
table.insert(char_list, uchar)
else
break
end
end
end
return table.concat(char_list)
end
function sizeUtf8Text(x, width, face, text, kerning)
if not text then
DEBUG("sizeUtf8Text called without text");
return
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local pen_y_top = 0
local pen_y_bottom = 0
local prevcharcode = 0
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < (width - x) then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + face.ftface:getKerning(prevcharcode, charcode)
end
pen_x = pen_x + glyph.ax
pen_y_top = math.max(pen_y_top, glyph.t)
pen_y_bottom = math.max(pen_y_bottom, glyph.bb:getHeight() - glyph.t)
--DEBUG("ax:"..glyph.ax.." t:"..glyph.t.." r:"..glyph.r.." h:"..glyph.bb:getHeight().." w:"..glyph.bb:getWidth().." yt:"..pen_y_top.." yb:"..pen_y_bottom)
prevcharcode = charcode
end -- if pen_x < (width - x)
end -- for uchar
return { x = pen_x, y_top = pen_y_top, y_bottom = pen_y_bottom}
end
function renderUtf8Text(buffer, x, y, face, text, kerning)
if not text then
DEBUG("renderUtf8Text called without text");
return 0
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local prevcharcode = 0
local buffer_width = buffer:getWidth()
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if pen_x < buffer_width then
local charcode = util.utf8charcode(uchar)
local glyph = getGlyph(face, charcode)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + face.ftface:getKerning(prevcharcode, charcode)
end
buffer:addblitFrom(
glyph.bb,
x + pen_x + glyph.l, y - glyph.t,
0, 0,
glyph.bb:getWidth(), glyph.bb:getHeight())
pen_x = pen_x + glyph.ax
prevcharcode = charcode
end -- if pen_x < buffer_width
end -- for uchar
return pen_x
end
|
fix kerning for Utf8Text family methods from tigran123
|
fix kerning for Utf8Text family methods from tigran123
refer to master pullrequest #386 and #383, related
commits are (all in master(kpv) tree):
cb25029dddc42693cc7aaefbe47e9bd3b7e1a750
c7b4cf71f808a40d2461bac4e02bf8d2d4127327
379cba7b68cac6b00cc0ef74a7de6f18a174d838
|
Lua
|
agpl-3.0
|
mihailim/koreader,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader-base,koreader/koreader,Hzj-jie/koreader-base,houqp/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,houqp/koreader-base,noname007/koreader,mwoz123/koreader,koreader/koreader-base,poire-z/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,NickSavage/koreader,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader,chrox/koreader,NiLuJe/koreader,Markismus/koreader,Frenzie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,robert00s/koreader,chihyang/koreader,Hzj-jie/koreader,Frenzie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader,koreader/koreader,ashhher3/koreader,frankyifei/koreader-base,poire-z/koreader,apletnev/koreader-base,frankyifei/koreader-base,lgeek/koreader,houqp/koreader-base,houqp/koreader-base,apletnev/koreader-base,pazos/koreader,Frenzie/koreader,koreader/koreader-base,Frenzie/koreader-base,apletnev/koreader,ashang/koreader,Hzj-jie/koreader-base,Frenzie/koreader
|
7d8c1359ab494ab17c75a791231197ef139f6b94
|
BtUtils/Vector3.lua
|
BtUtils/Vector3.lua
|
-- A 3D Vector Library.
-- By Gordon MacPherson with the assistance of google and sir divran! :L
-- changes by: Michal Mojzk
-- - adapted to be compatible BtUtils by
-- - fixed methods to belong into the __index lookup table rather than the metatable itself
-- - added LengthSqr
-- - changed Normalize to alter the current instance
-- - added return self to the various arithemtic operations
-- - disabled querying of the metatable from the outside
local type = type
local sin = math.sin
local cos = math.cos
local atan2 = math.atan2
local deg = math.deg
-- Meta table.
local vector_prototype = {}
local vector_mt = { __index = vector_prototype }
vector_mt.__metatable = false -- disable accessing of the metatable
-- Divran's idea.
local function new(x,y,z)
return setmetatable( {x = x or 0, y = y or 0, z = z or 0} , vector_mt)
end
local Vector3 = new
function vector_mt:__add( vector )
return new(
self.x + vector.x,
self.y + vector.y,
self.z + vector.z
)
end
function vector_mt:__sub( vector )
return new(
self.x - vector.x,
self.y - vector.y,
self.z - vector.z
)
end
function vector_mt:__mul( vector )
if type(vector) == "number" then
return new(
self.x * vector,
self.y * vector,
self.z * vector
)
else
return new(
self.x * vector.x,
self.y * vector.y,
self.z * vector.z
)
end
end
function vector_mt:__div( vector )
if type(vector) == "number" then
return new(
self.x / vector,
self.y / vector,
self.z / vector
)
else
return new(
self.x / vector.x,
self.y / vector.y,
self.z / vector.z
)
end
end
--
-- Boolean operators
--
function vector_mt:__eq( vector )
return self.x == vector.x and self.y == vector.y and self.z == vector.z
end
function vector_mt:__unm()
return new(-self.x,-self.y,-self.z)
end
--
-- String Operators.
--
function vector_mt:__tostring()
return "[" .. self.x .. "," .. self.y .. "," .. self.z .. "]"
end
--
-- Vector operator functions.
--
-- TODO: this doesn't change the current instance (self is a private variable), fix
function vector_prototype:Add( vector )
self = self + vector
return self
end
-- TODO: this doesn't change the current instance (self is a private variable), fix
function vector_prototype:Sub( vector )
self = self - vector
return self
end
function vector_prototype:Mul( n )
self.x = self.x * n
self.y = self.y * n
self.z = self.z * n
return self
end
function vector_prototype:Zero()
self.x = 0
self.y = 0
self.z = 0
return self
end
function vector_prototype:LengthSqr()
return ( ( self.x * self.x ) + ( self.y * self.y ) + ( self.z * self.z ) )
end
function vector_prototype:Length()
return self:LengthSqr() ^ 0.5
end
-- This should really be named get normalised copy.
function vector_prototype:GetNormal()
local length = self:Length()
return new( self.x / length, self.y / length, self.z / length )
end
-- Redirect for people doing it wrong.
function vector_prototype:GetNormalized()
return self:GetNormal()
end
function vector_prototype:Normalize()
local length = self:Length()
return self:Mul(1 / length)
end
function vector_prototype:DotProduct( vector )
return (self.x * vector.x) + (self.y * vector.y) + (self.z * vector.z)
end
-- Redirect for people doing it wrong.
function vector_prototype:Dot( vector )
return self:DotProduct( vector )
end
-- Cross Product.
function vector_prototype:Cross( vector )
local vec = new(0,0,0)
vec.x = ( self.y * vector.z ) - ( vector.y * self.z )
vec.y = ( self.z * vector.x ) - ( vector.z * self.x )
vec.z = ( self.x * vector.y ) - ( vector.x * self.y )
return vec
end
-- Returns the distance between two vectors.
function vector_prototype:Distance( vector )
local vec = self - vector
return vec:Length()
end
-- Convert vector in 2D heading in degrees between 0-360
function vector_prototype:ToHeading()
local angleInRads = atan2(self.x, self.z)
return (deg(angleInRads) % 360)
end
-- Rotate vector around Y axis by given angle in degrees
function vector_prototype:Rotate2D(angle)
local vec = new(0,0,0)
vec.x = self.x * cos(angle) - self.z * sin(angle)
vec.y = self.y
vec.z = self.x * sin(angle) - self.z * cos(angle)
return vec
end
function vector_prototype:AsSpringVector()
return { self.x, self.y, self.z }
end
return Vector3
|
-- A 3D Vector Library.
-- By Gordon MacPherson with the assistance of google and sir divran! :L
-- changes by: Michal Mojzk
-- - adapted to be compatible BtUtils by
-- - fixed methods to belong into the __index lookup table rather than the metatable itself
-- - added LengthSqr
-- - changed Normalize to alter the current instance
-- - added return self to the various arithemtic operations
-- - disabled querying of the metatable from the outside
local type = type
local sin = math.sin
local cos = math.cos
local atan2 = math.atan2
local deg = math.deg
local rad = math.rad
-- Meta table.
local vector_prototype = {}
local vector_mt = { __index = vector_prototype }
vector_mt.__metatable = false -- disable accessing of the metatable
-- Divran's idea.
local function new(x,y,z)
return setmetatable( {x = x or 0, y = y or 0, z = z or 0} , vector_mt)
end
local Vector3 = new
function vector_mt:__add( vector )
return new(
self.x + vector.x,
self.y + vector.y,
self.z + vector.z
)
end
function vector_mt:__sub( vector )
return new(
self.x - vector.x,
self.y - vector.y,
self.z - vector.z
)
end
function vector_mt:__mul( vector )
if type(vector) == "number" then
return new(
self.x * vector,
self.y * vector,
self.z * vector
)
else
return new(
self.x * vector.x,
self.y * vector.y,
self.z * vector.z
)
end
end
function vector_mt:__div( vector )
if type(vector) == "number" then
return new(
self.x / vector,
self.y / vector,
self.z / vector
)
else
return new(
self.x / vector.x,
self.y / vector.y,
self.z / vector.z
)
end
end
--
-- Boolean operators
--
function vector_mt:__eq( vector )
return self.x == vector.x and self.y == vector.y and self.z == vector.z
end
function vector_mt:__unm()
return new(-self.x,-self.y,-self.z)
end
--
-- String Operators.
--
function vector_mt:__tostring()
return "[" .. self.x .. "," .. self.y .. "," .. self.z .. "]"
end
--
-- Vector operator functions.
--
-- TODO: this doesn't change the current instance (self is a private variable), fix
function vector_prototype:Add( vector )
self = self + vector
return self
end
-- TODO: this doesn't change the current instance (self is a private variable), fix
function vector_prototype:Sub( vector )
self = self - vector
return self
end
function vector_prototype:Mul( n )
self.x = self.x * n
self.y = self.y * n
self.z = self.z * n
return self
end
function vector_prototype:Zero()
self.x = 0
self.y = 0
self.z = 0
return self
end
function vector_prototype:LengthSqr()
return ( ( self.x * self.x ) + ( self.y * self.y ) + ( self.z * self.z ) )
end
function vector_prototype:Length()
return self:LengthSqr() ^ 0.5
end
-- This should really be named get normalised copy.
function vector_prototype:GetNormal()
local length = self:Length()
return new( self.x / length, self.y / length, self.z / length )
end
-- Redirect for people doing it wrong.
function vector_prototype:GetNormalized()
return self:GetNormal()
end
function vector_prototype:Normalize()
local length = self:Length()
return self:Mul(1 / length)
end
function vector_prototype:DotProduct( vector )
return (self.x * vector.x) + (self.y * vector.y) + (self.z * vector.z)
end
-- Redirect for people doing it wrong.
function vector_prototype:Dot( vector )
return self:DotProduct( vector )
end
-- Cross Product.
function vector_prototype:Cross( vector )
local vec = new(0,0,0)
vec.x = ( self.y * vector.z ) - ( vector.y * self.z )
vec.y = ( self.z * vector.x ) - ( vector.z * self.x )
vec.z = ( self.x * vector.y ) - ( vector.x * self.y )
return vec
end
-- Returns the distance between two vectors.
function vector_prototype:Distance( vector )
local vec = self - vector
return vec:Length()
end
-- Convert vector in 2D heading in degrees between 0-360
function vector_prototype:ToHeading()
local angleInRads = atan2(self.x, self.z)
return (deg(angleInRads) % 360)
end
-- Rotate vector around Y axis by given angle in degrees 0-360 (clockwise)
function vector_prototype:Rotate2D(angle)
local angleInRads = rad(-angle) -- -1 for clockwise rotation (but input is positive number)
local vec = new(0,0,0)
vec.x = self.x * cos(angleInRads) - self.z * sin(angleInRads)
vec.y = self.y
vec.z = self.x * sin(angleInRads) + self.z * cos(angleInRads)
return vec
end
function vector_prototype:AsSpringVector()
return { self.x, self.y, self.z }
end
return Vector3
|
fixing Rotate2D method to work with radians instead of degrees + using clockwise rotation interpretation instead of the opposite one
|
fixing Rotate2D method to work with radians instead of degrees + using clockwise rotation interpretation instead of the opposite one
|
Lua
|
mit
|
MartinFrancu/BETS
|
06d14c94e02f2568dc5f0e21604bebfcf13080fa
|
GameOfLife/main.lua
|
GameOfLife/main.lua
|
require("turtle")
require("wx")
require("dvdlualib/common")
local life = require("dvdlualib/lifelib")
io.stdout:setvbuf("no")
function TurtleDraw(F,Arg)
local sx = 0
local sy = 15
local fx = F:getW()
local fy = F:getH()
local dx = (Arg[1]-sx)/fx
local dy = (Arg[2]-sy)/fy
local x,y = 1,1
local i = 1
local Arr = F:getArray()
wipe()
text("Generation: "..(F:getGenerations() or "N/A").." {"..tostring(Arg[3])..
","..tostring(Arg[4]).."} > "..tostring(Arg[5]),0,0,0)
while(Arr[i]) do
local v = Arr[i]
local j = 1
x = 1
while(v[j]) do
if(v[j] == 1) then
rect(x+sx,y+sy,dx,dy,0)
end
x = x + dx
j = j + 1
end
y = y + dy
i = i + 1
end
end
function getKeyboardKeyNonBlock()
local Ch = io.read(1)
io.write("\n\r")
return Ch
end
local Arg = {200, 100,0,0}
open("Game Of Life")
size(Arg[1],Arg[2])
updt(true)
zero(0, 0)
life.shapesPath("GameOfLife/shapes/")
local F = life.makeField(60,25)
F:RegisterDraw("turtle",TurtleDraw)
local GG = life.makeShape(life.initFileRle("gosperglidergun"))
io.write(tostring(GG))
-- For click detect
Arg[3] = 10
Arg[4] = 57
Arg[5] = ""
F:Spawn(GG,X,Y)
F:Draw("turtle",Arg)
while true do
Arg[5] = char()
F:Draw("turtle",Arg)
F:Evolve()
end
|
require("turtle")
require("wx")
require("dvdlualib/common")
local life = require("dvdlualib/lifelib")
io.stdout:setvbuf("no")
function TurtleDraw(F,Arg)
local sx = 0
local sy = 18
local fx = F:getW()
local fy = F:getH()
local dx = (Arg[1]-sx)/fx
local dy = (Arg[2]-sy)/fy
local x,y = 0,0
local i = 1
local Arr = F:getArray()
wipe()
text("Generation: "..(F:getGenerations() or "N/A").." {"..tostring(Arg[3])..
","..tostring(Arg[4]).."} > "..tostring(Arg[5]),0,0,0)
while(Arr[i]) do
local v = Arr[i]
local j = 1
x = 0
while(v[j]) do
if(v[j] == 1) then
rect(x+sx,y+sy,dx,dy,0)
end
x = x + dx
j = j + 1
end
y = y + dy
i = i + 1
end
rect(sx,sy,x,y,0)
end
function getKeyboardKeyNonBlock()
local Ch = io.read(1)
io.write("\n\r")
return Ch
end
local Arg = {200, 100,0,0}
open("Game Of Life")
size(Arg[1],Arg[2])
updt(true)
zero(0, 0)
life.shapesPath("GameOfLife/shapes/")
local F = life.makeField(60,25)
F:RegisterDraw("turtle",TurtleDraw)
local GG = life.makeShape(life.initFileRle("gosperglidergun"))
io.write(tostring(GG))
-- For click detect
Arg[3] = 10
Arg[4] = 57
Arg[5] = ""
F:Spawn(GG,X,Y)
F:Draw("turtle",Arg)
while true do
Arg[5] = char()
F:Draw("turtle",Arg)
F:Evolve()
end
|
Fixed Turtle life draw having wrong y end
|
Fixed Turtle life draw having wrong y end
|
Lua
|
apache-2.0
|
dvdvideo1234/ZeroBraineProjects
|
28f329f314029d6381fac184c7e764195f9835ff
|
src/extensions/cp/ui/Menu.lua
|
src/extensions/cp/ui/Menu.lua
|
--- === cp.ui.Menu ===
---
--- UI for AXMenus.
local require = require
local Element = require("cp.ui.Element")
local go = require "cp.rx.go"
local If, WaitUntil = go.If, go.WaitUntil
local find = string.find
-- TIMEOUT_AFTER -> number
-- Constant
-- The common timeout amount in milliseconds.
local TIMEOUT_AFTER = 3000
--- cp.ui.Menu(parent, uiFinder) -> Menu
--- Constructor
--- Creates a new `Menu` instance.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - A function which will return the `hs.axuielement` when available.
---
--- Returns:
--- * A new `Menu` object.
local Menu = Element:subclass("cp.ui.Menu")
--- cp.ui.Menu.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function Menu.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXMenu"
end
--- cp.ui.Menu:cancel() -> self
--- Method
--- Closes a menu.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function Menu:cancel()
local ui = self:UI()
if ui then
ui:performAction("AXCancel")
end
return self
end
function Menu:doCancel()
return If(self.UI)
:Then(function(ui)
ui:performAction("AXCancel")
end)
:Then(WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER))
:Otherwise(false)
:Label("Menu:doCancel")
end
--- cp.ui.Menu:doSelectItem(index) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `MenuButton` by index.
---
--- Parameters:
--- * index - The index number of the item to match.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectItem(index)
return If(self.UI)
:Then(function(ui)
local item = ui[index]
if item then
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
else
return self:doCancel()
end
end)
:Then()
:Otherwise(false)
:Label("Menu:doSelectItem")
end
--- cp.ui.Menu:doSelectValue(value) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `Menu` by value.
---
--- Parameters:
--- * value - The value of the item to match.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectValue(value)
return If(self.UI)
:Then(function(ui)
for _,item in ipairs(ui) do
if item:title() == value then
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
end
end
return self:doCancel():Then(false)
end)
:Otherwise(false)
:Label("Menu:doSelectValue")
end
--- cp.ui.Menu:doSelectValue(pattern[, altPattern]) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `Menu` by value.
---
--- Parameters:
--- * pattern - The pattern to match.
--- * [altPattern] - An optional alternate pattern to match if the first pattern fails.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectItemMatching(pattern, altPattern)
return If(self.UI)
:Then(function(ui)
local patterns = {pattern}
if altPattern then table.insert(patterns, altPattern) end
for _, selectedPattern in pairs(patterns) do
for _,item in ipairs(ui) do
local title = item:attributeValue("AXTitle")
if title then
local s,e = find(title, selectedPattern)
if s == 1 and e == title:len() then
-- perfect match
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
end
end
end
end
return self:doCancel():Then(false)
end)
:Otherwise(false)
:Label("Menu:doSelectItemMatching")
end
return Menu
|
--- === cp.ui.Menu ===
---
--- UI for AXMenus.
local require = require
local Element = require "cp.ui.Element"
local go = require "cp.rx.go"
local find = string.find
local If = go.If
local WaitUntil = go.WaitUntil
-- TIMEOUT_AFTER -> number
-- Constant
-- The common timeout amount in milliseconds.
local TIMEOUT_AFTER = 3000
--- cp.ui.Menu(parent, uiFinder) -> Menu
--- Constructor
--- Creates a new `Menu` instance.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - A function which will return the `hs.axuielement` when available.
---
--- Returns:
--- * A new `Menu` object.
local Menu = Element:subclass("cp.ui.Menu")
--- cp.ui.Menu.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function Menu.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXMenu"
end
--- cp.ui.Menu:cancel() -> self
--- Method
--- Closes a menu.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function Menu:cancel()
local ui = self:UI()
if ui then
ui:performAction("AXCancel")
end
return self
end
--- cp.ui.Menu:doCancel(value) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will cancel a menu.
---
--- Parameters:
--- * None
---
--- Returns:
--- * the `Statement`.
function Menu:doCancel()
return If(self.UI)
:Then(function(ui)
ui:performAction("AXCancel")
end)
:Then(WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER))
:Otherwise(false)
:Label("Menu:doCancel")
end
--- cp.ui.Menu:doSelectItem(index) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `MenuButton` by index.
---
--- Parameters:
--- * index - The index number of the item to match.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectItem(index)
return If(self.UI)
:Then(function(ui)
local item = ui[index]
if item then
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
else
return self:doCancel()
end
end)
:Then()
:Otherwise(false)
:Label("Menu:doSelectItem")
end
--- cp.ui.Menu:doSelectValue(value) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `Menu` by value.
---
--- Parameters:
--- * value - The value of the item to match.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectValue(value)
return If(self.UI)
:Then(function(ui)
for _, item in ipairs(ui) do
local title = item:attributeValue("AXTitle")
if title == value then
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
end
end
return self:doCancel():Then(false)
end)
:Otherwise(false)
:Label("Menu:doSelectValue")
end
--- cp.ui.Menu:doSelectValue(pattern[, altPattern]) -> cp.rx.go.Statement
--- Method
--- A [Statement](cp.rx.go.Statement.md) that will select an item on the `Menu` by value.
---
--- Parameters:
--- * pattern - The pattern to match.
--- * [altPattern] - An optional alternate pattern to match if the first pattern fails.
---
--- Returns:
--- * the `Statement`.
function Menu:doSelectItemMatching(pattern, altPattern)
return If(self.UI)
:Then(function(ui)
local patterns = {pattern}
if altPattern then table.insert(patterns, altPattern) end
for _, selectedPattern in pairs(patterns) do
for _,item in ipairs(ui) do
local title = item:attributeValue("AXTitle")
if title then
local s,e = find(title, selectedPattern)
if s == 1 and e == title:len() then
-- perfect match
item:doAXPress()
return WaitUntil(self.isShowing):Is(false):TimeoutAfter(TIMEOUT_AFTER)
end
end
end
end
return self:doCancel():Then(false)
end)
:Otherwise(false)
:Label("Menu:doSelectItemMatching")
end
return Menu
|
Fixed a bug in cp.ui.Menu that broke "Show Horizon" action
|
Fixed a bug in cp.ui.Menu that broke "Show Horizon" action
- Closes #2561
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
|
5059a52d1ea15a6228f11d92c3b48b74cadc5cb4
|
item/id_220_barrel.lua
|
item/id_220_barrel.lua
|
-- white dye (2683) + gray cloth (176) --> white cloth (178)
-- color dye + (white cloth (178) or grey cloth (176) --> colored cloth (see below for details)
-- additional tool: dyeing rod (2781)
-- UPDATE common SET com_script='item.id_220_barrel' WHERE com_itemid IN (220);
require("base.common")
require("content.gathering")
require("base.licence")
module("item.id_220_barrel", package.seeall)
-- format: {dyeID, neededClothID, producedClothID}
dyersList = {
{2678, {178, 176}, 175}, -- black
{2679, {178, 176}, 54}, -- green
{2680, {178, 176}, 179}, -- blue
{2681, {178, 176}, 174}, -- red
{2682, {178, 176}, 177}, -- yellow
{2683, {176,0}, 178} -- white
};
function UseItem(User, SourceItem, ltstate)
if base.licence.licence(User) then --checks if user is citizen or has a licence
return -- avoids crafting if user is neither citizen nor has a licence
end
content.gathering.InitGathering();
local dyeing = content.gathering.dyeing;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talk(Character.say, "#me unterbricht "..gText.." Arbeit.", "#me interrupts "..eText.." work.")
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
-- additional tool item is needed
if (User:countItemAt("all",2781)==0) then
base.common.HighInformNLS( User,
"Du brauchst einen Frberstab um Stoffe zu frben.",
"You need a dyeing rod for dyeing cloth." );
return
end
local toolItem = User:getItemAt(5);
if ( toolItem.id ~= 2781 ) then
toolItem = User:getItemAt(6);
if ( toolItem.id ~= 2781 ) then
base.common.HighInformNLS( User,
"Du musst den Frberstab in der Hand haben!",
"You have to hold the dyeing rod in your hand!" );
return
end
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
if not base.common.IsLookingAt( User, SourceItem.pos ) then -- check looking direction
base.common.TurnTo( User, SourceItem.pos ); -- turn if necessary
end
-- any other checks?
local dye = nil;
for _,d in pairs(dyersList) do
if (User:countItemAt("all",d[1])>0 and (User:countItemAt("all",d[2][1])>0 or User:countItemAt("all",d[2][2])>0)) then
dye = d;
break;
end
end
if (dye == nil) then -- check for items to work on
base.common.HighInformNLS( User,
"Du brauchst weie Farbe und grauen Stoff oder eine andere Farbe und weien oder grauen Stoff um zu frben.",
"You need white dye and grey cloth or any other dye and white or grey cloth for dyeing." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
dyeing.SavedWorkTime[User.id] = dyeing:GenWorkTime(User,toolItem);
User:startAction( dyeing.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talk(Character.say, "#me beginnt Stoff zu frben.", "#me starts to dye cloth.")
return
end
-- since we're here, we're working
if dyeing:FindRandomItem(User) then
return
end
User:learn( dyeing.LeadSkill, dyeing.SavedWorkTime[User.id], dyeing.LearnLimit);
User:eraseItem( dye[1], 1 ); -- erase the item we're working on
if User:countItemAt("all",dye[2][2]) == 0 then
User:eraseItem( dye[2][1], 5 ); -- erase the item we're working on
else
User:eraseItem( dye[2][2], 5 ); -- erase the item we're working on
end
local amount = 5; -- set the amount of items that are produced
local notCreated = User:createItem( dye[3], amount, 333, nil ); -- create the new produced items
User:createItem( 51, 1, 333, nil ); -- giving back the bucket
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( dye[3], notCreated, User.pos, true, 333, nil );
world:createItemFromId( 51, notCreated, User.pos, true, 333, nil ); -- giving back the bucket
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
dye = nil;
for _,d in pairs(dyersList) do
if (User:countItemAt("all",d[1])>0 and (User:countItemAt("all",d[2][1])>0 or User:countItemAt("all",d[2][2])>0)) then
dye = d;
break;
end
end
if (dye ~= nil) then -- there are still items we can work on
dyeing.SavedWorkTime[User.id] = dyeing:GenWorkTime(User,toolItem);
User:startAction( dyeing.SavedWorkTime[User.id], 0, 0, 0, 0);
else -- no items left
base.common.HighInformNLS(User,
"Du hast keine Farbe und passenden Stoff mehr.",
"You have no dye and respective cloth anymore.");
end
end
if base.common.GatheringToolBreaks( User, toolItem ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Dein alter Frberstab zerbricht.",
"Your old dyeing rod breaks.");
return
end
end
|
-- white dye (2683) + gray cloth (176) --> white cloth (178)
-- color dye + (white cloth (178) or grey cloth (176) --> colored cloth (see below for details)
-- additional tool: dyeing rod (2781)
-- UPDATE common SET com_script='item.id_220_barrel' WHERE com_itemid IN (220);
require("base.common")
require("content.gathering")
require("base.licence")
module("item.id_220_barrel", package.seeall)
-- format: {dyeID, neededClothID, producedClothID}
dyersList = {
{2678, {178, 176}, 175}, -- black
{2679, {178, 176}, 54}, -- green
{2680, {178, 176}, 179}, -- blue
{2681, {178, 176}, 174}, -- red
{2682, {178, 176}, 177}, -- yellow
{2683, {176,0}, 178} -- white
};
function UseItem(User, SourceItem, ltstate)
if base.licence.licence(User) then --checks if user is citizen or has a licence
return -- avoids crafting if user is neither citizen nor has a licence
end
content.gathering.InitGathering();
local dyeing = content.gathering.dyeing;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talk(Character.say, "#me unterbricht "..gText.." Arbeit.", "#me interrupts "..eText.." work.")
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
-- additional tool item is needed
if (User:countItemAt("all",2781)==0) then
base.common.HighInformNLS( User,
"Du brauchst einen Frberstab um Stoffe zu frben.",
"You need a dyeing rod for dyeing cloth." );
return
end
local toolItem = User:getItemAt(5);
if ( toolItem.id ~= 2781 ) then
toolItem = User:getItemAt(6);
if ( toolItem.id ~= 2781 ) then
base.common.HighInformNLS( User,
"Du musst den Frberstab in der Hand haben!",
"You have to hold the dyeing rod in your hand!" );
return
end
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
if not base.common.IsLookingAt( User, SourceItem.pos ) then -- check looking direction
base.common.TurnTo( User, SourceItem.pos ); -- turn if necessary
end
-- any other checks?
local dye = nil;
for _,d in pairs(dyersList) do
if (User:countItemAt("all",d[1])>0 and (User:countItemAt("all",d[2][1])>0 or User:countItemAt("all",d[2][2])>0)) then
dye = d;
break;
end
end
if (dye == nil) then -- check for items to work on
base.common.HighInformNLS( User,
"Du brauchst weie Farbe und grauen Stoff oder eine andere Farbe und weien oder grauen Stoff um zu frben.",
"You need white dye and grey cloth or any other dye and white or grey cloth for dyeing." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
dyeing.SavedWorkTime[User.id] = dyeing:GenWorkTime(User,toolItem);
User:startAction( dyeing.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talk(Character.say, "#me beginnt Stoff zu frben.", "#me starts to dye cloth.")
return
end
-- since we're here, we're working
if dyeing:FindRandomItem(User) then
return
end
User:learn( dyeing.LeadSkill, dyeing.SavedWorkTime[User.id], dyeing.LearnLimit);
User:eraseItem( dye[1], 1 ); -- erase the item we're working on
if User:countItemAt("all",dye[2][2]) == 0 then
User:eraseItem( dye[2][1], 5 ); -- erase the item we're working on
else
User:eraseItem( dye[2][2], 5 ); -- erase the item we're working on
end
local amount = 5; -- set the amount of items that are produced
local notCreated = User:createItem( dye[3], amount, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( dye[3], notCreated, User.pos, true, 333, nil );
world:createItemFromId( 51, 1, User.pos, true, 333, nil ); -- giving back the bucket
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
notCreated = User:createItem( 51, 1, 333, nil ); -- giving back the bucket
if ( notCreated > 0 ) then
world:createItemFromId( 51, 1, User.pos, true, 333, nil );
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
end
end
if (notCreated == 0) then -- character can go on
dye = nil;
for _,d in pairs(dyersList) do
if (User:countItemAt("all",d[1])>0 and (User:countItemAt("all",d[2][1])>0 or User:countItemAt("all",d[2][2])>0)) then
dye = d;
break;
end
end
if (dye ~= nil) then -- there are still items we can work on
dyeing.SavedWorkTime[User.id] = dyeing:GenWorkTime(User,toolItem);
User:startAction( dyeing.SavedWorkTime[User.id], 0, 0, 0, 0);
else -- no items left
base.common.HighInformNLS(User,
"Du hast keine Farbe und passenden Stoff mehr.",
"You have no dye and respective cloth anymore.");
end
end
if base.common.GatheringToolBreaks( User, toolItem ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Dein alter Frberstab zerbricht.",
"Your old dyeing rod breaks.");
return
end
end
|
fix bucket return
|
fix bucket return
* drop bucket to the ground, if space left for cloth but not for bucket (Mantis 0009447)
* drop only 1 bucket, if no space left for cloth+bucket
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content
|
186099ba954e31e49e330abb1b621ec2e4aa75a2
|
solver/selfgrav.lua
|
solver/selfgrav.lua
|
local class = require 'ext.class'
local Poisson = require 'solver.poisson'
local SelfGrav = class(Poisson)
SelfGrav.gravityConstant = 1 ---- 6.67384e-11 m^3 / (kg s^2)
-- params for solver/poisson.cl
function SelfGrav:getCodeParams()
return {
args = 'const global cons_t* UBuf',
calcRho = '#define gravitationalConstant '..require 'clnumber'(self.gravityConstant)..'\n'..[[
const global cons_t* U = UBuf + index;
rho = gravitationalConstant * U->rho; //maybe a 4pi? or is that only in the continuous case?
]],
}
end
SelfGrav.extraCode = [[
kernel void calcGravityDeriv(
global cons_t* derivBuffer,
const global cons_t* UBuf,
const global real* ePotBuf
) {
SETBOUNDS(2,2);
global cons_t* deriv = derivBuffer + index;
const global cons_t* U = UBuf + index;
//for (int side = 0; side < dim; ++side) {
<? for side=0,solver.dim-1 do ?>{
const int side = <?=side?>;
int indexL = index - stepsize[side];
int indexR = index + stepsize[side];
real gradient = (ePotBuf[indexR] - ePotBuf[indexL]) / (2. * dx<?=side?>_at(i));
real gravity = -gradient;
deriv->m.s[side] -= U->rho * gravity;
deriv->ETotal -= U->rho * gravity * U->m.s[side];
}<? end ?>
}
]]
function SelfGrav:refreshSolverProgram()
SelfGrav.super.refreshSolverProgram(self)
local solver = self.solver
solver.calcGravityDerivKernel = solver.solverProgram:kernel'calcGravityDeriv'
solver.calcGravityDerivKernel:setArg(1, solver.UBuf)
solver.calcGravityDerivKernel:setArg(2, solver.ePotBuf)
end
local field = 'gravityPoisson'
local enableField = 'useGravity'
local apply = SelfGrav:createBehavior(field, enableField)
return function(parent)
local template = apply(parent)
function template:step(dt)
template.super.step(self, dt)
if not self[enableField] then return end
self.integrator:integrate(dt, function(derivBuf)
self[field]:relax()
self.calcGravityDerivKernel:setArg(0, derivBuf)
self.app.cmds:enqueueNDRangeKernel{kernel=self.calcGravityDerivKernel, dim=self.dim, globalSize=self.gridSize:ptr(), localSize=self.localSize:ptr()}
end)
end
return template
end
|
local class = require 'ext.class'
local Poisson = require 'solver.poisson'
local SelfGrav = class(Poisson)
SelfGrav.gravityConstant = 1 ---- 6.67384e-11 m^3 / (kg s^2)
-- params for solver/poisson.cl
function SelfGrav:getCodeParams()
return {
args = 'const global '..self.solver.eqn.cons_t..'* UBuf',
calcRho = '#define gravitationalConstant '..require 'clnumber'(self.gravityConstant)..'\n'..[[
const global <?=eqn.cons_t?>* U = UBuf + index;
rho = gravitationalConstant * U->rho; //maybe a 4pi? or is that only in the continuous case?
]],
solver = self.solver,
eqn = self.solver.eqn,
}
end
SelfGrav.extraCode = [[
kernel void calcGravityDeriv(
global <?=eqn.cons_t?>* derivBuffer,
const global <?=eqn.cons_t?>* UBuf,
const global real* ePotBuf
) {
SETBOUNDS(2,2);
global <?=eqn.cons_t?>* deriv = derivBuffer + index;
const global <?=eqn.cons_t?>* U = UBuf + index;
//for (int side = 0; side < dim; ++side) {
<? for side=0,solver.dim-1 do ?>{
const int side = <?=side?>;
int indexL = index - stepsize[side];
int indexR = index + stepsize[side];
real gradient = (ePotBuf[indexR] - ePotBuf[indexL]) / (2. * dx<?=side?>_at(i));
real gravity = -gradient;
deriv->m.s[side] -= U->rho * gravity;
deriv->ETotal -= U->rho * gravity * U->m.s[side];
}<? end ?>
}
]]
function SelfGrav:refreshSolverProgram()
SelfGrav.super.refreshSolverProgram(self)
local solver = self.solver
solver.calcGravityDerivKernel = solver.solverProgram:kernel'calcGravityDeriv'
solver.calcGravityDerivKernel:setArg(1, solver.UBuf)
solver.calcGravityDerivKernel:setArg(2, solver.ePotBuf)
end
local field = 'gravityPoisson'
local enableField = 'useGravity'
local apply = SelfGrav:createBehavior(field, enableField)
return function(parent)
local template = apply(parent)
function template:step(dt)
template.super.step(self, dt)
if not self[enableField] then return end
self.integrator:integrate(dt, function(derivBuf)
self[field]:relax()
self.calcGravityDerivKernel:setArg(0, derivBuf)
self.app.cmds:enqueueNDRangeKernel{kernel=self.calcGravityDerivKernel, dim=self.dim, globalSize=self.gridSize:ptr(), localSize=self.localSize:ptr()}
end)
end
return template
end
|
and the last of the fixed types
|
and the last of the fixed types
|
Lua
|
mit
|
thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua
|
3e88201e15960bac22e0f5ac10b570c7e9469220
|
lib/luvit/utils.lua
|
lib/luvit/utils.lua
|
--[[
Copyright 2012 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 table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carriage, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carriage = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("B", '[')
cbracket = utils.colorize("B", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carriage):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local argsLength = select("#", ...)
-- Simple binding, just inserts self.
if argsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- This table will get mutated on every call, but it's async safe and the
-- unpack fence will only use the fresh data so it's ok.
local args = {...}
return function (...)
local extraLength = select("#", ...)
local extra = {...}
for i = 1, extraLength do
args[i + argsLength] = extra[i]
end
return fn(self, unpack(args, 1, argsLength + extraLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
--[[
Copyright 2012 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 table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carriage, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carriage = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("B", '[')
cbracket = utils.colorize("B", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carriage):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local bindArgsLength = select("#", ...)
-- Simple binding, just inserts self (or one arg or any kind)
if bindArgsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- More complex binding inserts arbitrary number of args into call.
local bindArgs = {...}
return function (...)
local argsLength = select("#", ...)
local args = {...}
local arguments = {}
for i = 1, bindArgsLength do
arguments[i] = bindArgs[i]
end
for i = 1, argsLength do
arguments[i + bindArgsLength] = args[i]
end
return fn(self, unpack(arguments, 1, bindArgsLength + argsLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
Fix memory leak in utils.bind
|
Fix memory leak in utils.bind
|
Lua
|
apache-2.0
|
bsn069/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,DBarney/luvit,AndrewTsao/luvit,sousoux/luvit,sousoux/luvit,boundary/luvit,kaustavha/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,AndrewTsao/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,sousoux/luvit,boundary/luvit,sousoux/luvit,connectFree/lev,DBarney/luvit,sousoux/luvit,kaustavha/luvit,sousoux/luvit,DBarney/luvit,boundary/luvit,AndrewTsao/luvit,connectFree/lev,zhaozg/luvit,bsn069/luvit,rjeli/luvit,luvit/luvit,kaustavha/luvit,boundary/luvit,rjeli/luvit
|
abe1926d7501b6f8d510db754157969e5cde186f
|
[resources]/GTWgui/s_refresh.lua
|
[resources]/GTWgui/s_refresh.lua
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: https://forum.404rq.com/bug-reports/
Suggestions: https://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- List of resources to refresh
restart_list = { }
--[[ Load list from HDD and apply GUI ]]--
function load_list(res)
--[[ Load dynamic list of resources to refresh ]]--
restart_list = getElementData(root, "GTWgui.refreshList")
--[[ Restart all resources using this GUI system ]]--
for k, v in pairs(restart_list) do
if getResourceFromName(k) then
restartResource(getResourceFromName(k))
outputServerLog("GTWgui: refreshed: '"..k.."'")
end
end
--[[ Inform online players that this refresh may cause some lag ]]--
if not getResourceFromName("GTWtopbar") then return end
exports.GTWtopbar:dm("Restarting GUI system, you may notice some lag for a few seconds, please be patient...", root, 255, 100, 0)
end
addEventHandler("onResourceStart", resourceRoot, load_list)
--[[ Save refresh array in HDD ]]--
function save_list(res)
setElementData(root, "GTWgui.refreshList", restart_list)
end
addEventHandler("onResourceStop", resourceRoot, save_list)
--[[ Add missing resource to dynamic refresh list
Use: exports, triggerEvent or triggerServerEvent
(client) to add a resource ]]--
function addToRefreshList(res_str)
restartList[res_str]=true
end
addEvent("GTWgui.addToRefreshList", true)
addEventHandler("GTWgui.addToRefreshList", resourceRoot, addToRefreshList)
addCommandHandler("gtwinfo", function(plr, cmd)
outputChatBox("[GTW-RPG] "..getResourceName(
getThisResource())..", by: "..getResourceInfo(
getThisResource(), "author")..", v-"..getResourceInfo(
getThisResource(), "version")..", is represented", plr)
end)
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: https://forum.404rq.com/bug-reports/
Suggestions: https://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- List of resources to refresh
restart_list = { }
--[[ Load list from HDD and apply GUI ]]--
function load_list(res)
--[[ Load dynamic list of resources to refresh ]]--
restart_list = getElementData(root, "GTWgui.refreshList")
--[[ Don't do anything if the table doesn't exist (mainly onResourceStart)]]
if not resource_list then
setTimer( load_list, 2500, 1 )
return
end
--[[ Restart all resources using this GUI system ]]--
for k, v in pairs(restart_list) do
if getResourceFromName(k) then
restartResource(getResourceFromName(k))
outputServerLog("GTWgui: refreshed: '"..k.."'")
end
end
--[[ Inform online players that this refresh may cause some lag ]]--
if not getResourceFromName("GTWtopbar") then return end
exports.GTWtopbar:dm("Restarting GUI system, you may notice some lag for a few seconds, please be patient...", root, 255, 100, 0)
end
addEventHandler("onResourceStart", resourceRoot, load_list)
--[[ Save refresh array in HDD ]]--
function save_list(res)
setElementData(root, "GTWgui.refreshList", restart_list)
end
addEventHandler("onResourceStop", resourceRoot, save_list)
--[[ Add missing resource to dynamic refresh list
Use: exports, triggerEvent or triggerServerEvent
(client) to add a resource ]]--
function addToRefreshList(res_str)
restartList[res_str]=true
end
addEvent("GTWgui.addToRefreshList", true)
addEventHandler("GTWgui.addToRefreshList", resourceRoot, addToRefreshList)
addCommandHandler("gtwinfo", function(plr, cmd)
outputChatBox("[GTW-RPG] "..getResourceName(
getThisResource())..", by: "..getResourceInfo(
getThisResource(), "author")..", v-"..getResourceInfo(
getThisResource(), "version")..", is represented", plr)
end)
|
Again a small fix
|
Again a small fix
|
Lua
|
bsd-2-clause
|
404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG
|
9369c58ee1032042e1350323ac76c435bef52a12
|
src/cosy/email.lua
|
src/cosy/email.lua
|
local Configuration = require "cosy.configuration"
local CSocket = require "cosy.socket"
local I18n = require "cosy.i18n"
local Logger = require "cosy.logger"
local Scheduler = require "cosy.scheduler"
local Socket = require "socket"
local Smtp = require "socket.smtp"
local Ssl = require "ssl"
if not Ssl then
Ssl = _G.ssl
end
Configuration.load "cosy.email"
local i18n = I18n.load "cosy.email"
i18n._locale = Configuration.locale._
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local result = Socket.tcp ()
result:settimeout (Configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local result = CSocket ()
result:settimeout (Configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = Ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self.socket:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return nil, "connection failed"
end
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = Ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self.socket:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local domain = Configuration.server.root._
local host = Configuration.smtp.host._
local username = Configuration.smtp.username._
local password = Configuration.smtp.password._
local methods = { Configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { Configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { Configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
Logger.debug {
_ = i18n ["smtp:discover"],
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (Smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
Configuration.smtp.port = port
Configuration.smtp.method = method
Configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
Scheduler.addthread (function ()
local locale = message.locale or Configuration.locale.default._
local si18n = I18n.new (locale)
message.from = si18n (message.from )
message.to = si18n (message.to )
message.subject = si18n (message.subject)
message.body = si18n (message.body )
Smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = Smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = Configuration.smtp.username._,
password = Configuration.smtp.password._,
server = Configuration.smtp.host._,
port = Configuration.smtp.port._,
create = Tcp [Configuration.smtp.method._] (Configuration.smtp.protocol._, make_socket.async),
}
end)
end
do
if not Email.discover () then
Logger.warning {
_ = i18n ["smtp:not-available"],
}
else
Logger.info {
_ = i18n ["smtp:available"],
host = Configuration.smtp.host._,
port = Configuration.smtp.port._,
method = Configuration.smtp.method._,
protocol = Configuration.smtp.protocol._,
}
end
end
return Email
|
local Configuration = require "cosy.configuration"
local CSocket = require "cosy.socket"
local I18n = require "cosy.i18n"
local Logger = require "cosy.logger"
local Scheduler = require "cosy.scheduler"
local Socket = require "socket"
local Smtp = require "socket.smtp"
local Ssl = require "ssl"
if not Ssl then
Ssl = _G.ssl
end
Configuration.load "cosy.email"
local i18n = I18n.load "cosy.email"
i18n._locale = Configuration.locale._
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local result = Socket.tcp ()
result:settimeout (Configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local result = CSocket ()
result:settimeout (Configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = Ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self.socket:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return nil, "connection failed"
end
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = Ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self.socket:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local domain = Configuration.server.root._
local host = Configuration.smtp.host._
local username = Configuration.smtp.username._
local password = Configuration.smtp.password._
local methods = { Configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { Configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { Configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
Logger.debug {
_ = i18n ["smtp:discover"],
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (Smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
Configuration.smtp.port = port
Configuration.smtp.method = method
Configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
Scheduler.addthread (function ()
local Value = require "cosy.value"
local locale = message.locale or Configuration.locale.default._
local si18n = I18n.new (locale)
message.from = si18n (message.from ).message
message.to = si18n (message.to ).message
message.subject = si18n (message.subject).message
message.body = si18n (message.body ).message
Smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = Smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = Configuration.smtp.username._,
password = Configuration.smtp.password._,
server = Configuration.smtp.host._,
port = Configuration.smtp.port._,
create = Tcp [Configuration.smtp.method._] (Configuration.smtp.protocol._, make_socket.async),
}
end)
end
do
if not Email.discover () then
Logger.warning {
_ = i18n ["smtp:not-available"],
}
else
Logger.info {
_ = i18n ["smtp:available"],
host = Configuration.smtp.host._,
port = Configuration.smtp.port._,
method = Configuration.smtp.method._,
protocol = Configuration.smtp.protocol._,
}
end
end
return Email
|
Fix email sending with i18n.
|
Fix email sending with i18n.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
cb33507a67d9b5e9b9f1caf0a87c29ee6842455b
|
OS/DiskOS/Libraries/map.lua
|
OS/DiskOS/Libraries/map.lua
|
local path = select(1,...)
return function(w,h,sheet)
local Map = {}
Map.w, Map.h = w or 24, h or 9
--Initialize the map table
Map.m = {}
for x=1, Map.w do
Map.m[x] = {}
for y=1, Map.h do
Map.m[x][y] = 0
end
end
Map.sheet = sheet
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
--func(x,y,self.m[x][y])
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = require(path)(w,h)
local m = nMap:map()
for my=1,h do
for mx=1,w do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
if sprid < 1 then return end
(self.sheet or sheet):draw(sprid,dx + spx*8*sx - 8*sx, dy + spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
function Map:export()
local data = "LK12;TILEMAP;"..self.w.."x"..self.h..";"
self:map(function(x,y,sprid)
data = data..sprid..";"
end)
return data
end
function Map:import(data)
if not data:sub(0,13) == "LK12;TILEMAP;" then error("Wrong header") end
local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)")
local nextid = mdata:gmatch("(.-);")
self:map(function(x,y,sprid)
return 0
end)
for x=1,w do
for y=1,h do
self:cell(x,y,tonumber(nextid()))
end
end
return self
end
return Map
end
|
local path = select(1,...)
return function(w,h,sheet)
local Map = {}
Map.w, Map.h = w or 24, h or 9
--Initialize the map table
Map.m = {}
for x=1, Map.w do
Map.m[x] = {}
for y=1, Map.h do
Map.m[x][y] = 0
end
end
Map.sheet = sheet
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
--func(x,y,self.m[x][y])
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if x > self.w or y > self.h then return false, "out of range" end
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = require(path)(w,h)
local m = nMap:map()
for my=1,h do
for mx=1,w do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
if sprid < 1 then return end
(self.sheet or sheet):draw(sprid,dx + spx*8*sx - 8*sx, dy + spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
function Map:export()
local data = "LK12;TILEMAP;"..self.w.."x"..self.h..";"
self:map(function(x,y,sprid)
data = data..sprid..";"
end)
return data
end
function Map:import(data)
if not data:sub(0,13) == "LK12;TILEMAP;" then error("Wrong header") end
local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)")
local nextid = mdata:gmatch("(.-);")
self:map(function(x,y,sprid)
return 0
end)
for x=1,w do
for y=1,h do
self:cell(x,y,tonumber(nextid()))
end
end
return self
end
return Map
end
|
Bugfix the error when loading a cart
|
Bugfix the error when loading a cart
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
2282d76e32a0f76e64e358c0c89a93c7c3eabd31
|
lua/entities/gmod_wire_addressbus.lua
|
lua/entities/gmod_wire_addressbus.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Address Bus"
ENT.WireDebugName = "AddressBus"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self.Outputs = Wire_CreateOutputs(self, {"Memory"})
self.Inputs = Wire_CreateInputs(self,{"Memory1","Memory2","Memory3","Memory4"})
self.DataRate = 0
self.DataBytes = 0
self.Memory = {}
self.MemStart = {}
self.MemEnd = {}
for i = 1,4 do
self.Memory[i] = nil
self.MemStart[i] = 0
self.MemEnd[i] = 0
end
self:SetOverlayText("Data rate: 0 bps")
end
function ENT:Setup(Mem1st, Mem2st, Mem3st, Mem4st, Mem1sz, Mem2sz, Mem3sz, Mem4sz)
local starts = {Mem1st,Mem2st,Mem3st,Mem4st}
local sizes = {Mem1sz,Mem2sz,Mem3sz,Mem4sz}
for i = 1,4 do
self.MemStart[i] = starts[i]
self.MemEnd[i] = starts[i] + sizes[i] - 1
self["Mem"..i.."st"] = starts[i]
self["Mem"..i.."sz"] = sizes[i]
end
end
function ENT:Think()
self.BaseClass.Think(self)
self.DataRate = self.DataBytes
self.DataBytes = 0
Wire_TriggerOutput(self, "Memory", self.DataRate)
self:SetOverlayText("Data rate: "..math.floor(self.DataRate*2).." bps")
self:NextThink(CurTime()+0.5)
return true
end
function ENT:ReadCell(Address)
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].ReadCell then
self.DataBytes = self.DataBytes + 1
local val = self.Memory[i]:ReadCell(Address - self.MemStart[i])
return val or 0
end
else
return 0
end
end
end
return nil
end
function ENT:WriteCell(Address, value)
local res = false
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].WriteCell then
self.Memory[i]:WriteCell(Address - self.MemStart[i], value)
end
end
self.DataBytes = self.DataBytes + 1
res = true
end
end
return res
end
function ENT:TriggerInput(iname, value)
for i = 1,4 do
if iname == "Memory"..i then
self.Memory[i] = self.Inputs["Memory"..i].Src
end
end
end
duplicator.RegisterEntityClass("gmod_wire_addressbus", WireLib.MakeWireEnt, "Data", "Mem1st", "Mem2st", "Mem3st", "Mem4st", "Mem1sz", "Mem2sz", "Mem3sz", "Mem4sz")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Address Bus"
ENT.WireDebugName = "AddressBus"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self.Outputs = Wire_CreateOutputs(self, {"Memory"})
self.Inputs = Wire_CreateInputs(self,{"Memory1","Memory2","Memory3","Memory4"})
self.DataRate = 0
self.DataBytes = 0
self.Memory = {}
self.MemStart = {}
self.MemEnd = {}
for i = 1,4 do
self.Memory[i] = nil
self.MemStart[i] = 0
self.MemEnd[i] = 0
end
self:SetOverlayText("Data rate: 0 bps")
end
function ENT:Setup(Mem1st, Mem2st, Mem3st, Mem4st, Mem1sz, Mem2sz, Mem3sz, Mem4sz)
local starts = {Mem1st,Mem2st,Mem3st,Mem4st}
local sizes = {Mem1sz,Mem2sz,Mem3sz,Mem4sz}
for i = 1,4 do
starts[i] = tonumber(starts[i]) or 0
sizes[i] = tonumber(sizes[i]) or 0
self.MemStart[i] = starts[i]
self.MemEnd[i] = starts[i] + sizes[i] - 1
self["Mem"..i.."st"] = starts[i]
self["Mem"..i.."sz"] = sizes[i]
end
end
function ENT:Think()
self.BaseClass.Think(self)
self.DataRate = self.DataBytes
self.DataBytes = 0
Wire_TriggerOutput(self, "Memory", self.DataRate)
self:SetOverlayText("Data rate: "..math.floor(self.DataRate*2).." bps")
self:NextThink(CurTime()+0.5)
return true
end
function ENT:ReadCell(Address)
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].ReadCell then
self.DataBytes = self.DataBytes + 1
local val = self.Memory[i]:ReadCell(Address - self.MemStart[i])
return val or 0
end
else
return 0
end
end
end
return nil
end
function ENT:WriteCell(Address, value)
local res = false
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].WriteCell then
self.Memory[i]:WriteCell(Address - self.MemStart[i], value)
end
end
self.DataBytes = self.DataBytes + 1
res = true
end
end
return res
end
function ENT:TriggerInput(iname, value)
for i = 1,4 do
if iname == "Memory"..i then
self.Memory[i] = self.Inputs["Memory"..i].Src
end
end
end
duplicator.RegisterEntityClass("gmod_wire_addressbus", WireLib.MakeWireEnt, "Data", "Mem1st", "Mem2st", "Mem3st", "Mem4st", "Mem1sz", "Mem2sz", "Mem3sz", "Mem4sz")
|
Fixed address buses not being duped
|
Fixed address buses not being duped
|
Lua
|
apache-2.0
|
sammyt291/wire,plinkopenguin/wiremod,rafradek/wire,mitterdoo/wire,NezzKryptic/Wire,garrysmodlua/wire,mms92/wire,dvdvideo1234/wire,bigdogmat/wire,Grocel/wire,wiremod/wire,notcake/wire,thegrb93/wire,Python1320/wire,CaptainPRICE/wire
|
03d1b1168c7d55251fb631286394ade8c46104ae
|
packages/unichar/init.lua
|
packages/unichar/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "unichar"
function package:registerCommands ()
self:registerCommand("unichar", function(_, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
local hlist = SILE.typesetter.state.nodes
local char = SU.utf8charfromcodepoint(cp)
if #hlist > 1 and hlist[#hlist].is_unshaped
and pl.tablex.deepcompare(hlist[#hlist].options, SILE.font.loadDefaults({})) then
-- Stack character with a preceeding unshaped node if its font is the
-- same as the current one, so that combining characters (e.g. diacritics)
-- and kerning works with \unichar'ed code points too.
hlist[#hlist].text = hlist[#hlist].text .. char
else
SILE.typesetter:typeset(char)
end
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.)
Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints.
After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available:
\begin{verbatim}
\line
% Note we are directly outputing the unicode to workaround https://github.com/sile-typesetter/sile/issues/991
\\unichar\{U+263A\} \% produces \font[family=Symbola]{☺}
\line
\end{verbatim}
If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value.
Otherwise it is assumed to be a decimal codepoint.
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "unichar"
function package:registerCommands ()
self:registerCommand("unichar", function(_, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
local hlist = SILE.typesetter.state.nodes
local char = SU.utf8charfromcodepoint(cp)
if #hlist > 1 and hlist[#hlist].is_unshaped
and pl.tablex.deepcompare(hlist[#hlist].options, SILE.font.loadDefaults({})) then
-- Stack character with a preceeding unshaped node if its font is the
-- same as the current one, so that combining characters (e.g. diacritics)
-- and kerning works with \unichar'ed code points too.
hlist[#hlist].text = hlist[#hlist].text .. char
else
SILE.typesetter:typeset(char)
end
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.)
Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints.
After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available:
\begin{verbatim}
\line
\\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}}
\line
\end{verbatim}
If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value.
Otherwise it is assumed to be a decimal codepoint.
\end{document}
]]
return package
|
Revert "docs(packages): Fixup unichar documentation, work around known bug (#1549)"
|
Revert "docs(packages): Fixup unichar documentation, work around known bug (#1549)"
This reverts commit 02ddce7ab28ac5d7c91b05a5695c611e0c4e1c03.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
fccd715e0b7448135827e1ef270eb662afd4ae97
|
mod_register_url/mod_register_url.lua
|
mod_register_url/mod_register_url.lua
|
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page to complete the registration.
local st = require "util.stanza";
function reg_redirect(event)
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" };
local url = module:get_option("registration_url");
local no_wl = module:get_option("no_registration_whitelist") or false;
if type(no_wl) ~= boolean then no_wl = false end
local test_ip = false;
if not no_wl then
for i,ip in ipairs(ip_wl) do
if event.origin.ip == ip then test_ip = true; end
break;
end
end
if not test_ip and url ~= nil or no_wl and url ~= nil then
local reply = st.reply(event.stanza);
reply:tag("query", {xmlns = "jabber:iq:register"})
:tag("instructions"):text("Please visit "..url.." to register an account on this server."):up()
:tag("x", {xmlns = "jabber:x:oob"}):up()
:tag("url"):text(url):up();
event.origin.send(reply);
return true;
end
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
|
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page to complete the registration.
local st = require "util.stanza";
function reg_redirect(event)
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" };
local url = module:get_option("registration_url");
local no_wl = module:get_option_boolean("no_registration_whitelist", false);
local test_ip = false;
if not no_wl then
for i,ip in ipairs(ip_wl) do
if event.origin.ip == ip then test_ip = true; end
break;
end
end
if not test_ip and url ~= nil or no_wl and url ~= nil then
local reply = st.reply(event.stanza);
reply:tag("query", {xmlns = "jabber:iq:register"})
:tag("instructions"):text("Please visit "..url.." to register an account on this server."):up()
:tag("x", {xmlns = "jabber:x:oob"}):up()
:tag("url"):text(url):up();
event.origin.send(reply);
return true;
end
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
|
mod_register_url: minor fix.
|
mod_register_url: minor fix.
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
bfbe7535fea0f817419593fd07c60d3a96bacd2e
|
nvim/.config/nvim/lua/plugin_conf.lua
|
nvim/.config/nvim/lua/plugin_conf.lua
|
--setup needed functions
local setkm = vim.api.nvim_set_keymap
--Treesitter
require('orgmode').setup_ts_grammar()
-- Tree-sitter configuration
require 'nvim-treesitter.configs'.setup {
highlight = {
enable = true,
additional_vim_regex_highlighting = { 'org' },
},
ensure_installed = { 'org' },
}
--Telescope
require("telescope").setup {
defaults = {
file_ignore_patterns = { "venv/.*" }
}
}
--Orgmode
require('orgmode').setup {}
--Nvim-autopairs
require("nvim-autopairs").setup {}
--Comment
require('Comment').setup()
--Ultisnips
vim.g.UltiSnipsExpandTrigger = "<tab>"
vim.g.UltiSnipsJumpForwardTrigger = "<tab>"
vim.g.UltiSnipsJumpBackwardTrigger = "<S-tab>"
--Whitespace
vim.cmd [[ highlight ExtraWhitespace ctermbg=78 ]]
setkm('n', '<leader>w', ':StripWhitespace<CR>', { noremap = true, desc = 'Strip whitespace' })
--Undotree
setkm('n', '<leader>u', ':UndotreeToggle<CR>', { noremap = true, desc = 'Undotree Toggle' })
--Slime
vim.g.slime_target = "tmux"
vim.g.slime_default_config = '{"socket_name": "default", "target_pane": "1"}'
vim.g.slime_dont_ask_default = 1
vim.g.slime_python_ipython = 0
--Rainbow brackets
vim.g.rainbow_active = 1
--Easy align
setkm('n', 'ga', '<Plug>(EasyAlign)', { noremap = true, desc = 'EasyAlign activate' })
setkm('v', 'ga', '<Plug>(EasyAlign)', { noremap = true, desc = 'EasyAlign activate' })
--IndentBlankLine
setkm('n', '<leader>i', ':IndentBlanklineToggle<CR>', { noremap = true, desc = 'IndentBlankLine Toggle' })
--Airline
vim.g['airline_symbols.colnr'] = ':'
vim.g['airline_symbols.crypt'] = '🔒'
vim.g['airline_symbols.linenr'] = ' | '
vim.g['airline_symbols.maxlinenr'] = ''
vim.g['airline_symbols.branch'] = '⎇'
vim.g['airline_symbols.paste'] = 'PASTE'
vim.g['airline_symbols.spell'] = 'SPELL'
vim.g['airline_symbols.notexists'] = 'Ɇ'
vim.g['airline_symbols.whitespace'] = 'wh'
vim.g['airline#extensions#wordcount#formatter#default#fmt'] = '%s |'
vim.g['airline#extensions#tabline#enabled'] = 1
vim.g['airline#extensions#tabline#show_tab_nr'] = 1
vim.g['airline_powerline_fonts'] = 1
vim.g['airline#extensions#tabline#ignore_bufadd_pat'] = '!|defx|gundo|nerd_tree|startify|tagbar|undotree|vimfiler'
--Telescope
setkm('n', '<leader>f%', ':Telescope oldfiles<CR>', { noremap = true, desc = 'Telescope find recently open files' })
setkm('n', '<leader>f/', ':Telescope search_history<CR>', { noremap = true, desc = 'Telescope find in search history' })
setkm('n', '<leader>fG', ':Telescope git_status<CR>', { noremap = true, desc = 'Telescope find modified git files' })
setkm('n', '<leader>fa', ':Telescope live_grep<CR>', { noremap = true, desc = 'Telescope find pattern in all files' })
setkm('n', '<leader>fb', ':Telescope buffers<CR>', { noremap = true, desc = 'Telescope find buffer' })
setkm('n', '<leader>f:', ':Telescope commands<CR>', { noremap = true, desc = 'Telescope find nvim command' })
setkm('n', '<leader>fd', ':Telescope diagnostics<CR>', { noremap = true, desc = 'Telescope find diagnostic' })
setkm('n', '<leader>ff', ':Telescope find_files<CR>', { noremap = true, desc = 'Telescope find file' })
setkm('n', '<leader>fg', ':Telescope git_files<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fh', ':Telescope help_tags<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fi', ':Telescope current_buffer_fuzzy_find<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fj', ':Telescope jumplist<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fk', ':Telescope keymaps<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fl', ':Telescope loclist<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f\'', ':Telescope marks<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fo', ':Telescope vim_options<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fq', ':Telescope quickfix<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f"', ':Telescope registers<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fw', ':Telescope grep_string<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>ft', ':Telescope tags<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fu', ':Telescope lsp_references<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f<', ':Telescope lsp_incoming_calls<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f>', ':Telescope lsp_outgoing_calls<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f$', ':Telescope lsp_document_symbols<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f^', ':Telescope lsp_workspace_symbols<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fD', ':Telescope lsp_definitions<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fI', ':Telescope lsp_implementations<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>ft', ':Telescope lsp_type_definitions<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fv', ':Telescope treesitter<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fc', ':Telescope git_commits<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fT', ':Telescope git_branches<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fs', ':Telescope git_status<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fS', ':Telescope git_stash<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fB', ':Telescope git_bcommits<CR>', { noremap = true, desc = 'Telescope find' })
--Web dev icons
require 'nvim-web-devicons'.setup {
default = true;
}
-- empty setup using defaults
require("nvim-tree").setup()
setkm('n', '<leader>n', ':NvimTreeToggle<CR>', { noremap = true, desc = 'Toggle NvimTree file explorer'})
|
--setup needed functions
local setkm = vim.api.nvim_set_keymap
--Treesitter
require('orgmode').setup_ts_grammar()
require 'nvim-treesitter.configs'.setup {
highlight = {
enable = true,
additional_vim_regex_highlighting = { 'org' },
},
ensure_installed = { 'org' },
}
--Telescope
require("telescope").setup {
defaults = {
file_ignore_patterns = { "venv/.*" }
}
}
--Orgmode
require('orgmode').setup {}
--Nvim-autopairs
require("nvim-autopairs").setup {}
--Comment
require('Comment').setup()
--Ultisnips
vim.g.UltiSnipsExpandTrigger = "<tab>"
vim.g.UltiSnipsJumpForwardTrigger = "<tab>"
vim.g.UltiSnipsJumpBackwardTrigger = "<S-tab>"
--Whitespace
vim.cmd [[ highlight ExtraWhitespace ctermbg=78 ]]
setkm('n', '<leader>w', ':StripWhitespace<CR>', { noremap = true, desc = 'Strip whitespace' })
--Undotree
setkm('n', '<leader>u', ':UndotreeToggle<CR>', { noremap = true, desc = 'Undotree Toggle' })
--Slime
vim.g.slime_target = "tmux"
vim.g.slime_default_config = '{"socket_name": "default", "target_pane": "1"}'
vim.g.slime_dont_ask_default = 1
vim.g.slime_python_ipython = 0
--Rainbow brackets
vim.g.rainbow_active = 1
--Easy align
setkm('n', 'ga', '<Plug>(EasyAlign)', { noremap = true, desc = 'EasyAlign activate' })
setkm('v', 'ga', '<Plug>(EasyAlign)', { noremap = true, desc = 'EasyAlign activate' })
--IndentBlankLine
setkm('n', '<leader>i', ':IndentBlanklineToggle<CR>', { noremap = true, desc = 'IndentBlankLine Toggle' })
--Airline
vim.g['airline_symbols.colnr'] = ':'
vim.g['airline_symbols.crypt'] = '🔒'
vim.g['airline_symbols.linenr'] = ' | '
vim.g['airline_symbols.maxlinenr'] = ''
vim.g['airline_symbols.branch'] = '⎇'
vim.g['airline_symbols.paste'] = 'PASTE'
vim.g['airline_symbols.spell'] = 'SPELL'
vim.g['airline_symbols.notexists'] = 'Ɇ'
vim.g['airline_symbols.whitespace'] = 'wh'
vim.g['airline#extensions#wordcount#formatter#default#fmt'] = '%s |'
vim.g['airline#extensions#tabline#enabled'] = 1
vim.g['airline#extensions#tabline#show_tab_nr'] = 1
vim.g['airline_powerline_fonts'] = 1
vim.g['airline#extensions#tabline#ignore_bufadd_pat'] = '!|defx|gundo|nerd_tree|startify|tagbar|undotree|vimfiler'
--Telescope
setkm('n', '<leader>f%', ':Telescope oldfiles<CR>', { noremap = true, desc = 'Telescope find recently open files' })
setkm('n', '<leader>f/', ':Telescope search_history<CR>', { noremap = true, desc = 'Telescope find in search history' })
setkm('n', '<leader>fG', ':Telescope git_status<CR>', { noremap = true, desc = 'Telescope find modified git files' })
setkm('n', '<leader>fa', ':Telescope live_grep<CR>', { noremap = true, desc = 'Telescope find pattern in all files' })
setkm('n', '<leader>fb', ':Telescope buffers<CR>', { noremap = true, desc = 'Telescope find buffer' })
setkm('n', '<leader>f:', ':Telescope commands<CR>', { noremap = true, desc = 'Telescope find nvim command' })
setkm('n', '<leader>fd', ':Telescope diagnostics<CR>', { noremap = true, desc = 'Telescope find diagnostic' })
setkm('n', '<leader>ff', ':Telescope find_files<CR>', { noremap = true, desc = 'Telescope find file' })
setkm('n', '<leader>fg', ':Telescope git_files<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fh', ':Telescope help_tags<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fi', ':Telescope current_buffer_fuzzy_find<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fj', ':Telescope jumplist<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fk', ':Telescope keymaps<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fl', ':Telescope loclist<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f\'', ':Telescope marks<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fo', ':Telescope vim_options<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fq', ':Telescope quickfix<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f"', ':Telescope registers<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fw', ':Telescope grep_string<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>ft', ':Telescope tags<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fu', ':Telescope lsp_references<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f<', ':Telescope lsp_incoming_calls<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f>', ':Telescope lsp_outgoing_calls<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f$', ':Telescope lsp_document_symbols<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>f^', ':Telescope lsp_workspace_symbols<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fD', ':Telescope lsp_definitions<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fI', ':Telescope lsp_implementations<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>ft', ':Telescope lsp_type_definitions<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fv', ':Telescope treesitter<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fc', ':Telescope git_commits<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fT', ':Telescope git_branches<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fs', ':Telescope git_status<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fS', ':Telescope git_stash<CR>', { noremap = true, desc = 'Telescope find' })
setkm('n', '<leader>fB', ':Telescope git_bcommits<CR>', { noremap = true, desc = 'Telescope find' })
--Web dev icons
require 'nvim-web-devicons'.setup {
default = true;
}
-- empty setup using defaults
require("nvim-tree").setup()
setkm('n', '<leader>n', ':NvimTreeToggle<CR>', { noremap = true, desc = 'Toggle NvimTree file explorer' })
|
[nvim] quickfix file formatting
|
[nvim] quickfix file formatting
|
Lua
|
mit
|
voltux/dotfiles,voltux/dotfiles,voltux/dotfiles
|
ccea8cb0f0ca67dc8b9207663a86eff6004d666d
|
LogSoftMax.lua
|
LogSoftMax.lua
|
function torch.ClTensor.nn.LogSoftMax_updateOutput(self, input)
if input:dim() == 1 then
if self.maxbuffer == nil then
self.maxbuffer, self.resind = input:max(1)
self.vec_size = input:size(1)
end
self.output:resize(input:size())
self.maxbuffer:max(self.resind, input, 1)
self.output:copy(input)
self.output:csub(self.maxbuffer:expand(input:size(1)))
self.output:exp()
self.maxbuffer:sum(self.output,1)
self.output:cdiv(self.maxbuffer:expand(input:size(1)))
self.output:log()
return self.output
elseif input:dim() == 2 then
if self.maxbuffer == nil then
self.maxbuffer, self.resind = input:max(2)
self.vec_size = input:size(2)
end
self.output:resize(input:size())
self.maxbuffer:max(self.resind, input, 2)
self.output:copy(input)
self.output:csub(self.maxbuffer:expand(input:size(1), input:size(2)))
self.output:exp()
self.maxbuffer:sum(self.output,2)
self.output:cdiv(self.maxbuffer:expand(input:size(1), input:size(2)))
self.output:log()
return self.output
else
error('LogSoftMax expects 1-d or 2-d tensor currently')
end
end
function torch.ClTensor.nn.LogSoftMax_updateGradInput(self, input, gradOutput)
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 1 then
self.maxbuffer:sum(gradOutput, 1)
self.gradInput:copy(self.output)
self.gradInput:exp()
self.gradInput:cmul(self.maxbuffer:expand(input:size(1)))
self.gradInput:neg()
self.gradInput:add(gradOutput)
elseif input:dim() == 2 then
self.maxbuffer:sum(gradOutput, 2)
self.gradInput:copy(self.output)
self.gradInput:exp()
self.gradInput:cmul(self.maxbuffer:expand(input:size(1), input:size(2)))
self.gradInput:neg()
self.gradInput:add(gradOutput)
else
error('LogSoftMax expects 1-d or 2-d tensor currently')
end
return self.gradInput
end
|
require 'nn'
nn.LogSoftMax.baseUpdateOutput = nn.LogSoftMax.updateOutput
nn.LogSoftMax.baseUpdateGradInput = nn.LogSoftMax.updateGradInput
function nn.LogSoftMax:updateOutput(input)
if torch.type(input) ~= 'torch.ClTensor' then
return self:baseUpdateOutput(input)
end
if input:dim() == 1 then
if self.maxbuffer == nil then
self.maxbuffer, self.resind = input:max(1)
self.vec_size = input:size(1)
end
self.output:resize(input:size())
self.maxbuffer:max(self.resind, input, 1)
self.output:copy(input)
self.output:csub(self.maxbuffer:expand(input:size(1)))
self.output:exp()
self.maxbuffer:sum(self.output,1)
self.output:cdiv(self.maxbuffer:expand(input:size(1)))
self.output:log()
return self.output
elseif input:dim() == 2 then
if self.maxbuffer == nil then
self.maxbuffer, self.resind = input:max(2)
self.vec_size = input:size(2)
end
self.output:resize(input:size())
self.maxbuffer:max(self.resind, input, 2)
self.output:copy(input)
self.output:csub(self.maxbuffer:expand(input:size(1), input:size(2)))
self.output:exp()
self.maxbuffer:sum(self.output,2)
self.output:cdiv(self.maxbuffer:expand(input:size(1), input:size(2)))
self.output:log()
return self.output
else
error('LogSoftMax expects 1-d or 2-d tensor currently')
end
end
function nn.LogSoftMax:updateGradInput(input, gradOutput)
if torch.type(input) ~= 'torch.ClTensor' then
return self:baseUpdateGradInput(input, gradOutput)
end
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 1 then
self.maxbuffer:sum(gradOutput, 1)
self.gradInput:copy(self.output)
self.gradInput:exp()
self.gradInput:cmul(self.maxbuffer:expand(input:size(1)))
self.gradInput:neg()
self.gradInput:add(gradOutput)
elseif input:dim() == 2 then
self.maxbuffer:sum(gradOutput, 2)
self.gradInput:copy(self.output)
self.gradInput:exp()
self.gradInput:cmul(self.maxbuffer:expand(input:size(1), input:size(2)))
self.gradInput:neg()
self.gradInput:add(gradOutput)
else
error('LogSoftMax expects 1-d or 2-d tensor currently')
end
return self.gradInput
end
|
fix logsoftmax following https://github.com/torch/nn/pull/549
|
fix logsoftmax following https://github.com/torch/nn/pull/549
|
Lua
|
bsd-2-clause
|
hughperkins/clnn,hughperkins/clnn,hughperkins/clnn,hughperkins/clnn
|
ad8389a758714af7e866e1db0ab830c8a9da31ee
|
WeightNorm.lua
|
WeightNorm.lua
|
-- Weight Normalization
-- https://arxiv.org/pdf/1602.07868v3.pdf
local WeightNorm, parent = torch.class("nn.WeightNorm", "nn.Container")
function WeightNorm:__init(module, outputDim)
-- this container will apply Weight Normalization to any module it wraps
-- it accepts parameter ``outputDim`` that represents the dimension of the output of the weight
-- if outputDim is not 1, the container will transpose the weight
-- if the weight is not 2D, the container will view the weight into a 2D shape
-- that is nOut x (nIn x kw x dw x ...)
parent.__init(self)
assert(module.weight)
if module.bias then
self.bias = module.bias
self.gradBias = module.gradBias
end
self.gradWeight = module.gradWeight
self.weight = module.weight
self.outputDim = outputDim or 1
-- track the non-output weight dimensions
self.otherDims = 1
for i = 1, self.weight:dim() do
if i ~= self.outputDim then
self.otherDims = self.otherDims * self.weight:size(i)
end
end
-- view size for weight norm 2D calculations
self.viewIn = torch.LongStorage({self.weight:size(self.outputDim), self.otherDims})
-- view size back to original weight
self.viewOut = self.weight:size()
-- bubble outputDim size up to the front
for i = self.outputDim - 1, 1, -1 do
self.viewOut[i], self.viewOut[i + 1] = self.viewOut[i + 1], self.viewOut[i]
end
-- weight is reparametrized to decouple the length from the direction
-- such that w = g * ( v / ||v|| )
self.v = torch.Tensor(self.viewIn[1], self.viewIn[2])
self.g = torch.Tensor(self.viewIn[1])
self._norm = torch.Tensor(self.viewIn[1])
self._scale = torch.Tensor(self.viewIn[1])
-- gradient of g
self.gradG = torch.Tensor(self.viewIn[1]):zero()
-- gradient of v
self.gradV = torch.Tensor(self.viewIn)
self.modules[1] = module
self:resetInit()
end
function WeightNorm:permuteIn(inpt)
local ans = inpt
for i = self.outputDim - 1, 1, -1 do
ans = ans:transpose(i, i+1)
end
return ans
end
function WeightNorm:permuteOut(inpt)
local ans = inpt
for i = 1, self.outputDim - 1 do
ans = ans:transpose(i, i+1)
end
return ans
end
function WeightNorm:resetInit(inputSize, outputSize)
self.v:normal(0, math.sqrt(2/self.viewIn[2]))
self.g:norm(self.v, 2, 2)
if self.bias then
self.bias:zero()
end
end
function WeightNorm:evaluate()
if not(self.train == false) then
self:updateWeight()
parent.evaluate(self)
end
end
function WeightNorm:updateWeight()
-- view to 2D when weight norm container operates
self.gradV:copy(self:permuteIn(self.weight))
self.gradV = self.gradV:view(self.viewIn)
-- ||w||
self._norm:norm(self.v, 2, 2):pow(2):add(10e-5):sqrt()
-- g * w / ||w||
self.gradV:copy(self.v)
self._scale:copy(self.g):cdiv(self._norm)
self.gradV:cmul(self._scale:view(self.viewIn[1], 1)
:expand(self.viewIn[1], self.viewIn[2]))
-- otherwise maintain size of original module weight
self.gradV = self.gradV:view(self.viewOut)
self.weight:copy(self:permuteOut(self.gradV))
end
function WeightNorm:updateOutput(input)
if not(self.train == false) then
self:updateWeight()
end
self.output:set(self.modules[1]:updateOutput(input))
return self.output
end
function WeightNorm:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self.modules[1]:accGradParameters(input, gradOutput, scale)
self.weight:copy(self:permuteIn(self.weight))
self.gradV:copy(self:permuteIn(self.gradWeight))
self.weight = self.weight:view(self.viewIn)
local norm = self._norm:view(self.viewIn[1], 1):expand(self.viewIn[1], self.viewIn[2])
local scale = self._scale:view(self.viewIn[1], 1):expand(self.viewIn[1], self.viewIn[2])
-- dL / dw * (w / ||w||)
self.weight:copy(self.gradV)
self.weight:cmul(self.v):cdiv(norm)
self.gradG:sum(self.weight, 2)
-- dL / dw * g / ||w||
self.gradV:cmul(scale)
-- dL / dg * (w * g / ||w||^2)
self.weight:copy(self.v):cmul(scale):cdiv(norm)
self.weight:cmul(self.gradG:view(self.viewIn[1], 1)
:expand(self.viewIn[1], self.viewIn[2]))
-- dL / dv update
self.gradV:add(-1, self.weight)
self.gradV = self.gradV:view(self.viewOut)
self.weight = self.weight:view(self.viewOut)
self.gradWeight:copy(self:permuteOut(self.gradV))
end
function WeightNorm:updateGradInput(input, gradOutput)
self.gradInput:set(self.modules[1]:updateGradInput(input, gradOutput))
return self.gradInput
end
function WeightNorm:zeroGradParameters()
self.modules[1]:zeroGradParameters()
self.gradV:zero()
self.gradG:zero()
end
function WeightNorm:updateParameters(lr)
self.modules[1]:updateParameters(lr)
self.g:add(-lr, self.gradG)
self.v:add(-lr, self.gradV)
end
function WeightNorm:parameters()
if self.bias then
return {self.v, self.g, self.bias}, {self.gradV, self.gradG, self.gradBias}
else
return {self.v, self.g}, {self.gradV, self.gradG}
end
end
function WeightNorm:__tostring__()
local str = 'nn.WeightNorm [' .. tostring(self.modules[1]) .. ']'
return str
end
function WeightNorm:write(file)
-- Don't save weight and gradWeight since we can easily re-compute it from v
-- and g.
local weight = self.modules[1].weight
local gradWeight = self.modules[1].gradWeight
self.weight = nil
self.gradWeight = nil
self.modules[1].weight = nil
self.modules[1].gradWeight = nil
parent.write(self, file)
self.modules[1].weight = weight
self.modules[1].gradWeight = gradWeight
self.weight = weight
self.gradWeight = gradWeight
end
function WeightNorm:read(file)
parent.read(self, file)
-- Re-compute weight and gradWeight
self.modules[1].weight = self.v.new(self.viewOut)
self.modules[1].gradWeight = self.v.new(self.viewOut)
self.weight = self.modules[1].weight
self.gradWeight = self.modules[1].gradWeight
self:updateWeight()
self.gradWeight:copy(self:permuteOut(self.gradV))
end
|
-- Weight Normalization
-- https://arxiv.org/pdf/1602.07868v3.pdf
local WeightNorm, parent = torch.class("nn.WeightNorm", "nn.Container")
function WeightNorm:__init(module, outputDim)
-- this container will apply Weight Normalization to any module it wraps
-- it accepts parameter ``outputDim`` that represents the dimension of the output of the weight
-- if outputDim is not 1, the container will transpose the weight
-- if the weight is not 2D, the container will view the weight into a 2D shape
-- that is nOut x (nIn x kw x dw x ...)
parent.__init(self)
assert(module.weight)
if module.bias then
self.bias = module.bias
self.gradBias = module.gradBias
end
self.gradWeight = module.gradWeight
self.weight = module.weight
self.outputDim = outputDim or 1
-- track the non-output weight dimensions
self.otherDims = 1
for i = 1, self.weight:dim() do
if i ~= self.outputDim then
self.otherDims = self.otherDims * self.weight:size(i)
end
end
-- view size for weight norm 2D calculations
self.viewIn = torch.LongStorage({self.weight:size(self.outputDim), self.otherDims})
-- view size back to original weight
self.viewOut = self.weight:size()
self.weightSize = self.weight:size()
-- bubble outputDim size up to the front
for i = self.outputDim - 1, 1, -1 do
self.viewOut[i], self.viewOut[i + 1] = self.viewOut[i + 1], self.viewOut[i]
end
-- weight is reparametrized to decouple the length from the direction
-- such that w = g * ( v / ||v|| )
self.v = torch.Tensor(self.viewIn[1], self.viewIn[2])
self.g = torch.Tensor(self.viewIn[1])
self._norm = torch.Tensor(self.viewIn[1])
self._scale = torch.Tensor(self.viewIn[1])
-- gradient of g
self.gradG = torch.Tensor(self.viewIn[1]):zero()
-- gradient of v
self.gradV = torch.Tensor(self.viewIn)
self.modules[1] = module
self:resetInit()
end
function WeightNorm:permuteIn(inpt)
local ans = inpt
for i = self.outputDim - 1, 1, -1 do
ans = ans:transpose(i, i+1)
end
return ans
end
function WeightNorm:permuteOut(inpt)
local ans = inpt
for i = 1, self.outputDim - 1 do
ans = ans:transpose(i, i+1)
end
return ans
end
function WeightNorm:resetInit(inputSize, outputSize)
self.v:normal(0, math.sqrt(2/self.viewIn[2]))
self.g:norm(self.v, 2, 2)
if self.bias then
self.bias:zero()
end
end
function WeightNorm:evaluate()
if not(self.train == false) then
self:updateWeight()
parent.evaluate(self)
end
end
function WeightNorm:updateWeight()
-- view to 2D when weight norm container operates
self.gradV:copy(self:permuteIn(self.weight))
self.gradV = self.gradV:view(self.viewIn)
-- ||w||
self._norm:norm(self.v, 2, 2):pow(2):add(10e-5):sqrt()
-- g * w / ||w||
self.gradV:copy(self.v)
self._scale:copy(self.g):cdiv(self._norm)
self.gradV:cmul(self._scale:view(self.viewIn[1], 1)
:expand(self.viewIn[1], self.viewIn[2]))
-- otherwise maintain size of original module weight
self.gradV = self.gradV:view(self.viewOut)
self.weight:copy(self:permuteOut(self.gradV))
end
function WeightNorm:updateOutput(input)
if not(self.train == false) then
self:updateWeight()
end
self.output:set(self.modules[1]:updateOutput(input))
return self.output
end
function WeightNorm:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self.modules[1]:accGradParameters(input, gradOutput, scale)
self.weight:copy(self:permuteIn(self.weight))
self.gradV:copy(self:permuteIn(self.gradWeight))
self.weight = self.weight:view(self.viewIn)
local norm = self._norm:view(self.viewIn[1], 1):expand(self.viewIn[1], self.viewIn[2])
local scale = self._scale:view(self.viewIn[1], 1):expand(self.viewIn[1], self.viewIn[2])
-- dL / dw * (w / ||w||)
self.weight:copy(self.gradV)
self.weight:cmul(self.v):cdiv(norm)
self.gradG:sum(self.weight, 2)
-- dL / dw * g / ||w||
self.gradV:cmul(scale)
-- dL / dg * (w * g / ||w||^2)
self.weight:copy(self.v):cmul(scale):cdiv(norm)
self.weight:cmul(self.gradG:view(self.viewIn[1], 1)
:expand(self.viewIn[1], self.viewIn[2]))
-- dL / dv update
self.gradV:add(-1, self.weight)
self.gradV = self.gradV:view(self.viewOut)
self.weight = self.weight:view(self.viewOut)
self.gradWeight:copy(self:permuteOut(self.gradV))
end
function WeightNorm:updateGradInput(input, gradOutput)
self.gradInput:set(self.modules[1]:updateGradInput(input, gradOutput))
return self.gradInput
end
function WeightNorm:zeroGradParameters()
self.modules[1]:zeroGradParameters()
self.gradV:zero()
self.gradG:zero()
end
function WeightNorm:updateParameters(lr)
self.modules[1]:updateParameters(lr)
self.g:add(-lr, self.gradG)
self.v:add(-lr, self.gradV)
end
function WeightNorm:parameters()
if self.bias then
return {self.v, self.g, self.bias}, {self.gradV, self.gradG, self.gradBias}
else
return {self.v, self.g}, {self.gradV, self.gradG}
end
end
function WeightNorm:__tostring__()
local str = 'nn.WeightNorm [' .. tostring(self.modules[1]) .. ']'
return str
end
function WeightNorm:write(file)
-- Don't save weight and gradWeight since we can easily re-compute it from v
-- and g.
local weight = self.modules[1].weight
local gradWeight = self.modules[1].gradWeight
self.weight = nil
self.gradWeight = nil
self.modules[1].weight = nil
self.modules[1].gradWeight = nil
if not self.weightSize then
self.weightSize = weight:size()
end
parent.write(self, file)
self.modules[1].weight = weight
self.modules[1].gradWeight = gradWeight
self.weight = weight
self.gradWeight = gradWeight
end
function WeightNorm:read(file)
parent.read(self, file)
-- Re-compute weight and gradWeight
if not self.weight then
self.modules[1].weight = self.v.new(self.weightSize)
self.modules[1].gradWeight = self.v.new(self.weightSize)
self.weight = self.modules[1].weight
self.gradWeight = self.modules[1].gradWeight
self:updateWeight()
self.gradWeight:copy(self:permuteOut(self.gradV))
end
end
|
Fix WeightNorm serialization for permutated weight matrices
|
Fix WeightNorm serialization for permutated weight matrices
For layers where the first weight dimension does not correspond to the output
dimension, self.viewOut will *not* correspond to self.weight:size(). This is
fixed by introducing another member variable that simply holds the original size
of the weight matrix.
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn
|
ce8531220f97bd171f58f6523d8ccb56be9bfda1
|
lua/wire/flir.lua
|
lua/wire/flir.lua
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
* players are drawn fullbright but NPCs aren't.
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.RenderStack = {}
FLIR.ShouldRender = false
FLIR.bright = CreateMaterial("flir_bright", "UnlitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1
})
FLIR.mapcol = {
[ "$pp_colour_brightness" ] = 0.4,
[ "$pp_colour_contrast" ] = 0.4
}
FLIR.skycol = {
[ "$pp_colour_contrast" ] = 0.2,
[ "$pp_colour_brightness" ] = 1
}
FLIR.desat = {
["$pp_colour_colour"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_brightness"] = 0
}
local function SetFLIRMat(ent)
if not IsValid(ent) then return end
if (ent:GetMoveType() == MOVETYPE_VPHYSICS or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() or ent:GetClass() == "gmod_wire_hologram") and ent:GetColor().a > 0 then
ent.RenderOverride = FLIR.Render
FLIR.RenderStack[ent] = true
end
end
local function RemoveFLIRMat(ent)
ent.RenderOverride = nil
FLIR.RenderStack[ent] = nil
end
function FLIR.Render(self)
if FLIR.ShouldRender then self:DrawModel() end
end
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
bright = false
hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright
render.SetLightingMode(1)
FLIR.ShouldRender = false
end)
hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white or black
DrawColorModify(FLIR.skycol)
end)
hook.Add("PreDrawTranslucentRenderables", "wire_flir", function(a, b, sky)
if not sky then
DrawColorModify(FLIR.mapcol)
end
end)
hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky)
if sky then return end
render.SetLightingMode(0)
FLIR.ShouldRender = true
render.MaterialOverride(FLIR.bright)
--draw all the FLIR highlighted enemies after the opaque render to separate then from the rest of the map
for v in pairs(FLIR.RenderStack) do
if v:IsValid() then v:DrawModel() else FLIR.RenderStack[v] = nil end
end
FLIR.ShouldRender = false
render.MaterialOverride(nil)
render.SetLightingMode(1)
end)
hook.Add("RenderScreenspaceEffects", "wire_flir", function()
render.SetLightingMode(0)
DrawColorModify(FLIR.desat)
DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1)
DrawBokehDOF(1, 0.1, 0.1)
end)
hook.Add("OnEntityCreated", "wire_flir", function(ent)
if FLIR.enabled then
SetFLIRMat(ent)
end
end)
hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag)
if FLIR.enabled then
SetFLIRMat(rag)
end
end)
for k, v in pairs(ents.GetAll()) do
SetFLIRMat(v)
end
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
render.SetLightingMode(0)
hook.Remove("PreDrawTranslucentRenderables", "wire_flir")
hook.Remove("PostDrawTranslucentRenderables", "wire_flir")
hook.Remove("RenderScreenspaceEffects", "wire_flir")
hook.Remove("PostDraw2DSkyBox", "wire_flir")
hook.Remove("PreRender", "wire_flir")
hook.Remove("OnEntityCreated", "wire_flir")
hook.Remove("CreateClientsideRagdoll", "wire_flir")
render.MaterialOverride(nil)
for k, v in pairs(ents.GetAll()) do
RemoveFLIRMat(v)
end
end
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
usermessage.Hook("flir.enable",function(um)
FLIR.enable(um:ReadBool())
end)
concommand.Add("flir_enable", function(player, command, args)
FLIR.enable(tobool(args[1]))
end)
else
function FLIR.start(player) FLIR.enable(player, true) end
function FLIR.stop(player) FLIR.enable(player, false) end
function FLIR.enable(player, enabled)
umsg.Start( "flir.enable", player)
umsg.Bool( enabled )
umsg.End()
end
end
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
To Fix:
* Find a way to make fog work. With rendermode 1 or 2, fog is disabled. mat_fullbright would be
perfect except that it causes a big stutter on being disabled.
* Add entities to the list as they are parented. If something is parented while FLIR is enabled, it doesn't
add itself until it's switched off and back on.
* Sun pops in and out of full brightness when looking around it
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.RenderStack = {}
FLIR.enabled = false
FLIR.gcvar = CreateClientConVar("wire_flir_gain", 2.2, true, false, "Brightness of FLIR ents. Higher = less detail, more visible.", 0, 10)
cvars.AddChangeCallback("wire_flir_gain", function(_,_,v)
FLIR.gain = v
end)
FLIR.gain = FLIR.gcvar:GetInt()
FLIR.mat = Material("phoenix_storms/concrete0")
FLIR.transmat = Material("phoenix_storms/iron_rails")
FLIR.hide = false
function FLIR.Render(self)
if not FLIR.hide then self:DrawModel() return end
end
FLIR.mapcol = {
[ "$pp_colour_brightness" ] = 0.5,
[ "$pp_colour_contrast" ] = 0.4
}
FLIR.skycol = {
[ "$pp_colour_contrast" ] = 0.2,
[ "$pp_colour_brightness" ] = 1
}
FLIR.desat = {
["$pp_colour_colour"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_brightness"] = 0
}
--add and remove entities from the FLIR rendering stack
local function RemoveFLIR(ent)
FLIR.RenderStack[ent] = nil
if ent:IsValid() then ent.RenderOverride = nil end
end
local function SetFLIR(ent)
if not ent:IsValid() then return end
local c = ent:GetClass()
if (c == "prop_physics" or ent:GetMoveType() == MOVETYPE_VPHYSICS or (ent:IsPlayer() and ent != ply) or ent:IsNPC() or ent:IsRagdoll() or c == "gmod_wire_hologram") and ent:GetColor().a > 0 then
if ent:GetColor().a > 0 then
FLIR.RenderStack[ent] = true
ent.RenderOverride = FLIR.Render --we're already rendering later, so don't bother beforehand
end
end
end
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
for _, v in pairs(ents.GetAll()) do
SetFLIR(v)
end
hook.Add("PreRender", "wire_flir", function()
render.SetLightingMode(2)
FLIR.hide = true
end)
hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white or black
DrawColorModify(FLIR.skycol)
end)
hook.Add("PostDrawOpaqueRenderables", "wire_flir", function(_, sky)
if sky then return end
DrawColorModify(FLIR.mapcol)
render.MaterialOverride(FLIR.mat)
render.SuppressEngineLighting(true)
render.SetColorModulation(FLIR.gain, FLIR.gain, FLIR.gain) --this works?? I could not for the life of me make it work in renderoverride. Well.
--It's a much better solution than the stencil I spent hours on...
for ent, valid in pairs(FLIR.RenderStack) do
if valid and ent:IsValid() and not ent:GetNoDraw() then
FLIR.hide = false
ent:DrawModel()
FLIR.hide = true
else
RemoveFLIR(ent)
end
end
render.SuppressEngineLighting(false)
render.MaterialOverride(FLIR.transmat)
end)
hook.Add("PostDrawTranslucentRenderables", "wire_flir", function()
render.SuppressEngineLighting(false)
render.MaterialOverride(nil)
end)
hook.Add("RenderScreenspaceEffects", "wire_flir", function()
--post-processing
DrawColorModify(FLIR.desat)
DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1)
DrawBokehDOF(1, 0.1, 0.1)
render.SetLightingMode(0)
--reset lighting so the menus are intelligble (try 1)
end)
hook.Add("OnEntityCreated", "wire_flir", function(ent)
if FLIR.enabled then
SetFLIR(ent)
end
end)
hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag)
if FLIR.enabled then
SetFLIR(rag)
end
end)
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
render.SetLightingMode(0)
hook.Remove("PostDrawOpaqueRenderables", "wire_flir")
hook.Remove("PostDrawTranslucentRenderables", "wire_flir")
hook.Remove("RenderScreenspaceEffects", "wire_flir")
hook.Remove("PostDraw2DSkyBox", "wire_flir")
hook.Remove("PreRender", "wire_flir")
hook.Remove("OnEntityCreated", "wire_flir")
hook.Remove("CreateClientsideRagdoll", "wire_flir")
for _, v in ipairs(ents.GetAll()) do
RemoveFLIR(v)
end
end
function FLIR.toggle()
if not FLIR.enabled then FLIR.start() else FLIR.stop() end
end
concommand.Add("flir_toggle", function()
FLIR.toggle()
end)
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
net.Receive("FLIR.enable", function()
local enabled = net.ReadBool()
FLIR.enable(enabled)
end)
else
function FLIR.start(ply) FLIR.enable(ply, true) end
function FLIR.stop(ply) FLIR.enable(ply, false) end
util.AddNetworkString("FLIR.enable")
function FLIR.enable(ply, enabled)
net.Start("FLIR.enable")
net.WriteBool(enabled)
net.Send(ply)
end
end
|
Better(er) FLIR rendering (#2308)
|
Better(er) FLIR rendering (#2308)
* Fixed FLIR behavior and improved performance
* Reverted stencil->material to fix fog, setlightingmode(1)->mat_fullbright 1
* Moved Color() outside of hook, added colormod and suppressenginelighting
* added sun to TODO
* revert all prop_ entities to just prop_physics, render translucent props with dark texture to help with brightness
* lowered FLIR.col values to show texture
* raise flir.col slightly
* commented setcolormodulation since it's 1 now, fixed NPCs drawing after death
* Added client cvar for FLIR gain, so I don't decide the brightness for everyone
* removed unnecessary color call
* added check to make sure ents are actually removed on callonremove
* simplified rendering loop
* ipairs
* default gain 2 -> 2.2, translucent material changed to be less dark
* changed trans texture again because I used a CS texture...
* IsValid(ent) -> ent:IsValid(), removed CallOnRemove
|
Lua
|
apache-2.0
|
wiremod/wire,Grocel/wire,dvdvideo1234/wire
|
96ce71d67a2d27adaf58bca878c566110183bd1d
|
mod_websocket/mod_websocket.lua
|
mod_websocket/mod_websocket.lua
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit = softreq"bit" or softreq"bit32" or module:log("error", "No bit module found. Either LuaJIT 2 or Lua 5.2 is required");
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit;
pcall(function() bit = require"bit"; end);
bit = bit or softreq"bit32"
if not bit then module:log("error", "No bit module found. Either LuaJIT 2, lua-bitop or Lua 5.2 is required"); end
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
mod_websocket: Fix require to work with lua-bitop (Thanks István and Zash)
|
mod_websocket: Fix require to work with lua-bitop (Thanks István and Zash)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
2568da78b65fbaff91a27c1eb31264aa4a100fb6
|
lib/upstream.lua
|
lib/upstream.lua
|
local digest = require('openssl').digest.digest
local git = require('creationix/git')
local deframe = git.deframe
local decodeTag = git.decoders.tag
local decodeTree = git.decoders.tree
local connect = require('creationix/coro-tcp').connect
local makeRemote = require('./codec').makeRemote
return function (storage, host, port)
local read, write, socket = assert(connect(host, port or 4821))
local remote = makeRemote(read, write)
local upstream = {}
-- Client: SEND tagObject
-- Server: WANTS objectHash
-- Client: SEND object
-- Server: WANTS ...
-- Client: SEND ...
-- Client: SEND ...
-- Client: SEND ...
-- Server: DONE hash
function upstream.push(hash)
remote.writeAs("send", storage.load(hash))
while true do
local name, data = remote.read()
if name == "wants" then
for i = 1, #data do
remote.writeAs("send", storage.load(data[i]))
end
elseif name == "done" then
return data
else
error("Expected more wants or done in reply to send to server")
end
end
end
-- Client: WANT tagHash
-- Server: SEND tagObject
-- Client: WANT objectHash
-- Server: SEND object
-- Client: WANT ...
-- Client: WANT ...
-- Client: WANT ...
-- Server: SEND ...
-- Server: SEND ...
-- Server: SEND ...
function upstream.pull(hash)
local list = {hash}
local refs = {}
repeat
local hashes = list
list = {}
remote.writeAs("wants", hashes)
for i = 1, #hashes do
local hash = hashes[i]
local data = remote.readAs("send")
assert(digest("sha1", data) == hash, "hash mismatch in result object")
local kind, body = deframe(data)
if kind == "tag" then
local tag = decodeTag(body)
-- TODO: verify tag
refs[tag.tag] = hash
-- Check if we have the object the tag points to.
if not storage.has(tag.object) then
-- If not, add it to the list
table.insert(list, tag.object)
end
elseif kind == "tree" then
local tree = decodeTree(body)
for i = 1, #tree do
local subHash = tree[i].hash
if not storage.has(subHash) then
table.insert(list, subHash)
end
end
end
storage.save(data)
end
until #list == 0
for ref, hash in pairs(refs) do
storage.write(ref, hash)
end
return refs
end
-- Client: WANTS hash
-- Server: SEND data
function upstream.load(hash)
remote.writeAs("wants", {hash})
local data = remote.readAs("send")
assert(digest("sha1", data) == hash, "hash mismatch in result object")
storage.save(data)
return data
end
-- Client: MATCH name version
-- SERVER: REPLY version hash
function upstream.read(name, version)
remote.writeAs("read", name .. " " .. version)
local data = assert(remote.readAs("reply"))
local match, hash = string.match(data, "^([^ ]+) (.*)$")
return match, hash
end
function upstream.match(name, version)
remote.writeAs("match", version and (name .. " " .. version) or name)
local data = assert(remote.readAs("reply"))
local match, hash = string.match(data, "^([^ ]+) (.*)$")
return match, hash
end
--[[
upstream.close()
----------------
Called when the db is done with the connection.
]]--
function upstream.close()
return socket:close()
end
return upstream
end
|
local digest = require('openssl').digest.digest
local git = require('creationix/git')
local deframe = git.deframe
local decodeTag = git.decoders.tag
local decodeTree = git.decoders.tree
local connect = require('creationix/coro-tcp').connect
local makeRemote = require('./codec').makeRemote
return function (storage, host, port)
local read, write, socket = assert(connect(host, port or 4821))
local remote = makeRemote(read, write)
local upstream = {}
-- Client: SEND tagObject
-- Server: WANTS objectHash
-- Client: SEND object
-- Server: WANTS ...
-- Client: SEND ...
-- Client: SEND ...
-- Client: SEND ...
-- Server: DONE hash
function upstream.push(hash)
remote.writeAs("send", storage.load(hash))
while true do
local name, data = remote.read()
if name == "wants" then
for i = 1, #data do
remote.writeAs("send", storage.load(data[i]))
end
elseif name == "done" then
return data
else
error("Expected more wants or done in reply to send to server")
end
end
end
-- Client: WANT tagHash
-- Server: SEND tagObject
-- Client: WANT objectHash
-- Server: SEND object
-- Client: WANT ...
-- Client: WANT ...
-- Client: WANT ...
-- Server: SEND ...
-- Server: SEND ...
-- Server: SEND ...
function upstream.pull(hash)
local list = {hash}
local refs = {}
repeat
local hashes = list
list = {}
-- Fetch any hashes from list we don't have already
local wants = {}
for i = 1, #hashes do
local hash = hashes[i]
if not storage.has(hash) then
wants[#wants + 1] = hash
end
end
if #wants > 0 then
remote.writeAs("wants", wants)
for i = 1, #wants do
local hash = hashes[i]
local data = remote.readAs("send")
assert(digest("sha1", data) == hash, "hash mismatch in result object")
assert(storage.save(data) == hash)
end
end
-- Process the hashes looking for child nodes
for i = 1, #hashes do
local hash = hashes[i]
local data = storage.load(hash)
local kind, body = deframe(data)
if kind == "tag" then
local tag = decodeTag(body)
-- TODO: verify tag
refs[tag.tag] = hash
table.insert(list, tag.object)
elseif kind == "tree" then
local tree = decodeTree(body)
for i = 1, #tree do
local subHash = tree[i].hash
table.insert(list, subHash)
end
end
end
until #list == 0
for ref, hash in pairs(refs) do
storage.write(ref, hash)
end
return refs
end
-- Client: WANTS hash
-- Server: SEND data
function upstream.load(hash)
remote.writeAs("wants", {hash})
local data = remote.readAs("send")
assert(digest("sha1", data) == hash, "hash mismatch in result object")
storage.save(data)
return data
end
-- Client: MATCH name version
-- SERVER: REPLY version hash
function upstream.read(name, version)
remote.writeAs("read", name .. " " .. version)
local data = assert(remote.readAs("reply"))
local match, hash = string.match(data, "^([^ ]+) (.*)$")
return match, hash
end
function upstream.match(name, version)
remote.writeAs("match", version and (name .. " " .. version) or name)
local data = assert(remote.readAs("reply"))
local match, hash = string.match(data, "^([^ ]+) (.*)$")
return match, hash
end
--[[
upstream.close()
----------------
Called when the db is done with the connection.
]]--
function upstream.close()
return socket:close()
end
return upstream
end
|
Fix upstream.pull to not fetch objects already cached locally
|
Fix upstream.pull to not fetch objects already cached locally
|
Lua
|
apache-2.0
|
zhaozg/lit,squeek502/lit,lduboeuf/lit,james2doyle/lit,DBarney/lit,kidaa/lit,luvit/lit,1yvT0s/lit,kaustavha/lit
|
33a29cebe37af33a03c7172c2ce4ee82ab342d91
|
spec/integration/cli/restart_spec.lua
|
spec/integration/cli/restart_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
describe("CLI", function()
setup(function()
pcall(spec_helper.stop_kong)
end)
teardown(function()
pcall(spec_helper.stop_kong)
end)
it("should restart kong when it's not running", function()
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's running", function()
local res, code = spec_helper.stop_kong()
assert.are.same(0, code)
local res, code = spec_helper.start_kong()
assert.are.same(0, code)
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's crashed", function()
os.execute("pkill -9 nginx")
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should not restart kong when the port is taken", function()
spec_helper.stop_kong()
local thread = spec_helper.start_tcp_server(spec_helper.TEST_PROXY_PORT)
local ok, res = pcall(spec_helper.restart_kong)
assert.falsy(ok)
thread:join()
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
describe("CLI", function()
setup(function()
pcall(spec_helper.stop_kong)
end)
teardown(function()
pcall(spec_helper.stop_kong)
end)
it("should restart kong when it's not running", function()
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's running", function()
local res, code = spec_helper.stop_kong()
assert.are.same(0, code)
local res, code = spec_helper.start_kong()
assert.are.same(0, code)
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's crashed", function()
os.execute("pkill -9 nginx")
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
end)
|
Fixing tests
|
Fixing tests
|
Lua
|
apache-2.0
|
Mashape/kong,ejoncas/kong,ejoncas/kong,Kong/kong,xvaara/kong,Kong/kong,salazar/kong,akh00/kong,ajayk/kong,ind9/kong,isdom/kong,beauli/kong,ind9/kong,jebenexer/kong,rafael/kong,smanolache/kong,Kong/kong,vzaramel/kong,li-wl/kong,ccyphers/kong,vzaramel/kong,Vermeille/kong,streamdataio/kong,jerizm/kong,streamdataio/kong,isdom/kong,kyroskoh/kong,icyxp/kong,rafael/kong,shiprabehera/kong,kyroskoh/kong
|
591abadf8a4874d83fbdad28317b7d9679a04ed9
|
src/cosy/loader/js.lua
|
src/cosy/loader/js.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (options)
options = options or {}
local loader = {}
for k, v in pairs (options) do
loader [k] = v
end
local global = _G or _ENV
loader.home = "/"
loader.prefix = "/"
loader.js = global.js
loader.window = loader.js.global
loader.document = loader.js.global.document
loader.screen = loader.js.global.screen
local modules = setmetatable ({}, { __mode = "kv" })
loader.request = function (url)
local request = loader.js.new (loader.window.XMLHttpRequest)
request:open ("GET", url, false)
request:send (nil)
if request.status == 200 then
return request.responseText, request.status
else
return nil , request.status
end
end
table.insert (package.searchers, 2, function (name)
local url = "/lua/" .. name
local result, err
result, err = loader.request (url)
if not result then
error (err)
end
return load (result, url)
end)
loader.require = require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.coroutine = loader.require "coroutine.make" ()
loader.logto = true
loader.scheduler = {
_running = nil,
waiting = {},
ready = {},
coroutine = loader.coroutine,
}
function loader.scheduler.running ()
return loader.scheduler._running
end
function loader.scheduler.addthread (f, ...)
local co = loader.scheduler.coroutine.create (f)
loader.scheduler.ready [co] = {
parameters = { ... },
}
end
function loader.scheduler.sleep (time)
time = time or -math.huge
local co = loader.scheduler.running ()
if time > 0 then
loader.window:setTimeout (function ()
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
if coroutine.status (loader.scheduler.co) == "suspended" then
coroutine.resume (loader.scheduler.co)
end
end, time * 1000)
end
if time ~= 0 then
loader.scheduler.waiting [co] = true
loader.scheduler.ready [co] = nil
loader.scheduler.coroutine.yield ()
end
end
function loader.scheduler.wakeup (co)
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
coroutine.resume (loader.scheduler.co)
end
function loader.scheduler.loop ()
while true do
local to_run, t = next (loader.scheduler.ready)
if to_run then
if loader.scheduler.coroutine.status (to_run) == "suspended" then
loader.scheduler._running = to_run
local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters))
if not ok then
loader.window.console:log (err)
end
end
if loader.scheduler.coroutine.status (to_run) == "dead" then
loader.scheduler.waiting [to_run] = nil
loader.scheduler.ready [to_run] = nil
end
end
if not next (loader.scheduler.ready )
and not next (loader.scheduler.waiting) then
break
elseif not next (loader.scheduler.ready) then
loader.scheduler.co = coroutine.running ()
coroutine.yield ()
end
end
end
local _ = loader.load "cosy.string"
local Value = loader.load "cosy.value"
loader.library = loader.load "cosy.library"
loader.storage = loader.js.global.sessionStorage
local data = loader.storage:getItem "cosy:client"
if data == loader.js.null then
data = nil
else
data = Value.decode (data)
end
loader.client = loader.library.connect (loader.js.global.location.origin, data)
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (options)
options = options or {}
local loader = {}
for k, v in pairs (options) do
loader [k] = v
end
local global = _G or _ENV
loader.home = "/"
loader.prefix = "/"
loader.js = global.js
loader.window = loader.js.global
loader.document = loader.js.global.document
loader.screen = loader.js.global.screen
local modules = setmetatable ({}, { __mode = "kv" })
loader.request = function (url)
local request = loader.js.new (loader.window.XMLHttpRequest)
request:open ("GET", url, false)
request:send (nil)
if request.status == 200 then
return request.responseText, request.status
else
return nil , request.status
end
end
table.insert (package.searchers, 2, function (name)
local url = "/lua/" .. name
local result, err
result, err = loader.request (url)
if not result then
error (err)
end
return load (result, url)
end)
loader.require = require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.coroutine = loader.require "coroutine.make" ()
loader.logto = true
loader.scheduler = {
_running = nil,
waiting = {},
ready = {},
coroutine = loader.coroutine,
timeout = {},
}
function loader.scheduler.running ()
return loader.scheduler._running
end
function loader.scheduler.addthread (f, ...)
local co = loader.scheduler.coroutine.create (f)
loader.scheduler.ready [co] = {
parameters = { ... },
}
end
function loader.scheduler.sleep (time)
time = time or -math.huge
local co = loader.scheduler.running ()
if time > 0 then
loader.scheduler.timeout [co] = loader.window:setTimeout (function ()
loader.window:clearTimeout (loader.scheduler.timeout [co])
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
if coroutine.status (loader.scheduler.co) == "suspended" then
coroutine.resume (loader.scheduler.co)
end
end, time * 1000)
end
if time ~= 0 then
loader.scheduler.waiting [co] = true
loader.scheduler.ready [co] = nil
loader.scheduler.coroutine.yield ()
end
end
function loader.scheduler.wakeup (co)
loader.window:clearTimeout (loader.scheduler.timeout [co])
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
coroutine.resume (loader.scheduler.co)
end
function loader.scheduler.loop ()
while true do
local to_run, t = next (loader.scheduler.ready)
if to_run then
if loader.scheduler.coroutine.status (to_run) == "suspended" then
loader.scheduler._running = to_run
local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters))
if not ok then
loader.window.console:log (err)
end
end
if loader.scheduler.coroutine.status (to_run) == "dead" then
loader.scheduler.waiting [to_run] = nil
loader.scheduler.ready [to_run] = nil
end
end
if not next (loader.scheduler.ready )
and not next (loader.scheduler.waiting) then
break
elseif not next (loader.scheduler.ready) then
loader.scheduler.co = coroutine.running ()
coroutine.yield ()
end
end
end
local _ = loader.load "cosy.string"
local Value = loader.load "cosy.value"
loader.library = loader.load "cosy.library"
loader.storage = loader.js.global.sessionStorage
local data = loader.storage:getItem "cosy:client"
if data == loader.js.null then
data = nil
else
data = Value.decode (data)
end
loader.client = loader.library.connect (loader.js.global.location.origin, data)
return loader
end
|
Fix sleep/wakeup in JS loader.
|
Fix sleep/wakeup in JS loader.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
0912522eb9217cb3bf3ee0a9c2eb3af181acddce
|
game/scripts/vscripts/data/abilities.lua
|
game/scripts/vscripts/data/abilities.lua
|
LINKED_ABILITIES = {
shredder_chakram_2 = {"shredder_return_chakram_2"},
shredder_chakram = {"shredder_return_chakram"},
kunkka_x_marks_the_spot = {"kunkka_return"},
life_stealer_infest = {"life_stealer_control", "life_stealer_consume"},
rubick_telekinesis = {"rubick_telekinesis_land"},
bane_nightmare = {"bane_nightmare_end"},
phoenix_icarus_dive = {"phoenix_icarus_dive_stop"},
phoenix_fire_spirits = {"phoenix_launch_fire_spirit"},
ancient_apparition_ice_blast = {"ancient_apparition_ice_blast_release"},
wisp_tether = {"wisp_tether_break"},
alchemist_unstable_concoction = {"alchemist_unstable_concoction_throw"},
monkey_king_mischief = {"monkey_king_untransform"},
monkey_king_primal_spring = {"monkey_king_primal_spring_early"},
}
MULTICAST_TYPE_NONE = 0
MULTICAST_TYPE_SAME = 1 -- Fireblast
MULTICAST_TYPE_DIFFERENT = 2 -- Ignite
MULTICAST_TYPE_INSTANT = 3 -- Bloodlust
MULTICAST_ABILITIES = {
ogre_magi_bloodlust = MULTICAST_TYPE_NONE,
ogre_magi_fireblast = MULTICAST_TYPE_NONE,
ogre_magi_ignite = MULTICAST_TYPE_NONE,
ogre_magi_unrefined_fireblast = MULTICAST_TYPE_NONE,
ogre_magi_multicast_arena = MULTICAST_TYPE_NONE,
invoker_quas = MULTICAST_TYPE_NONE,
invoker_wex = MULTICAST_TYPE_NONE,
invoker_exort = MULTICAST_TYPE_NONE,
invoker_invoke = MULTICAST_TYPE_NONE,
shredder_chakram = MULTICAST_TYPE_NONE,
alchemist_unstable_concoction = MULTICAST_TYPE_NONE,
alchemist_unstable_concoction_throw = MULTICAST_TYPE_NONE,
elder_titan_ancestral_spirit = MULTICAST_TYPE_NONE,
elder_titan_return_spirit = MULTICAST_TYPE_NONE,
ember_spirit_sleight_of_fist = MULTICAST_TYPE_NONE,
monkey_king_tree_dance = MULTICAST_TYPE_NONE,
monkey_king_primal_spring = MULTICAST_TYPE_NONE,
monkey_king_primal_spring_early = MULTICAST_TYPE_NONE,
terrorblade_conjure_image = MULTICAST_TYPE_INSTANT,
terrorblade_reflection = MULTICAST_TYPE_INSTANT,
magnataur_empower = MULTICAST_TYPE_INSTANT,
oracle_purifying_flames = MULTICAST_TYPE_SAME,
vengefulspirit_magic_missile = MULTICAST_TYPE_SAME,
}
REFRESH_LIST_IGNORE_REFRESHER = {
item_refresher_arena = true,
item_refresher_core = true,
}
REFRESH_LIST_IGNORE_BODY_RECONSTRUCTION = {
item_refresher_arena = true,
item_refresher_core = true,
item_black_king_bar = true,
item_titanium_bar = true,
item_coffee_bean = true,
destroyer_body_reconstruction = true,
}
REFRESH_LIST_IGNORE_REARM = {
tinker_rearm_arena = true,
item_refresher_arena = true,
item_refresher_core = true,
item_titanium_bar = true,
item_guardian_greaves_arena = true,
item_demon_king_bar = true,
item_pipe = true,
item_arcane_boots = true,
item_helm_of_the_dominator = true,
item_sphere = true,
item_necronomicon = true,
item_hand_of_midas_arena = true,
item_hand_of_midas_2_arena = true,
item_hand_of_midas_3_arena = true,
item_mekansm_arena = true,
item_mekansm_2 = true,
item_black_king_bar_arena = true,
item_black_king_bar_2 = true,
item_black_king_bar_3 = true,
item_black_king_bar_4 = true,
item_black_king_bar_5 = true,
item_black_king_bar_6 = true,
destroyer_body_reconstruction = true,
stargazer_cosmic_countdown = true,
faceless_void_chronosphere = true,
zuus_thundergods_wrath = true,
enigma_black_hole = true,
freya_pain_reflection = true,
skeleton_king_reincarnation = true,
dazzle_shallow_grave = true,
zuus_cloud = true,
ancient_apparition_ice_blast = true,
silencer_global_silence = true,
naga_siren_song_of_the_siren = true,
slark_shadow_dance = true,
}
COFFEE_BEAN_NOT_REFRESHABLE = {
zuus_cloud = true,
monkey_king_boundless_strike = true,
dazzle_shallow_grave = true,
saitama_push_ups = true,
saitama_squats = true,
saitama_sit_ups = true,
}
BOSS_BANNED_ABILITIES = {
item_heart_cyclone = true,
item_blink_staff = true,
item_urn_of_demons = true,
razor_static_link = true,
tusk_walrus_kick = true,
death_prophet_spirit_siphon = true,
item_force_staff = true,
item_hurricane_pike = true,
rubick_telekinesis = true,
item_demon_king_bar = true,
morphling_adaptive_strike_str = true,
item_spirit_helix = true,
pugna_life_drain = true,
}
-- "CalculateSpellDamageTooltip" "0"
SPELL_AMPLIFY_NOT_SCALABLE_MODIFIERS = {
zuus_static_field = true,
enigma_midnight_pulse = true,
enigma_black_hole = true,
zaken_stitching_strikes = true,
morphling_adaptive_strike_agi = true,
nyx_assassin_mana_burn = true,
elder_titan_earth_splitter = true,
necrolyte_reapers_scythe = true,
doom_bringer_infernal_blade = true,
phoenix_sun_ray = true,
silencer_glaives_of_wisdom = true,
winter_wyvern_arctic_burn = true,
obsidian_destroyer_sanity_eclipse = true,
centaur_stampede = true,
obsidian_destroyer_arcane_orb = true,
spectre_dispersion = true,
skywrath_mage_arcane_bolt = true,
centaur_return = true,
huskar_life_break = true,
item_spirit_helix = true,
item_ethereal_blade = true,
}
OCTARINE_NOT_LIFESTALABLE_ABILITIES = {
["freya_pain_reflection"] = true,
["spectre_dispersion"] = true,
}
ARENA_NOT_CASTABLE_ABILITIES = {
["techies_land_mines"] = GetAbilitySpecial("techies_land_mines", "radius"),
["techies_stasis_trap"] = GetAbilitySpecial("techies_stasis_trap", "activation_radius"),
["techies_remote_mines"] = GetAbilitySpecial("techies_land_mines", "radius"),
["invoker_chaos_meteor"] = 1100,
["disruptor_thunder_strike"] = GetAbilitySpecial("disruptor_thunder_strike", "radius"),
["pugna_nether_blast"] = GetAbilitySpecial("pugna_nether_blast", "radius"),
["enigma_midnight_pulse"] = GetAbilitySpecial("enigma_midnight_pulse", "radius"),
["abyssal_underlord_firestorm"] = GetAbilitySpecial("abyssal_underlord_firestorm", "radius"),
["skywrath_mage_mystic_flare"] = GetAbilitySpecial("skywrath_mage_mystic_flare", "radius"),
}
PERCENT_DAMAGE_MODIFIERS = {
}
-- https://dota2.gamepedia.com/Spell_Reflection#Not_reflected_abilities
SPELL_REFLECT_IGNORED_ABILITIES = {
grimstroke_soul_chain = true,
morphling_replicate = true,
rubick_spell_steal = true,
}
|
LINKED_ABILITIES = {
shredder_chakram_2 = {"shredder_return_chakram_2"},
shredder_chakram = {"shredder_return_chakram"},
kunkka_x_marks_the_spot = {"kunkka_return"},
life_stealer_infest = {"life_stealer_control", "life_stealer_consume"},
rubick_telekinesis = {"rubick_telekinesis_land"},
bane_nightmare = {"bane_nightmare_end"},
phoenix_icarus_dive = {"phoenix_icarus_dive_stop"},
phoenix_fire_spirits = {"phoenix_launch_fire_spirit"},
ancient_apparition_ice_blast = {"ancient_apparition_ice_blast_release"},
wisp_tether = {"wisp_tether_break"},
alchemist_unstable_concoction = {"alchemist_unstable_concoction_throw"},
monkey_king_mischief = {"monkey_king_untransform"},
monkey_king_primal_spring = {"monkey_king_primal_spring_early"},
}
MULTICAST_TYPE_NONE = 0
MULTICAST_TYPE_SAME = 1 -- Fireblast
MULTICAST_TYPE_DIFFERENT = 2 -- Ignite
MULTICAST_TYPE_INSTANT = 3 -- Bloodlust
MULTICAST_ABILITIES = {
ogre_magi_bloodlust = MULTICAST_TYPE_NONE,
ogre_magi_fireblast = MULTICAST_TYPE_NONE,
ogre_magi_ignite = MULTICAST_TYPE_NONE,
ogre_magi_unrefined_fireblast = MULTICAST_TYPE_NONE,
ogre_magi_multicast_arena = MULTICAST_TYPE_NONE,
item_manta_arena = MULTICAST_TYPE_NONE,
item_diffusal_style = MULTICAST_TYPE_NONE,
item_refresher_arena = MULTICAST_TYPE_NONE,
item_refresher_core = MULTICAST_TYPE_NONE,
invoker_quas = MULTICAST_TYPE_NONE,
invoker_wex = MULTICAST_TYPE_NONE,
invoker_exort = MULTICAST_TYPE_NONE,
invoker_invoke = MULTICAST_TYPE_NONE,
shredder_chakram = MULTICAST_TYPE_NONE,
alchemist_unstable_concoction = MULTICAST_TYPE_NONE,
alchemist_unstable_concoction_throw = MULTICAST_TYPE_NONE,
elder_titan_ancestral_spirit = MULTICAST_TYPE_NONE,
elder_titan_return_spirit = MULTICAST_TYPE_NONE,
ember_spirit_sleight_of_fist = MULTICAST_TYPE_NONE,
monkey_king_tree_dance = MULTICAST_TYPE_NONE,
monkey_king_primal_spring = MULTICAST_TYPE_NONE,
monkey_king_primal_spring_early = MULTICAST_TYPE_NONE,
wisp_spirits = MULTICAST_TYPE_NONE,
wisp_spirits_in = MULTICAST_TYPE_NONE,
wisp_spirits_out = MULTICAST_TYPE_NONE,
arc_warden_tempest_double = MULTICAST_TYPE_NONE,
phoenix_sun_ray = MULTICAST_TYPE_NONE,
phoenix_sun_ray_stop = MULTICAST_TYPE_NONE,
phoenix_sun_ray_toggle_move = MULTICAST_TYPE_NONE,
terrorblade_conjure_image = MULTICAST_TYPE_INSTANT,
terrorblade_reflection = MULTICAST_TYPE_INSTANT,
magnataur_empower = MULTICAST_TYPE_INSTANT,
oracle_purifying_flames = MULTICAST_TYPE_SAME,
vengefulspirit_magic_missile = MULTICAST_TYPE_SAME,
}
REFRESH_LIST_IGNORE_REFRESHER = {
item_refresher_arena = true,
item_refresher_core = true,
}
REFRESH_LIST_IGNORE_BODY_RECONSTRUCTION = {
item_refresher_arena = true,
item_refresher_core = true,
item_black_king_bar = true,
item_titanium_bar = true,
item_coffee_bean = true,
destroyer_body_reconstruction = true,
}
REFRESH_LIST_IGNORE_REARM = {
tinker_rearm_arena = true,
item_refresher_arena = true,
item_refresher_core = true,
item_titanium_bar = true,
item_guardian_greaves_arena = true,
item_demon_king_bar = true,
item_pipe = true,
item_arcane_boots = true,
item_helm_of_the_dominator = true,
item_sphere = true,
item_necronomicon = true,
item_hand_of_midas_arena = true,
item_hand_of_midas_2_arena = true,
item_hand_of_midas_3_arena = true,
item_mekansm_arena = true,
item_mekansm_2 = true,
item_black_king_bar_arena = true,
item_black_king_bar_2 = true,
item_black_king_bar_3 = true,
item_black_king_bar_4 = true,
item_black_king_bar_5 = true,
item_black_king_bar_6 = true,
destroyer_body_reconstruction = true,
stargazer_cosmic_countdown = true,
faceless_void_chronosphere = true,
zuus_thundergods_wrath = true,
enigma_black_hole = true,
freya_pain_reflection = true,
skeleton_king_reincarnation = true,
dazzle_shallow_grave = true,
zuus_cloud = true,
ancient_apparition_ice_blast = true,
silencer_global_silence = true,
naga_siren_song_of_the_siren = true,
slark_shadow_dance = true,
}
COFFEE_BEAN_NOT_REFRESHABLE = {
zuus_cloud = true,
monkey_king_boundless_strike = true,
dazzle_shallow_grave = true,
saitama_push_ups = true,
saitama_squats = true,
saitama_sit_ups = true,
}
BOSS_BANNED_ABILITIES = {
item_heart_cyclone = true,
item_blink_staff = true,
item_urn_of_demons = true,
razor_static_link = true,
tusk_walrus_kick = true,
death_prophet_spirit_siphon = true,
item_force_staff = true,
item_hurricane_pike = true,
rubick_telekinesis = true,
item_demon_king_bar = true,
morphling_adaptive_strike_str = true,
item_spirit_helix = true,
pugna_life_drain = true,
}
-- "CalculateSpellDamageTooltip" "0"
SPELL_AMPLIFY_NOT_SCALABLE_MODIFIERS = {
zuus_static_field = true,
enigma_midnight_pulse = true,
enigma_black_hole = true,
zaken_stitching_strikes = true,
morphling_adaptive_strike_agi = true,
nyx_assassin_mana_burn = true,
elder_titan_earth_splitter = true,
necrolyte_reapers_scythe = true,
doom_bringer_infernal_blade = true,
phoenix_sun_ray = true,
silencer_glaives_of_wisdom = true,
winter_wyvern_arctic_burn = true,
obsidian_destroyer_sanity_eclipse = true,
centaur_stampede = true,
obsidian_destroyer_arcane_orb = true,
spectre_dispersion = true,
skywrath_mage_arcane_bolt = true,
centaur_return = true,
huskar_life_break = true,
item_spirit_helix = true,
item_ethereal_blade = true,
}
OCTARINE_NOT_LIFESTALABLE_ABILITIES = {
["freya_pain_reflection"] = true,
["spectre_dispersion"] = true,
}
ARENA_NOT_CASTABLE_ABILITIES = {
["techies_land_mines"] = GetAbilitySpecial("techies_land_mines", "radius"),
["techies_stasis_trap"] = GetAbilitySpecial("techies_stasis_trap", "activation_radius"),
["techies_remote_mines"] = GetAbilitySpecial("techies_land_mines", "radius"),
["invoker_chaos_meteor"] = 1100,
["disruptor_thunder_strike"] = GetAbilitySpecial("disruptor_thunder_strike", "radius"),
["pugna_nether_blast"] = GetAbilitySpecial("pugna_nether_blast", "radius"),
["enigma_midnight_pulse"] = GetAbilitySpecial("enigma_midnight_pulse", "radius"),
["abyssal_underlord_firestorm"] = GetAbilitySpecial("abyssal_underlord_firestorm", "radius"),
["skywrath_mage_mystic_flare"] = GetAbilitySpecial("skywrath_mage_mystic_flare", "radius"),
}
PERCENT_DAMAGE_MODIFIERS = {
}
-- https://dota2.gamepedia.com/Spell_Reflection#Not_reflected_abilities
SPELL_REFLECT_IGNORED_ABILITIES = {
grimstroke_soul_chain = true,
morphling_replicate = true,
rubick_spell_steal = true,
}
|
balance(ogre_magi): disable multicast on some abilities
|
balance(ogre_magi): disable multicast on some abilities
Refs #458, fixes #465, fixes #467.
|
Lua
|
mit
|
ark120202/aabs
|
46039b963e7801131747706e83c999960776402f
|
vrp/modules/map.lua
|
vrp/modules/map.lua
|
local client_areas = {}
-- free client areas when leaving
AddEventHandler("vRP:playerLeave",function(user_id,source)
-- leave areas
local areas = client_areas[source]
if areas then
for k,area in pairs(areas) do
if area.inside then
area.leave(source,k)
end
end
end
client_areas[source] = nil
end)
-- create/update a player area
function vRP.setArea(source,name,x,y,z,radius,height,cb_enter,cb_leave)
local areas = client_areas[source] or {}
client_areas[source] = areas
areas[name] = {enter=cb_enter,leave=cb_leave}
vRPclient._setArea(source,name,x,y,z,radius,height)
end
-- check if a player is in an area
function vRP.inArea(source,name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area then return area.inside end
end
end
-- delete a player area
function vRP.removeArea(source,name)
-- delete remote area
vRPclient._removeArea(source,name)
-- delete local area
local areas = client_areas[source]
if areas then
areas[name] = nil
end
end
-- TUNNER SERVER API
function tvRP.enterArea(name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area and area.enter and not area.inside then -- trigger enter callback
area.inside = true
area.enter(source,name)
end
end
end
function tvRP.leaveArea(name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area and area.leave and area.inside then -- trigger leave callback
area.inside = false
area.leave(source,name)
end
end
end
local cfg = module("cfg/blips_markers")
-- add additional static blips/markers
AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn)
if first_spawn then
for k,v in pairs(cfg.blips) do
vRPclient._addBlip(source,v[1],v[2],v[3],v[4],v[5],v[6])
end
for k,v in pairs(cfg.markers) do
vRPclient._addMarker(source,v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11])
end
end
end)
|
local client_areas = {}
-- free client areas when leaving
AddEventHandler("vRP:playerLeave",function(user_id,source)
-- leave areas
local areas = client_areas[source]
if areas then
for k,area in pairs(areas) do
if area.inside and area.leave then
area.leave(source,k)
end
end
end
client_areas[source] = nil
end)
-- create/update a player area
function vRP.setArea(source,name,x,y,z,radius,height,cb_enter,cb_leave)
local areas = client_areas[source] or {}
client_areas[source] = areas
areas[name] = {enter=cb_enter,leave=cb_leave}
vRPclient._setArea(source,name,x,y,z,radius,height)
end
-- check if a player is in an area
function vRP.inArea(source,name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area then return area.inside end
end
end
-- delete a player area
function vRP.removeArea(source,name)
-- delete remote area
vRPclient._removeArea(source,name)
-- delete local area
local areas = client_areas[source]
if areas then
local area = areas[name]
if area and area.inside then
if area.leave then
area.leave(source,name)
end
areas[name] = nil
end
end
end
-- TUNNER SERVER API
function tvRP.enterArea(name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area and not area.inside then -- trigger enter callback
area.inside = true
if area.enter then
area.enter(source,name)
end
end
end
end
function tvRP.leaveArea(name)
local areas = client_areas[source]
if areas then
local area = areas[name]
if area and area.inside then -- trigger leave callback
area.inside = false
if area.leave then
area.leave(source,name)
end
end
end
end
local cfg = module("cfg/blips_markers")
-- add additional static blips/markers
AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn)
if first_spawn then
for k,v in pairs(cfg.blips) do
vRPclient._addBlip(source,v[1],v[2],v[3],v[4],v[5],v[6])
end
for k,v in pairs(cfg.markers) do
vRPclient._addMarker(source,v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11])
end
end
end)
|
Fix more area issues with nil callbacks.
|
Fix more area issues with nil callbacks.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
6925ff13d0ea593eda5883650421286eae9384fe
|
core/Matrix4.lua
|
core/Matrix4.lua
|
local class = require 'middleclass'
local Matrix4 = class('core/Matrix4')
function Matrix4:initialize( handle )
if handle then
self.handle = handle
else
self.handle = NATIVE.CreateMatrix4()
end
end
function Matrix4:copy()
return Matrix4.new(NATIVE.CopyMatrix4(self.handle))
end
function Matrix4:__add( other )
return Matrix4.new(NATIVE.AddMatrix4(self, other))
end
function Matrix4:__sub( other )
return Matrix4.new(NATIVE.SubMatrix4(self, other))
end
function Matrix4:__mul( other )
return Matrix4.new(NATIVE.MulMatrix4(self, other))
end
function Matrix4:__div( other )
return Matrix4.new(NATIVE.DivMatrix4(self, other))
end
function Matrix4:translate( x, y, z )
return Matrix4.new(NATIVE.TranslateMatrix4(self.handle, x, y, z))
end
function Matrix4:scale( x, y, z )
return Matrix4.new(NATIVE.ScaleMatrix4(self.handle, x, y, z))
end
function Matrix4:rotate( angle, x, y, z )
return Matrix4.new(NATIVE.RotateMatrix4(self.handle, angle, x, y, z))
end
function Matrix4:transform( x, y, z, w )
w = w or 0
return NATIVE.Matrix4TransformVector(self.handle, x, y, z, w)
end
function Matrix4:toRotationMatrix()
return Matrix4.new(NATIVE.MakeRotationMatrix(self.handle))
end
return Matrix4
|
local class = require 'middleclass'
local Matrix4 = class('core/Matrix4')
function Matrix4:initialize( handle )
self.handle = handle or NATIVE.CreateMatrix4()
end
function Matrix4:copy()
return Matrix4:new(NATIVE.CopyMatrix4(self.handle))
end
function Matrix4:__add( other )
return Matrix4:new(NATIVE.AddMatrix4(self, other))
end
function Matrix4:__sub( other )
return Matrix4:new(NATIVE.SubMatrix4(self, other))
end
function Matrix4:__mul( other )
return Matrix4:new(NATIVE.MulMatrix4(self, other))
end
function Matrix4:__div( other )
return Matrix4:new(NATIVE.DivMatrix4(self, other))
end
function Matrix4:translate( x, y, z )
return Matrix4:new(NATIVE.TranslateMatrix4(self.handle, x, y, z))
end
function Matrix4:scale( x, y, z )
return Matrix4:new(NATIVE.ScaleMatrix4(self.handle, x, y, z))
end
function Matrix4:rotate( angle, x, y, z )
return Matrix4:new(NATIVE.RotateMatrix4(self.handle, angle, x, y, z))
end
function Matrix4:transform( x, y, z, w )
w = w or 0
return NATIVE.Matrix4TransformVector(self.handle, x, y, z, w)
end
function Matrix4:toRotationMatrix()
return Matrix4:new(NATIVE.MakeRotationMatrix(self.handle))
end
return Matrix4
|
Fixed Matrix4 class.
|
Fixed Matrix4 class.
|
Lua
|
mit
|
henry4k/konstrukt,henry4k/apoapsis,henry4k/apoapsis,henry4k/konstrukt,henry4k/apoapsis,henry4k/konstrukt
|
20c453e43c6abd8ebc9412389723875c90810daa
|
commands/assets.lua
|
commands/assets.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- 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.
--
-- @endcond
--]]
zpm.assets.commands = {}
function zpm.assets.commands.extract( repo, folder, files )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( folder, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.extractto( repo, folder, files, to )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( _MAIN_SCRIPT_DIR, to, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.download( repo, folder, url, to )
local targetDir = path.join( folder, to )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside assets folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
zpm.util.download( url, targetDir, "*" )
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- 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.
--
-- @endcond
--]]
zpm.assets.commands = {}
function zpm.assets.commands.extract( repo, folder, files )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( folder, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.extractto( repo, folder, files, to )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( os.getcwd(), to, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
print(target, path.getabsolute( targetDir ), ( os.getcwd() ))
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.download( repo, folder, url, to )
local targetDir = path.join( folder, to )
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside assets folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
zpm.util.download( url, targetDir, "*" )
end
|
Fix asset path
|
Fix asset path
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
33057ea86c8c5e0126dda480c2c2aadca6a35b3d
|
scripts/bgfx.lua
|
scripts/bgfx.lua
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
path.join(BX_DIR, "include"),
}
defines {
_defines,
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
if _OPTIONS["with-ovr"] then
defines {
-- "BGFX_CONFIG_MULTITHREADED=0",
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
configuration { "x32" }
libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/Win32/Release", _ACTION) }
configuration { "x64" }
libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/x64/Release", _ACTION) }
configuration { "x32 or x64" }
links { "libovr" }
configuration {}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "winphone8* or winstore8*" }
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "*clang*" }
buildoptions {
"-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int'
"-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension
}
configuration { "osx" }
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
"-weak_framework MetalKit",
}
configuration { "not nacl", "not linux-steamlink" }
includedirs {
--nacl has GLES2 headers modified...
--steamlink has EGL headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "linux-steamlink" }
defines {
"EGL_API_FB",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/debug_**.cpp"),
path.join(BGFX_DIR, "src/glcontext_**.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/hmd**.cpp"),
path.join(BGFX_DIR, "src/renderer_**.cpp"),
path.join(BGFX_DIR, "src/shader_**.cpp"),
path.join(BGFX_DIR, "src/topology.cpp"),
path.join(BGFX_DIR, "src/vertexdecl.cpp"),
}
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/amalgamated.mm"),
}
excludes {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration {}
else
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
configuration {}
copyLib()
end
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
path.join(BX_DIR, "include"),
}
defines {
_defines,
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
if _OPTIONS["with-ovr"] then
defines {
-- "BGFX_CONFIG_MULTITHREADED=0",
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
configuration { "x32" }
libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/Win32/Release", _ACTION) }
configuration { "x64" }
libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/x64/Release", _ACTION) }
configuration { "x32 or x64" }
links { "libovr" }
configuration {}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "winphone8* or winstore8*" }
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "*clang*" }
buildoptions {
"-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int'
"-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension
}
configuration { "osx" }
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
"-weak_framework MetalKit",
}
configuration { "not nacl", "not linux-steamlink" }
includedirs {
--nacl has GLES2 headers modified...
--steamlink has EGL headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "linux-steamlink" }
defines {
"EGL_API_FB",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/debug_**.cpp"),
path.join(BGFX_DIR, "src/glcontext_**.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/hmd**.cpp"),
path.join(BGFX_DIR, "src/renderer_**.cpp"),
path.join(BGFX_DIR, "src/shader**.cpp"),
path.join(BGFX_DIR, "src/topology.cpp"),
path.join(BGFX_DIR, "src/vertexdecl.cpp"),
}
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/amalgamated.mm"),
}
excludes {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration { "not (xcode* or osx or ios*)" }
excludes {
path.join(BGFX_DIR, "src/**.mm"),
}
configuration {}
else
configuration { "xcode* or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_**.mm"),
path.join(BGFX_DIR, "src/renderer_**.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
configuration {}
copyLib()
end
|
Fixed amalgamated build.
|
Fixed amalgamated build.
|
Lua
|
bsd-2-clause
|
attilaz/bgfx,bkaradzic/bgfx,jdryg/bgfx,jpcy/bgfx,bkaradzic/bgfx,Synxis/bgfx,septag/bgfx,fluffyfreak/bgfx,Synxis/bgfx,MikePopoloski/bgfx,jdryg/bgfx,mmicko/bgfx,bkaradzic/bgfx,mendsley/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,mmicko/bgfx,fluffyfreak/bgfx,mendsley/bgfx,mendsley/bgfx,Synxis/bgfx,jpcy/bgfx,septag/bgfx,LWJGL-CI/bgfx,emoon/bgfx,fluffyfreak/bgfx,jdryg/bgfx,jpcy/bgfx,jpcy/bgfx,MikePopoloski/bgfx,attilaz/bgfx,jdryg/bgfx,emoon/bgfx,attilaz/bgfx,mmicko/bgfx,emoon/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,septag/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx
|
c758d294edf922ada25fcb73e967b978b90852dd
|
scripts/bgfx.lua
|
scripts/bgfx.lua
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "../bx/include"),
}
defines {
_defines,
}
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
if (_OPTIONS["vs"] == "vs2012-xp")
or (_OPTIONS["vs"] == "vs2013-xp") then
configuration { "vs201*" }
includedirs {
"$(DXSDK_DIR)/include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "mingw* or vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "xcode4 or osx or ios*" }
files {
path.join(BGFX_DIR, "src/**.mm"),
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
excludes {
path.join(BGFX_DIR, "src/**.bin.h"),
}
configuration {}
copyLib()
end
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "../bx/include"),
}
defines {
_defines,
}
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
if (_OPTIONS["vs"] == "vs2012-xp")
or (_OPTIONS["vs"] == "vs2013-xp") then
configuration { "vs201*" }
includedirs {
"$(DXSDK_DIR)/include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "mingw* or vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "xcode4 or osx or ios*" }
files {
path.join(BGFX_DIR, "src/**.mm"),
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
excludes {
path.join(BGFX_DIR, "src/**.bin.h"),
}
configuration {}
copyLib()
end
|
Linux: fixed building of shared libraries
|
Linux: fixed building of shared libraries
|
Lua
|
bsd-2-clause
|
emoon/bgfx,janstk/bgfx,mmicko/bgfx,mcanthony/bgfx,marco-we/bgfx,fluffyfreak/bgfx,BlueCrystalLabs/bgfx,0-wiz-0/bgfx,janstk/bgfx,v3n/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,bkaradzic/bgfx,BlueCrystalLabs/bgfx,elmindreda/bgfx,ming4883/bgfx,mcanthony/bgfx,attilaz/bgfx,ocornut/bgfx,ktotheoz/bgfx,fluffyfreak/bgfx,emoon/bgfx,sergeScherbakov/bgfx,septag/bgfx,mmicko/bgfx,mendsley/bgfx,MikePopoloski/bgfx,Vertexwahn/bgfx,0-wiz-0/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,LWJGL-CI/bgfx,0-wiz-0/bgfx,jdryg/bgfx,fluffyfreak/bgfx,kondrak/bgfx,ocornut/bgfx,septag/bgfx,jpcy/bgfx,aonorin/bgfx,elmindreda/bgfx,marco-we/bgfx,cuavas/bgfx,v3n/bgfx,MikePopoloski/bgfx,Vertexwahn/bgfx,aonorin/bgfx,marco-we/bgfx,Extrawurst/bgfx,attilaz/bgfx,cuavas/bgfx,bkaradzic/bgfx,darkimage/bgfx,ocornut/bgfx,fluffyfreak/bgfx,ktotheoz/bgfx,septag/bgfx,aonorin/bgfx,jpcy/bgfx,BlueCrystalLabs/bgfx,LSBOSS/bgfx,Vertexwahn/bgfx,janstk/bgfx,andr3wmac/bgfx,bkaradzic/bgfx,Synxis/bgfx,jdryg/bgfx,LWJGL-CI/bgfx,ming4883/bgfx,emoon/bgfx,jpcy/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,ming4883/bgfx,LWJGL-CI/bgfx,mendsley/bgfx,kondrak/bgfx,mendsley/bgfx,v3n/bgfx,cuavas/bgfx,MikePopoloski/bgfx,sergeScherbakov/bgfx,mmicko/bgfx,elmindreda/bgfx,sergeScherbakov/bgfx,Synxis/bgfx,attilaz/bgfx,LSBOSS/bgfx,mcanthony/bgfx,Synxis/bgfx,kondrak/bgfx,cyndis/bgfx,darkimage/bgfx,LSBOSS/bgfx,jdryg/bgfx,darkimage/bgfx,jdryg/bgfx,ktotheoz/bgfx,cyndis/bgfx,cyndis/bgfx,jpcy/bgfx
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.