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
1f945a7a896bd26e22a731984675eada36b9d861
AudioData.lua
AudioData.lua
--Retrieves audio datasets. Currently retrieves the AN4 dataset by giving the folder directory. require 'lfs' require 'audio' cutorch = require 'cutorch' require 'xlua' local AudioData = {} local alphabet = { '$', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ' } local alphabetMapping = {} local indexMapping = {} for index, character in ipairs(alphabet) do alphabetMapping[character] = index - 1 indexMapping[index - 1] = character end --Given an index returns the letter at that index. function AudioData.findLetter(index) return indexMapping[index] end function AudioData.retrieveAN4TrainingDataSet(folderDirPath, windowSize, stride) local audioLocationPath = folderDirPath .. "/etc/an4_train.fileids" local transcriptPath = folderDirPath .. "/etc/an4_train.transcription" local nbSamples = 948 -- Amount of samples found in the AN4 training set. local targets = {} for line in io.lines(transcriptPath) do local label = {} for string in string.gmatch(line, ">([^<]*)<") do --This line removes the space at the beginning and end of the sentence input. string = string:sub(2):sub(1, -2) for i = 1, #string do local character = string:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(targets, label) end end local dataSet = an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbSamples) return dataSet end function AudioData.retrieveAN4TestDataSet(folderDirPath, windowSize, stride) local audioLocationPath = folderDirPath .. "/etc/an4_test.fileids" local transcriptPath = folderDirPath .. "/etc/an4_test.transcription" local nbSamples = 130 -- Amount of samples found in the AN4 test set. local targets = {} local transcripts = {} -- For verification of words, we return the lines of the test data. for line in io.lines(transcriptPath) do local label = {} local line = line:gsub('%b()', '') --Remove the space at the end of the line. line = line:sub(1, -2) for i = 1, #line do local character = line:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(targets, label) table.insert(transcripts, string.lower(line)) end local dataSet = an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbSamples) return dataSet, transcripts end --Used by the Seq2Seq model. Retrieves both the test and training transcripts for AN4. function AudioData.retrieveAN4TranscriptSet(folderDirPath) local transcriptPathTrain = folderDirPath .. "/etc/an4_train.transcription" local transcriptPathTest = folderDirPath .. "/etc/an4_test.transcription" local trainingTranscripts = {} local testTranscripts = {} local function convertToLabel(transcripts, line) local label = {} local string = line:gsub('%b()', '') --Remove the space at the end of the line. string = string:sub(1, -2) for i = 1, #string do local character = string:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(transcripts, label) end for line in io.lines(transcriptPathTrain) do convertToLabel(trainingTranscripts, line) end for line in io.lines(transcriptPathTest) do convertToLabel(testTranscripts, line) end return trainingTranscripts end function an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbOfSamples) local inputs = {} local counter = 0 for audioPath in io.lines(audioLocationPath) do counter = counter + 1 local audioData = audio.load(folderDirPath .. "/wav/" .. audioPath .. ".wav") -- We transpose the frequency/time to now put time on the x axis, frequency on the y axis. local spectrogram = audio.spectrogram(audioData, windowSize, 'hamming', stride):transpose(1, 2) table.insert(inputs, spectrogram) xlua.progress(counter,nbOfSamples) end local dataset = createDataSet(inputs, targets) return dataset end function createDataSet(inputs, targets) local dataset = {} for i = 1, #inputs do --Wrap the targets into a table (batches would go into the table, but no batching supported). --Convert the tensor into a cuda tensor for gpu calculations. table.insert(dataset, {inputs[i]:cuda(), {targets[i]}}) end local pointer = 1 function dataset:size() return #dataset end function dataset:nextData() local sample = dataset[pointer] pointer = pointer + 1 if (pointer > dataset:size()) then pointer = 1 end return sample[1], sample[2] end return dataset end return AudioData
--Retrieves audio datasets. Currently retrieves the AN4 dataset by giving the folder directory. require 'lfs' require 'audio' cutorch = require 'cutorch' require 'xlua' local AudioData = {} local alphabet = { '$', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ' } local alphabetMapping = {} local indexMapping = {} for index, character in ipairs(alphabet) do alphabetMapping[character] = index - 1 indexMapping[index - 1] = character end --Given an index returns the letter at that index. function AudioData.findLetter(index) return indexMapping[index] end function AudioData.retrieveAN4TrainingDataSet(folderDirPath, windowSize, stride) local audioLocationPath = folderDirPath .. "/etc/an4_train.fileids" local transcriptPath = folderDirPath .. "/etc/an4_train.transcription" local nbSamples = 948 -- Amount of samples found in the AN4 training set. local targets = {} for line in io.lines(transcriptPath) do local label = {} line = string.lower(line) for string in string.gmatch(line, ">([^<]*)<") do --This line removes the space at the beginning and end of the sentence input. string = string:sub(2):sub(1, -2) for i = 1, #string do local character = string:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(targets, label) end end local dataSet = an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbSamples) return dataSet end function AudioData.retrieveAN4TestDataSet(folderDirPath, windowSize, stride) local audioLocationPath = folderDirPath .. "/etc/an4_test.fileids" local transcriptPath = folderDirPath .. "/etc/an4_test.transcription" local nbSamples = 130 -- Amount of samples found in the AN4 test set. local targets = {} local transcripts = {} -- For verification of words, we return the lines of the test data. for line in io.lines(transcriptPath) do local label = {} line = string.lower(line) local line = line:gsub('%b()', '') --Remove the space at the end of the line. line = line:sub(1, -2) for i = 1, #line do local character = line:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(targets, label) table.insert(transcripts, line) end local dataSet = an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbSamples) return dataSet, transcripts end --Used by the Seq2Seq model. Retrieves both the test and training transcripts for AN4. function AudioData.retrieveAN4TranscriptSet(folderDirPath) local transcriptPathTrain = folderDirPath .. "/etc/an4_train.transcription" local transcriptPathTest = folderDirPath .. "/etc/an4_test.transcription" local trainingTranscripts = {} local testTranscripts = {} local function convertToLabel(transcripts, line) local label = {} local string = line:gsub('%b()', '') --Remove the space at the end of the line. string = string:sub(1, -2) for i = 1, #string do local character = string:sub(i, i) table.insert(label, alphabetMapping[character]) end table.insert(transcripts, label) end for line in io.lines(transcriptPathTrain) do convertToLabel(trainingTranscripts, line) end for line in io.lines(transcriptPathTest) do convertToLabel(testTranscripts, line) end return trainingTranscripts end function an4Dataset(folderDirPath, audioLocationPath, windowSize, stride, targets, nbOfSamples) local inputs = {} local counter = 0 for audioPath in io.lines(audioLocationPath) do counter = counter + 1 local audioData = audio.load(folderDirPath .. "/wav/" .. audioPath .. ".wav") -- We transpose the frequency/time to now put time on the x axis, frequency on the y axis. local spectrogram = audio.spectrogram(audioData, windowSize, 'hamming', stride):transpose(1, 2) table.insert(inputs, spectrogram) xlua.progress(counter,nbOfSamples) end local dataset = createDataSet(inputs, targets) return dataset end function createDataSet(inputs, targets) local dataset = {} for i = 1, #inputs do --Wrap the targets into a table (batches would go into the table, but no batching supported). --Convert the tensor into a cuda tensor for gpu calculations. table.insert(dataset, {inputs[i]:cuda(), {targets[i]}}) end local pointer = 1 function dataset:size() return #dataset end function dataset:nextData() local sample = dataset[pointer] pointer = pointer + 1 if (pointer > dataset:size()) then pointer = 1 end return sample[1], sample[2] end return dataset end return AudioData
fixed lower case issue
fixed lower case issue
Lua
mit
zhirongw/Speech,SeanNaren/CTCSpeechRecognition
17ecd85bccce95eb857890f1eaa91534040d74b5
lib/resty/kafka/client.lua
lib/resty/kafka/client.lua
-- Copyright (C) Dejiang Zhu(doujiang24) local broker = require "resty.kafka.broker" local request = require "resty.kafka.request" local setmetatable = setmetatable local timer_at = ngx.timer.at local ngx_log = ngx.log local ERR = ngx.ERR local pid = ngx.worker.pid local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 4) _M._VERSION = '0.01' local mt = { __index = _M } local function metadata_encode(self, topics) local client_id = self.client_id local id = 0 -- hard code correlation_id local req = request:new(request.MetadataRequest, id, client_id) local num = #topics req:int32(num) for i = 1, num do req:string(topics[i]) end return req end local function metadata_decode(resp) local bk_num = resp:int32() local brokers = new_tab(0, bk_num) for i = 1, bk_num do local nodeid = resp:int32(); brokers[nodeid] = { host = resp:string(), port = resp:int32(), } end local topic_num = resp:int32() local topics = new_tab(0, topic_num) for i = 1, topic_num do local tp_errcode = resp:int16() local topic = resp:string() local partition_num = resp:int32() local topic_info = { partitions = new_tab(partition_num, 0), errcode = tp_errcode, num = partition_num, } for j = 1, partition_num do local partition_info = new_tab(0, 5) partition_info.errcode = resp:int16() partition_info.id = resp:int32() partition_info.leader = resp:int32() local repl_num = resp:int32() local replicas = new_tab(repl_num, 0) for m = 1, repl_num do replicas[m] = resp:int32() end partition_info.replicas = replicas local isr_num = resp:int32() local isr = new_tab(isr_num, 0) for m = 1, isr_num do isr[m] = resp:int32() end partition_info.isr = isr topic_info.partitions[j] = partition_info end topics[topic] = topic_info end return brokers, topics end local function _fetch_metadata(self) local broker_list = self.broker_list local topics = self.topics local sc = self.socket_config local req = metadata_encode(self, topics) for i = 1, #broker_list do local host, port = broker_list[i].host, broker_list[i].port local bk = broker:new(host, port, sc) local resp, err = bk:send_receive(req) if not resp then ngx_log(ERR, "broker metadata failed, err:", err, host, port) else local brokers, topic_partitions = metadata_decode(resp) self.broker_nodes, self.topic_partitions = brokers, topic_partitions return brokers, topic_partitions end end ngx_log(ERR, "refresh metadata failed") return nil, "refresh metadata failed" end _M.refresh = _fetch_metadata local function meta_refresh(premature, self, interval) if premature then return end if #self.topics > 0 then _fetch_metadata(self) end local ok, err = timer_at(interval, meta_refresh, self, interval) if not ok then ngx_log(ERR, "failed to create timer at meta_refresh, err: ", err) end end function _M.new(self, broker_list, client_config) local opts = client_config or {} local socket_config = { socket_timeout = opts.socket_timeout or 3000, keepalive_timeout = opts.keepalive_timeout or 600 * 1000, -- 10 min keepalive_size = opts.keepalive_size or 2, } local cli = setmetatable({ broker_list = broker_list, topic_partitions = {}, broker_nodes = {}, topics = {}, client_id = "worker:" .. pid(), socket_config = socket_config, }, mt) if opts.refresh_interval then meta_refresh(nil, cli, opts.refresh_interval / 1000) -- in ms end return cli end function _M.fetch_metadata(self, topic) if not topic then return self.broker_nodes, self.topic_partitions end local partitions = self.topic_partitions[topic] if partitions then if partitions.num and partitions.num > 0 then return self.broker_nodes, partitions end else self.topics[#self.topics + 1] = topic end _fetch_metadata(self) local partitions = self.topic_partitions[topic] if partitions and partitions.num and partitions.num > 0 then return self.broker_nodes, partitions end return nil, "not found topic" end return _M
-- Copyright (C) Dejiang Zhu(doujiang24) local broker = require "resty.kafka.broker" local request = require "resty.kafka.request" local setmetatable = setmetatable local timer_at = ngx.timer.at local ngx_log = ngx.log local ERR = ngx.ERR local INFO = ngx.INFO local pid = ngx.worker.pid local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 4) _M._VERSION = '0.01' local mt = { __index = _M } local function metadata_encode(self, topics) local client_id = self.client_id local id = 0 -- hard code correlation_id local req = request:new(request.MetadataRequest, id, client_id) local num = #topics req:int32(num) for i = 1, num do req:string(topics[i]) end return req end local function metadata_decode(resp) local bk_num = resp:int32() local brokers = new_tab(0, bk_num) for i = 1, bk_num do local nodeid = resp:int32(); brokers[nodeid] = { host = resp:string(), port = resp:int32(), } end local topic_num = resp:int32() local topics = new_tab(0, topic_num) for i = 1, topic_num do local tp_errcode = resp:int16() local topic = resp:string() local partition_num = resp:int32() local topic_info = { partitions = new_tab(partition_num, 0), errcode = tp_errcode, num = partition_num, } for j = 1, partition_num do local partition_info = new_tab(0, 5) partition_info.errcode = resp:int16() partition_info.id = resp:int32() partition_info.leader = resp:int32() local repl_num = resp:int32() local replicas = new_tab(repl_num, 0) for m = 1, repl_num do replicas[m] = resp:int32() end partition_info.replicas = replicas local isr_num = resp:int32() local isr = new_tab(isr_num, 0) for m = 1, isr_num do isr[m] = resp:int32() end partition_info.isr = isr topic_info.partitions[j] = partition_info end topics[topic] = topic_info end return brokers, topics end local function _fetch_metadata(self) local broker_list = self.broker_list local topics = self.topics local sc = self.socket_config local req = metadata_encode(self, topics) for i = 1, #broker_list do local host, port = broker_list[i].host, broker_list[i].port local bk = broker:new(host, port, sc) local resp, err = bk:send_receive(req) if not resp then ngx_log(INFO, "broker fetch metadata failed, err:", err, host, port) else local brokers, topic_partitions = metadata_decode(resp) self.broker_nodes, self.topic_partitions = brokers, topic_partitions return brokers, topic_partitions end end ngx_log(ERR, "refresh metadata failed") return nil, "refresh metadata failed" end _M.refresh = _fetch_metadata local function meta_refresh(premature, self, interval) if premature then return end if #self.topics > 0 then _fetch_metadata(self) end local ok, err = timer_at(interval, meta_refresh, self, interval) if not ok then ngx_log(ERR, "failed to create timer at meta_refresh, err: ", err) end end function _M.new(self, broker_list, client_config) local opts = client_config or {} local socket_config = { socket_timeout = opts.socket_timeout or 3000, keepalive_timeout = opts.keepalive_timeout or 600 * 1000, -- 10 min keepalive_size = opts.keepalive_size or 2, } local cli = setmetatable({ broker_list = broker_list, topic_partitions = {}, broker_nodes = {}, topics = {}, client_id = "worker:" .. pid(), socket_config = socket_config, }, mt) if opts.refresh_interval then meta_refresh(nil, cli, opts.refresh_interval / 1000) -- in ms end return cli end function _M.fetch_metadata(self, topic) if not topic then return self.broker_nodes, self.topic_partitions end local partitions = self.topic_partitions[topic] if partitions then if partitions.num and partitions.num > 0 then return self.broker_nodes, partitions end else self.topics[#self.topics + 1] = topic end _fetch_metadata(self) local partitions = self.topic_partitions[topic] if partitions and partitions.num and partitions.num > 0 then return self.broker_nodes, partitions end return nil, "not found topic" end return _M
bugfix: turn some verbose error log from ERR to INFO
bugfix: turn some verbose error log from ERR to INFO
Lua
bsd-3-clause
doujiang24/lua-resty-kafka,wzb56/lua-resty-kafka,wangfakang/lua-resty-kafka
c9355bf7dc8c07453b63e5e63f21c52fa7452897
lua/plugins/completion.lua
lua/plugins/completion.lua
local nvim = require'nvim' local load_module = require'tools'.helpers.load_module local has_attrs = require'tools'.tables.has_attrs local plugins = nvim.plugins local nvim_set_autocmd = nvim.nvim_set_autocmd local completion = load_module'completion' local lsp = require 'plugins/lsp' local treesitter = require 'plugins/treesitter' if completion ~= nil then if plugins.ultisnips then nvim.g.completion_enable_snippet = 'UltiSnips' end nvim.g.completion_matching_strategy_list = { 'exact', 'fuzzy', 'substring', } nvim.g.completion_matching_ignore_case = 1 nvim.g.completion_matching_smart_case = 1 nvim.g.completion_confirm_key = '' nvim.g.completion_sorting = 'none' nvim.g.completion_trigger_on_delete = 1 nvim.g.completion_auto_change_source = 1 nvim.g.completion_enable_auto_signature = 0 nvim.g.completion_enable_auto_hover = 0 nvim.g.completion_enable_auto_paren = 1 -- local spell_check = {'gitcommit', 'markdown', 'tex', 'text', 'plaintext'} local completion_chain = { default = { default = { {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'} }, -- func = {} -- string = {} -- comment = {}, }, } local items = { complete_items = {} } -- if lsp then -- items.complete_items[#items.complete_items + 1] = 'lsp' -- end -- if treesitter then -- items.complete_items[#items.complete_items + 1] = 'ts' -- end if nvim.g.completion_enable_snippet then items.complete_items[#items.complete_items + 1] = 'snippet' end if #items.complete_items > 0 then table.insert(completion_chain.default.default, 1, items) end if lsp then for _,language in pairs(lsp) do if completion_chain[language] == nil then completion_chain[language] = { default = { {complete_items = {'lsp', 'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } if language == 'vim' then table.insert(completion_chain[language].default, 3, {mode = 'cmd'}) -- elseif spell_check[language] ~= nil then -- table.insert(completion_chain[language].default, 3, {mode = 'spel'}) end end end end if treesitter and plugins['completion-treesitter'] ~= nil then for _,language in pairs(treesitter) do if completion_chain[language] == nil then completion_chain[language] = { default = { {complete_items = {'ts', 'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } end -- if spell_check[language] ~= nil then -- table.insert(completion_chain[language].default, 3, {mode = 'spel'}) -- end end end if completion_chain.vim == nil then completion_chain.vim = { default = { {complete_items = {'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = 'cmd'}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } end -- for _,language in pairs(spell_check) do -- if completion_chain[language] == nil then -- completion_chain[language] = { -- default = { -- {complete_items = { 'path' }, triggered_only = {'/'}}, -- {mode = 'spel'}, -- {mode = '<c-p>'}, -- {mode = '<c-n>'}, -- } -- } -- end -- end nvim.g.completion_chain_complete_list = completion_chain nvim_set_autocmd{ event = 'BufEnter', pattern = '*', cmd = [[lua require'completion'.on_attach()]], group = 'Completion', } -- TODO: Create Pull request to use buffer-variables nvim_set_autocmd{ event = 'BufEnter', pattern = '*', cmd = [[ let g:completion_trigger_character = ['.'] ]], group = 'Completion', } if has_attrs(lsp, 'cpp') or has_attrs(treesitter, 'cpp') then nvim_set_autocmd{ event = 'BufEnter', pattern = {'*.cpp', '*.hpp', '*.cc', '*.cxx'}, cmd = [[ let g:completion_trigger_character = ['.', '::', '->'] ]], group = 'Completion', } end if has_attrs(lsp, 'lua') or has_attrs(treesitter, 'lua') then nvim_set_autocmd{ event = 'BufEnter', pattern = {'*.lua'}, cmd = [[ let g:completion_trigger_character = ['.', ':'] ]], group = 'Completion', } end elseif lsp and plugins['vim-mucomplete'] ~= nil then nvim_set_autocmd{ event = 'FileType', pattern = lsp, cmd = [[call plugins#vim_mucomplete#setOmni()]], group = 'Completion', } return false end return true
local nvim = require'nvim' local load_module = require'tools'.helpers.load_module local has_attrs = require'tools'.tables.has_attrs local plugins = nvim.plugins local nvim_set_autocmd = nvim.nvim_set_autocmd local completion = load_module'completion' local lsp = require 'plugins/lsp' local treesitter = require 'plugins/treesitter' if completion ~= nil then if plugins.ultisnips then nvim.g.completion_enable_snippet = 'UltiSnips' end nvim.g.completion_matching_strategy_list = { 'exact', 'fuzzy', 'substring', } nvim.g.completion_matching_ignore_case = 1 nvim.g.completion_matching_smart_case = 1 nvim.g.completion_confirm_key = '' -- nvim.g.completion_sorting = 'alphabet' -- 'none' -- 'length' nvim.g.completion_trigger_on_delete = 1 nvim.g.completion_auto_change_source = 1 nvim.g.completion_enable_auto_signature = 0 nvim.g.completion_enable_auto_hover = 0 nvim.g.completion_enable_auto_paren = 1 -- local spell_check = {'gitcommit', 'markdown', 'tex', 'text', 'plaintext'} local completion_chain = { default = { default = { {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'} }, -- func = {} -- string = {} -- comment = {}, }, } local items = { complete_items = {} } -- if lsp then -- items.complete_items[#items.complete_items + 1] = 'lsp' -- end -- if treesitter then -- items.complete_items[#items.complete_items + 1] = 'ts' -- end if nvim.g.completion_enable_snippet then items.complete_items[#items.complete_items + 1] = 'snippet' end if #items.complete_items > 0 then table.insert(completion_chain.default.default, 1, items) end if lsp then for _,language in pairs(lsp) do if completion_chain[language] == nil then completion_chain[language] = { default = { {complete_items = {'lsp', 'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } if language == 'vim' then table.insert(completion_chain[language].default, 3, {mode = 'cmd'}) -- elseif spell_check[language] ~= nil then -- table.insert(completion_chain[language].default, 3, {mode = 'spel'}) end end end end if treesitter and plugins['completion-treesitter'] ~= nil then for _,language in pairs(treesitter) do if completion_chain[language] == nil then completion_chain[language] = { default = { {complete_items = {'ts', 'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } end -- if spell_check[language] ~= nil then -- table.insert(completion_chain[language].default, 3, {mode = 'spel'}) -- end end end if completion_chain.vim == nil then completion_chain.vim = { default = { {complete_items = {'snippet'}}, {complete_items = { 'path' }, triggered_only = {'/'}}, {mode = 'cmd'}, {mode = '<c-p>'}, {mode = '<c-n>'}, } } end -- for _,language in pairs(spell_check) do -- if completion_chain[language] == nil then -- completion_chain[language] = { -- default = { -- {complete_items = { 'path' }, triggered_only = {'/'}}, -- {mode = 'spel'}, -- {mode = '<c-p>'}, -- {mode = '<c-n>'}, -- } -- } -- end -- end nvim.g.completion_chain_complete_list = completion_chain nvim_set_autocmd{ event = 'BufEnter', pattern = '*', cmd = [[lua require'completion'.on_attach()]], group = 'Completion', } -- TODO: Create Pull request to use buffer-variables nvim_set_autocmd{ event = 'BufEnter', pattern = '*', cmd = [[ let g:completion_trigger_character = ['.'] ]], group = 'Completion', } if has_attrs(lsp, 'cpp') or has_attrs(treesitter, 'cpp') then nvim_set_autocmd{ event = 'BufEnter', pattern = {'*.cpp', '*.hpp', '*.cc', '*.cxx'}, cmd = [[ let g:completion_trigger_character = ['.', '::', '->'] ]], group = 'Completion', } end if has_attrs(lsp, 'lua') or has_attrs(treesitter, 'lua') then nvim_set_autocmd{ event = 'BufEnter', pattern = {'*.lua'}, cmd = [[ let g:completion_trigger_character = ['.', ':'] ]], group = 'Completion', } end elseif lsp and plugins['vim-mucomplete'] ~= nil then nvim_set_autocmd{ event = 'FileType', pattern = lsp, cmd = [[call plugins#vim_mucomplete#setOmni()]], group = 'Completion', } return false end return true
fix: revert to default completion-nvim sorting
fix: revert to default completion-nvim sorting
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
22fdca3b92743ca2e764ed364a2fe7334f069c32
mod_auth_joomla/mod_auth_joomla.lua
mod_auth_joomla/mod_auth_joomla.lua
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `jos_users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `jos_users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local prefix = params and params.prefix or "jos_"; local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `"..prefix.."users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `"..prefix.."users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
a9c12b9b498f23bf349320f0bf0224d27e76c0d9
levent/socket.lua
levent/socket.lua
--[[ -- author: xjdrew -- date: 2014-07-17 --]] local c = require "levent.socket.c" local errno = require "levent.errno.c" local class = require "levent.class" local hub = require "levent.hub" local timeout = require "levent.timeout" local closed_socket = setmetatable({}, {__index = function(t, key) if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then return function(...) return nil, errno.EBADF end end end}) local function _wait(watcher, sec) local t if sec and sec > 0 then t = timeout.start_new(sec) end local ok, excepiton = pcall(hub.wait, hub, watcher) if t then t:cancel() end return ok, excepiton end local Socket = class("Socket") function Socket:_init(cobj) assert(type(cobj.fileno) == "function", cobj) self.cobj = cobj self.cobj:setblocking(false) local loop = hub.loop self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ) self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE) -- timeout self.timeout = nil end function Socket:setblocking(flag) if flag then self.timeout = nil else self.timeout = 0.0 end end function Socket:set_timeout(sec) self.timeout = sec end function Socket:get_timeout() return self.timeout end function Socket:bind(ip, port) self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1) local ok, code = self.cobj:bind(ip, port) if not ok then return false, errno.strerror(code) end return true end function Socket:listen(backlog) local ok, code = self.cobj:listen(backlog) if not ok then return false, errno.strerror(code) end return true end function Socket:_need_block(err) if self.timeout == 0 then return false end if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then return false end return true end function Socket:accept() local csock, err while true do csock, err = self.cobj:accept() if csock then break end if not self:_need_block(err) then return nil, errno.strerror(err) end local ok, exception = _wait(self._read_event, self.timeout) if not ok then return nil, exception end end return Socket.new(csock) end function Socket:_recv(func, ...) while true do local data, err = func(self.cobj, ...) if data then return data end if not self:_need_block(err) then return nil, err end local ok, exception = _wait(self._read_event, self.timeout) if not ok then return nil, exception end end end -- args:len function Socket:recvfrom(len) return self:_recv(self.cobj.recvfrom, len) end -- args: len function Socket:recv(len) return self:_recv(self.cobj.recv, len) end function Socket:_send(func, ...) while true do local nwrite, err = func(self.cobj, ...) if nwrite then return nwrite end if not self:_need_block(err) then return nil, err end local ok, exception = _wait(self._write_event, self.timeout) if not ok then return nil, exception end end end -- args: data, from -- from: count from 0 function Socket:send(data, from) return self:_send(self.cobj.send, data, from) end -- args: function Socket:sendto(ip, port, data, from) return self:_send(self.cobj.sendto, ip, port, data, from) end -- from: count from 0 function Socket:sendall(data, from) local from = from or 0 local total = #data - from local sent = 0 while sent < total do local nwrite, err = self:send(data, from + sent) if not nwrite then return sent, err end sent = sent + nwrite end return sent end function Socket:connect(ip, port) while true do local ok, err = self.cobj:connect(ip, port) if ok then return ok end if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK) then return ok, err end return _wait(self._write_event, self.timeout) end end function Socket:fileno() return self.cobj:fileno() end function Socket:getpeername() return self.cobj:getpeername() end function Socket:getsockname() return self.cobj:getsockname() end function Socket:getsockopt(level, optname, buflen) return self.cobj:getsockopt(level, optname, buflen) end function Socket:setsockopt(level, optname, value) return self.cobj:setsockopt(level, optname, value) end function Socket:close() if self.cobj ~= closed_socket then hub:cancel_wait(self._read_event) hub:cancel_wait(self._write_event) self.cobj:close() self.cobj = closed_socket end end local socket = {} function socket.socket(family, _type, protocol) local cobj, err = c.socket(family, _type, protocol) if not cobj then return nil, errno.strerror(err) end return Socket.new(cobj) end return setmetatable(socket, {__index = c} )
--[[ -- author: xjdrew -- date: 2014-07-17 --]] local c = require "levent.socket.c" local errno = require "levent.errno.c" local class = require "levent.class" local hub = require "levent.hub" local timeout = require "levent.timeout" local closed_socket = setmetatable({}, {__index = function(t, key) if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then return function(...) return nil, errno.EBADF end end end}) local function _wait(watcher, sec) local t if sec and sec > 0 then t = timeout.start_new(sec) end local ok, excepiton = pcall(hub.wait, hub, watcher) if t then t:cancel() end return ok, excepiton end local Socket = class("Socket") function Socket:_init(cobj) assert(type(cobj.fileno) == "function", cobj) self.cobj = cobj self.cobj:setblocking(false) local loop = hub.loop self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ) self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE) -- timeout self.timeout = nil end function Socket:setblocking(flag) if flag then self.timeout = nil else self.timeout = 0.0 end end function Socket:set_timeout(sec) self.timeout = sec end function Socket:get_timeout() return self.timeout end function Socket:bind(ip, port) self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1) local ok, code = self.cobj:bind(ip, port) if not ok then return false, errno.strerror(code) end return true end function Socket:listen(backlog) local ok, code = self.cobj:listen(backlog) if not ok then return false, errno.strerror(code) end return true end function Socket:_need_block(err) if self.timeout == 0 then return false end if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then return false end return true end function Socket:accept() local csock, err while true do csock, err = self.cobj:accept() if csock then break end if not self:_need_block(err) then return nil, errno.strerror(err) end local ok, exception = _wait(self._read_event, self.timeout) if not ok then return nil, exception end end return Socket.new(csock) end function Socket:_recv(func, ...) while true do local data, err = func(self.cobj, ...) if data then return data end if not self:_need_block(err) then return nil, err end local ok, exception = _wait(self._read_event, self.timeout) if not ok then return nil, exception end end end -- args:len function Socket:recvfrom(len) return self:_recv(self.cobj.recvfrom, len) end -- args: len function Socket:recv(len) return self:_recv(self.cobj.recv, len) end function Socket:_send(func, ...) while true do local nwrite, err = func(self.cobj, ...) if nwrite then return nwrite end if not self:_need_block(err) then return nil, err end local ok, exception = _wait(self._write_event, self.timeout) if not ok then return nil, exception end end end -- args: data, from -- from: count from 0 function Socket:send(data, from) return self:_send(self.cobj.send, data, from) end -- args: function Socket:sendto(ip, port, data, from) return self:_send(self.cobj.sendto, ip, port, data, from) end -- from: count from 0 function Socket:sendall(data, from) local from = from or 0 local total = #data - from local sent = 0 while sent < total do local nwrite, err = self:send(data, from + sent) if not nwrite then return sent, err end sent = sent + nwrite end return sent end function Socket:connect(ip, port) while true do local ok, err = self.cobj:connect(ip, port) if ok then return ok end if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK) then return ok, err end local ok, exception = _wait(self._write_event, self.timeout) if not ok then return nil, exception end end end function Socket:fileno() return self.cobj:fileno() end function Socket:getpeername() return self.cobj:getpeername() end function Socket:getsockname() return self.cobj:getsockname() end function Socket:getsockopt(level, optname, buflen) return self.cobj:getsockopt(level, optname, buflen) end function Socket:setsockopt(level, optname, value) return self.cobj:setsockopt(level, optname, value) end function Socket:close() if self.cobj ~= closed_socket then hub:cancel_wait(self._read_event) hub:cancel_wait(self._write_event) self.cobj:close() self.cobj = closed_socket end end local socket = {} function socket.socket(family, _type, protocol) local cobj, err = c.socket(family, _type, protocol) if not cobj then return nil, errno.strerror(err) end return Socket.new(cobj) end return setmetatable(socket, {__index = c} )
bugfix: connect failed
bugfix: connect failed
Lua
mit
xjdrew/levent
e02fc7f3e4d7cffe47127acd30d68e606194d37e
util.lua
util.lua
local util = {} local cjson = require 'cjson' local io_open , io_popen = io.open , io.popen local os_date = os.date local ffi = require 'ffi' ffi.cdef[[ unsigned int sleep(unsigned int seconds); ]] function util.sleep(sec) ffi.C.sleep(sec) end function util.getHostName() local v = io_popen("hostname") local result = v:lines()() v:close() return result end function util.getFileAndInode(task , timestamp) local path = task.path if task.logNameSuffix then path = task.path .. os_date(task.logNameSuffix , timestamp) end local file = io_open(path , "r") local inode = nil if file then local tmp = io_popen("ls -i " .. path) inode = tmp:lines()() tmp:close() end return file , inode end function util.checkFileRolling(task , file , inode , timestamp) local rolling = false if file == nil then file , inode = util.getFileAndInode(task , timestamp) rolling = true else local t_file , t_inode = util.getFileAndInode(task , timestamp) if inode == t_inode then t_file:close() else file:close() file , inode , rolling = t_file , t_inode , true end end return rolling , file , inode end function util.mergeMapTables(tbs) local container = {} for _ , tb in ipairs(tbs) do for key , value in pairs(tb) do container[key] = value end end return container end function util.mergeMapTables2Left(left , right) for key , value in pairs(right) do left[key] = value end end function util.parseData(msg , rule , container) local handled , parseResult = false , {msg:match(rule.regex)} for index , value in ipairs(parseResult) do local cf = rule.conversion[index] container[rule.mapping[index]] = (cf and cf(value) or value) handled = true end return handled end function util.grok(rule) rule.mapping = {} local escapes = { ['%.'] = '%%.' , ['%%'] = '%%%' , ['%['] = '%%[' , ['%]'] = '%%]' , ['%('] = '%%(' , ['%)'] = '%%)' , ['%+'] = '%%+' , ['%*'] = '%%*' , ['%-'] = '%%-' , ['%?'] = '%%?' , ['%^'] = '%%^' , } for k , v in pairs(escapes) do rule.grok = string.gsub(rule.grok , k , v) end local t_grokstr , cts = string.gsub(rule.grok , '%$([%a|_]+)%$([%a|_]+)' , function(l , f) return '$' .. l .. '_' .. f end) while cts > 0 do t_grokstr , cts = string.gsub(t_grokstr , '%$([%a|_]+)%$([%a|_]+)' , function(l , f) return '$' .. l .. '_' .. f end) end local _ , count = string.gsub(t_grokstr , '%$([%a|_]+)' , '(.-)') local index = 0 rule.regex = string.gsub(t_grokstr , '%$([%a|_]+)' , function(w) table.insert(rule.mapping , w) index = index + 1 return (index == count and '(.*)' or '(.-)') end) end function util.grokP(rule) local total_len , pos = string.len(rule.regex) , 0 local posSeq = {} while total_len - pos > 4 do pos = string.find(rule.regex , '%(%.%-%)' , pos) if pos then pos = pos + 4 table.insert(posSeq , pos) else pos = total_len end end local index = 1 local result = string.gsub(rule.regex , '%(%.%-%)' , function(w) local sp = string.sub(rule.regex , posSeq[index] , posSeq[index]) sp = '([^' .. sp .. ']*)' index = index + 1 return sp end) rule.regex = result end return util
local util = {} local cjson = require 'cjson' local io_open , io_popen = io.open , io.popen local os_date = os.date local ffi = require 'ffi' ffi.cdef[[ unsigned int sleep(unsigned int seconds); ]] function util.sleep(sec) ffi.C.sleep(sec) end function util.getHostName() local v = io_popen("hostname") local result = v:lines()() v:close() return result end function util.getFileAndInode(task , timestamp) local path = task.path if task.logNameSuffix then path = task.path .. os_date(task.logNameSuffix , timestamp) end local file = io_open(path , "r") local inode = nil if file then local tmp = io_popen("ls -i " .. path) inode = tmp:lines()() tmp:close() end return file , inode end function util.checkFileRolling(task , file , inode , timestamp) local rolling = false if file == nil then file , inode = util.getFileAndInode(task , timestamp) rolling = true else local t_file , t_inode = util.getFileAndInode(task , timestamp) if inode == t_inode then t_file:close() else file:close() file , inode , rolling = t_file , t_inode , true end end return rolling , file , inode end function util.mergeMapTables(tbs) local container = {} for _ , tb in ipairs(tbs) do for key , value in pairs(tb) do container[key] = value end end return container end function util.mergeMapTables2Left(left , right) for key , value in pairs(right) do left[key] = value end end function util.parseData(msg , rule , container) local handled , parseResult = false , {msg:match(rule.regex)} for index , value in ipairs(parseResult) do local cf = rule.conversion[index] container[rule.mapping[index]] = (cf and cf(value) or value) handled = true end return handled end function util.grok(rule) rule.mapping = {} local escapes = { ['%%'] = '%%%' , ['%.'] = '%%.' , ['%['] = '%%[' , ['%]'] = '%%]' , ['%('] = '%%(' , ['%)'] = '%%)' , ['%+'] = '%%+' , ['%*'] = '%%*' , ['%-'] = '%%-' , ['%?'] = '%%?' , ['%^'] = '%%^' , } for k , v in pairs(escapes) do rule.grok = string.gsub(rule.grok , k , v) end local t_grokstr , cts = string.gsub(rule.grok , '%$([%a|_]+)%$([%a|_]+)' , function(l , f) return '$' .. l .. '_' .. f end) while cts > 0 do t_grokstr , cts = string.gsub(t_grokstr , '%$([%a|_]+)%$([%a|_]+)' , function(l , f) return '$' .. l .. '_' .. f end) end local _ , count = string.gsub(t_grokstr , '%$([%a|_]+)' , '(.-)') local index = 0 rule.regex = string.gsub(t_grokstr , '%$([%a|_]+)' , function(w) table.insert(rule.mapping , w) index = index + 1 return (index == count and '(.*)' or '(.-)') end) end function util.grokP(rule) local total_len , pos = string.len(rule.regex) , 0 local posSeq = {} while total_len - pos > 4 do pos = string.find(rule.regex , '%(%.%-%)' , pos) if pos then pos = pos + 4 table.insert(posSeq , pos) else pos = total_len end end local index = 1 local result = string.gsub(rule.regex , '%(%.%-%)' , function(w) local sp = string.sub(rule.regex , posSeq[index] , posSeq[index] + 1) if sp == '%' then sp = string.sub(rule.regex , posSeq[index] , posSeq[index] + 2) end sp = '([^' .. sp .. ']*)' index = index + 1 return sp end) rule.regex = result end return util
fix grok bug
fix grok bug
Lua
apache-2.0
peiliping/logwatch
0fa934280308ed31f778c72125b14f2c41882173
mods/BeardLib-Editor/Classes/Map/Elements/navobstacleelement.lua
mods/BeardLib-Editor/Classes/Map/Elements/navobstacleelement.lua
EditorNavObstacle = EditorNavObstacle or class(MissionScriptEditor) --Currently broken function EditorNavObstacle:create_element() EditorNavObstacle.super.create_element(self) self._element.class = "ElementNavObstacle" self._element.values.obstacle_list = {} self._element.values.operation = "add" self._guis = {} self._obstacle_units = {} self._all_object_names = {} end function EditorNavObstacle:_build_panel() self:_create_panel() self:ComboCtrl("operation", {"add", "remove"}, {help = "Choose if you want to add or remove an obstacle"}) self:BuildUnitsManage("obstacle_list", {values_name = "Object", value_key = "obj_name", key = "unit_id", orig = {unit_id = 0, obj_name = "", guis_id = 1}, combo_items_func = function(name, value) -- get all obj idstrings and map them to unindented values -- why the fuck is this function called collect it should be called map AAAA local objects = table.collect(self:_get_objects_by_unit(value.unit), self._unindent_obj_name) return objects end}) end function EditorNavObstacle:_get_objects_by_unit(unit) local all_object_names = {} if unit then local root_obj = unit:orientation_object() all_object_names = {} local tree_depth = 1 local function _process_object_tree(obj, depth) local indented_name = obj:name():s() for i = 1, depth, 1 do indented_name = "-" .. indented_name end table.insert(all_object_names, indented_name) local children = obj:children() for _, child in ipairs(children) do _process_object_tree(child, depth + 1) end end _process_object_tree(root_obj, 0) end return all_object_names end function EditorNavObstacle._unindent_obj_name(obj_name) while string.sub(obj_name, 1, 1) == "-" do obj_name = string.sub(obj_name, 2) end -- get rid of @ID(obj_name)@ return obj_name:match("@ID(.*)@") end
EditorNavObstacle = EditorNavObstacle or class(MissionScriptEditor) --Currently broken function EditorNavObstacle:create_element() EditorNavObstacle.super.create_element(self) self._element.class = "ElementNavObstacle" self._element.values.obstacle_list = {} self._element.values.operation = "add" self._guis = {} self._obstacle_units = {} self._all_object_names = {} end function EditorNavObstacle:_build_panel() self:_create_panel() self:ComboCtrl("operation", {"add", "remove"}, {help = "Choose if you want to add or remove an obstacle"}) self:BuildUnitsManage("obstacle_list", {values_name = "Object", value_key = "obj_name", key = "unit_id", orig = {unit_id = 0, obj_name = Idstring(""), guis_id = 1}, combo_items_func = function(name, value) -- get all obj idstrings and map them to unindented values -- why the fuck is this function called collect it should be called map AAAA local objects = table.collect(self:_get_objects_by_unit(value.unit), self._unindent_obj_name) return objects end}) end function EditorNavObstacle:_get_objects_by_unit(unit) local all_object_names = {} if unit then local root_obj = unit:orientation_object() all_object_names = {} local tree_depth = 1 local function _process_object_tree(obj, depth) local indented_name = obj:name():s() for i = 1, depth, 1 do indented_name = "-" .. indented_name end table.insert(all_object_names, indented_name) local children = obj:children() for _, child in ipairs(children) do _process_object_tree(child, depth + 1) end end _process_object_tree(root_obj, 0) end return all_object_names end function EditorNavObstacle._unindent_obj_name(obj_name) while string.sub(obj_name, 1, 1) == "-" do obj_name = string.sub(obj_name, 2) end return Idstring(obj_name) end
I can't beleive it took me so long to fix #258
I can't beleive it took me so long to fix #258
Lua
mit
simon-wh/PAYDAY-2-BeardLib-Editor
ffd1428e21e287abde33bef6d00cae7da141804a
home/.hammerspoon/jira.lua
home/.hammerspoon/jira.lua
-- Requirements and local vars local utils = require('utils') local jiraAccount = require ('jiraAccount') local log = hs.logger.new('init.lua', 'debug') local jira = {} -- Returns a Jira URL to browse the given issue Key function jira.getBrowseUrl(key) local url = ""; -- Accordig to the issue key, we use either the base or alt URL local c2 = string.sub(key, 1, 2) if string.match(c2, "^" .. jiraAccount.getDefaultProjectPrefix()) ~= nil then url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key) else url = string.format("%s%s%s", jiraAccount.getAltBaseUrl(), "browse/", key) end return url -- IRN-23450 end -- Type JIRA issue browsing base url function jira.typeBrowseUrl() local url = jira.getBrowseUrl(utils.getTrimmedSelectedText()) hs.eventtap.keyStrokes(url) end -- Type a JIRA bug template function jira.typeBugTemplate() local source=[[ # *Steps to reproduce* ## ## # *Expected result* ## ## # *Actual* ## ## # *Reproducibility* ## 100% # *Traces* ## File attached foobar.log ## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code} ## !Foobar Sreenshot.png|thumbnail! # *Extra Information* ## ## ]] hs.eventtap.keyStrokes(source) end -- Search the highlighted selection in Request.jira.com function jira.search() local url = jiraAccount.getBaseUrl() .. "issues/?jql=project IN " .. jiraAccount.getDefaultSearchProjects() .. " AND summary ~ \"" .. utils.getTrimmedSelectedText() .. "\" ORDER BY issueKey DESC" log.f("Searching '%s'", url) -- TODO: if empty, pop-up a chooser utils.browseUrl(url) end -- Browse the issue key currently highlighted selection, or pop up a chooser function jira.browseIssue() local key = utils.getTrimmedSelectedText() if key == "" then log.f("browseIssue: no selection: invoking graphical chooser") lookupJiraIssue() else -- Does the key starts with only a digit ? local c1 = string.sub(key, 1, 1) if string.match(c1, "^%d") ~= nil then -- Yes: add the default project prefix ! log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix()) key = jiraAccount.getDefaultProjectPrefix() .. key end log.f("browseIssue: browse issue '%s'", key) utils.browseUrl(jira.getBrowseUrl(key)) end end -- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua -- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial) function createAuthorisationRequestBody() return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword()) end function getSession() log.f("getSession(): entering") data = createAuthorisationRequestBody() headers = {["Content-Type"] = "application/json"} status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers) log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then result = hs.json.decode(body) session = result["session"] return session["name"], session["value"] else return nil, nil end end function lookupJiraIssue() sessionName, sessionValue = getSession() if (sessionName ~= nil and sessionValue ~= nil) then log.f("lookupJiraIssue(): got a valid session.") local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"} local picker = hs.chooser.new(function(userInput) if userInput ~= nil then log.f("chooser: user chose '%s'",userInput) if userInput["key"] ~= Nil then local url = jira.getBrowseUrl(userInput["key"]) log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url) hs.execute("open " .. url) end end end) picker:query(jiraAccount.getDefaultIssueSearch()) picker:queryChangedCallback( function(query) log.f("queryChangedCallback(): query is '%s'", query) if string.len(query) > 3 then log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query) hs.http.asyncGet( getJiraQueryUrl(query), cookieHeaders, function(status, body, headers) log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then searchResult = hs.json.decode(body) if searchResult["fields"] ~= nil then local results = {} local key = searchResult["key"] local summary = searchResult["fields"]["summary"] table.insert(results, {text = key, subText = summary, key = key}) picker:choices(results) end end end ) else log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query) end end ) picker:rows(1) picker:show() else log.f("lookupJiraIssue(): could not get a valid session.") notify = hs.notify.new() notify:title("Jira") notify:informativeText("Could not get authorization") notify:send() end end function getJiraQueryUrl(query) local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query) log.f("jiraQuey(): return url '%s'", url) return url end return jira
-- Requirements and local vars local utils = require('utils') local jiraAccount = require ('jiraAccount') local log = hs.logger.new('init.lua', 'debug') local jira = {} local function startsWith(str, start) return str:sub(1, #start) == start end -- Returns a Jira URL to browse the given issue Key function jira.getBrowseUrl(key) log.f("getBrowseUrl: Build url for issue key '%s'", key) local url = ""; -- Accordig to the issue key, we use either the base or alt URL if startsWith(key, jiraAccount.getDefaultProjectPrefix()) then url = jiraAccount.getBaseUrl() else url = jiraAccount.getAltBaseUrl() end log.f("getBrowseUrl: use base URL '%s'", url) url = string.format("%sbrowse/%s", url, key) return url -- IRN-940 IS-28800 end -- Type JIRA issue browsing base url function jira.typeBrowseUrl() local url = jira.getBrowseUrl(utils.getTrimmedSelectedText()) hs.eventtap.keyStrokes(url) end -- Type a JIRA bug template function jira.typeBugTemplate() local source=[[ # *Steps to reproduce* ## ## # *Expected result* ## ## # *Actual* ## ## # *Reproducibility* ## 100% # *Traces* ## File attached foobar.log ## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code} ## !Foobar Sreenshot.png|thumbnail! # *Extra Information* ## ## ]] hs.eventtap.keyStrokes(source) end -- Search the highlighted selection in Request.jira.com function jira.search() local url = jiraAccount.getBaseUrl() .. "issues/?jql=project IN " .. jiraAccount.getDefaultSearchProjects() .. " AND summary ~ \"" .. utils.getTrimmedSelectedText() .. "\" ORDER BY issueKey DESC" log.f("Searching '%s'", url) -- TODO: if empty, pop-up a chooser utils.browseUrl(url) end -- Browse the issue key currently highlighted selection, or pop up a chooser function jira.browseIssue() local key = utils.getTrimmedSelectedText() if key == "" then log.f("browseIssue: no selection: invoking graphical chooser") lookupJiraIssue() else -- Does the key starts with only a digit ? local c1 = string.sub(key, 1, 1) if string.match(c1, "^%d") ~= nil then -- Yes: add the default project prefix ! log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix()) key = jiraAccount.getDefaultProjectPrefix() .. key end log.f("browseIssue: browse issue '%s'", key) utils.browseUrl(jira.getBrowseUrl(key)) end end -- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua -- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial) function createAuthorisationRequestBody() return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword()) end function getSession() log.f("getSession(): entering") data = createAuthorisationRequestBody() headers = {["Content-Type"] = "application/json"} status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers) log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then result = hs.json.decode(body) session = result["session"] return session["name"], session["value"] else return nil, nil end end function lookupJiraIssue() sessionName, sessionValue = getSession() if (sessionName ~= nil and sessionValue ~= nil) then log.f("lookupJiraIssue(): got a valid session.") local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"} local picker = hs.chooser.new(function(userInput) if userInput ~= nil then log.f("chooser: user chose '%s'",userInput) if userInput["key"] ~= Nil then local url = jira.getBrowseUrl(userInput["key"]) log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url) hs.execute("open " .. url) end end end) picker:query(jiraAccount.getDefaultIssueSearch()) picker:queryChangedCallback( function(query) log.f("queryChangedCallback(): query is '%s'", query) if string.len(query) > 3 then log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query) hs.http.asyncGet( getJiraQueryUrl(query), cookieHeaders, function(status, body, headers) log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then searchResult = hs.json.decode(body) if searchResult["fields"] ~= nil then local results = {} local key = searchResult["key"] local summary = searchResult["fields"]["summary"] table.insert(results, {text = key, subText = summary, key = key}) picker:choices(results) end end end ) else log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query) end end ) picker:rows(1) picker:show() else log.f("lookupJiraIssue(): could not get a valid session.") notify = hs.notify.new() notify:title("Jira") notify:informativeText("Could not get authorization") notify:send() end end function getJiraQueryUrl(query) local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query) log.f("jiraQuey(): return url '%s'", url) return url end return jira
fix: Fix the base vs alt baseURL condition
fix: Fix the base vs alt baseURL condition
Lua
mit
maanuair/dotfiles_tmp,maanuair/dotfiles
7f272c5107bd3960e018b71a887cf74c822d90c2
asyncsgd/optim-msgd.lua
asyncsgd/optim-msgd.lua
-- MSGD -- Nesterov's momentum, see e.g. Sutskever et al., ICML 2013 -- Author: Sixin Zhang (zsx@cims.nyu.edu) require 'optim' function optim.msgd(opfunc, w, config, state) local config = config or {} local state = state or config local lr = config.lr or 0 local lrd = config.lrd or 0 local lrp = config.lrp or 0 local mmax = config.mommax or 1 local mlrd = config.momdecay or 0 local l2wd = config.l2wd or 0 state.pversion = state.pversion or 0 local mom = mmax if mom > 0 then if mlrd > 0 then mom = math.min(mom, 1-0.5/(1+state.pversion/mlrd)) end if not state.vt then state.vt = w:clone():zero() end state.vt:mul(mom) w:add(state.vt) end local fx,dfdx = opfunc(w) if l2wd ~= 0 then dfdx:add(l2wd,w) end local clr = lr if lrd > 0 and lrp > 0 then clr = lr / math.pow(1+state.pversion*lrd,lrp) end w:add(-clr,dfdx) if mom > 0 then state.vt:add(-clr,dfdx) end state.pversion = state.pversion + 1 return w,{fx} end
-- MSGD -- Nesterov's momentum, see e.g. Sutskever et al., ICML 2013 -- Author: Sixin Zhang (zsx@cims.nyu.edu) require 'optim' function optim.msgd(opfunc, w, config, state) local config = config or {} local state = state or config local lr = config.lr or 0 local lrd = config.lrd or 0 local lrp = config.lrp or 0 local mom = config.mom or 0 local mmax = config.mommax or 1 local mlrd = config.momdecay or 0 local l2wd = config.l2wd or 0 state.pversion = state.pversion or 0 if mom > 0 then if mlrd > 0 then mom = math.min(mom, 1-0.5/(1+state.pversion/mlrd)) end if not state.vt then state.vt = w:clone():zero() end state.vt:mul(mom) w:add(state.vt) end local fx,dfdx = opfunc(w) if l2wd ~= 0 then dfdx:add(l2wd,w) end local clr = lr if lrd > 0 and lrp > 0 then clr = lr / math.pow(1+state.pversion*lrd,lrp) end w:add(-clr,dfdx) if mom > 0 then state.vt:add(-clr,dfdx) end state.pversion = state.pversion + 1 return w,{fx} end
fix msgd mom variable init
fix msgd mom variable init
Lua
apache-2.0
sixin-zh/mpiT,sixin-zh/mpiT,sixin-zh/mpiT
8f0fe69369b55f52d0c86bdd33ed1bf903241c7f
pud/entity/EntityArray.lua
pud/entity/EntityArray.lua
local Class = require 'lib.hump.class' local property = require 'pud.component.property' local table_sort = table.sort -- EntityArray -- local EntityArray = Class{name='EntityArray', function(self, ...) self._entities = {} self._count = 0 if select('#', ...) > 0 then self:add(...) end end } -- destructor function EntityArray:destroy() self:clear() self._entities = nil self._count = nil end -- add entities to the array function EntityArray:add(id) verify('number', id) local success = false if not self._entities[id] then self._entities[id] = true success = true end return success end -- remove entities from the array function EntityArray:remove(id) local success = false if self._entities[id] then self._entities[id] = nil success = true end return success end -- return the entity table as an unsorted array of IDs. -- if property is supplied, only entities with that property (non-nil) are -- returned. function EntityArray:getArray(prop) local propStr = prop and property(prop) or nil local array = {} local count = 0 for k in pairs(self._entities) do local ent = EntityRegistry:get(k) local p = not nil if propStr then p = ent:query(propStr) end if nil ~= p then count = count + 1 array[count] = k end end return count > 0 and array or nil end -- get an array of all the entities, sorted by property function EntityArray:byProperty(prop) local propStr = property(prop) local array = self:getArray(propStr) -- comparison function for sorting by a property local _byProperty = function(a, b) if not a then return true end if not b then return false end local aEnt, bEnt = EntityRegistry:get(a), EntityRegistry:get(b) local aVal, bVal = aEnt:query(propStr), bEnt:query(propStr) if aVal == nil then return true end if bVal == nil then return false end return aVal < bVal end table_sort(array, _byProperty) return array end -- return the size of the array function EntityArray:size() return self._count end -- iterate through the array function EntityArray:iterate() local array = self:getArray() local i = 0 return function() i = i + 1; return array[i] end end -- clear the array function EntityArray:clear() for k in pairs(self._entities) do self._entities[k] = nil end self._count = 0 end -- the class return EntityArray
local Class = require 'lib.hump.class' local property = require 'pud.component.property' local table_sort = table.sort -- EntityArray -- local EntityArray = Class{name='EntityArray', function(self, ...) self._entities = {} self._count = 0 if select('#', ...) > 0 then self:add(...) end end } -- destructor function EntityArray:destroy() self:clear() self._entities = nil self._count = nil end -- add entities to the array function EntityArray:add(id) verify('number', id) local success = false if not self._entities[id] then self._entities[id] = true self._count = self._count + 1 success = true end return success end -- remove entities from the array function EntityArray:remove(id) local success = false if self._entities[id] then self._entities[id] = nil self._count = self._count - 1 success = true end return success end -- return the entity table as an unsorted array of IDs. -- if property is supplied, only entities with that property (non-nil) are -- returned. function EntityArray:getArray(prop) local propStr = prop and property(prop) or nil local array = {} local count = 0 for k in pairs(self._entities) do local ent = EntityRegistry:get(k) local p = not nil if propStr then p = ent:query(propStr) end if nil ~= p then count = count + 1 array[count] = k end end return count > 0 and array or nil end -- get an array of all the entities, sorted by property function EntityArray:byProperty(prop) local propStr = property(prop) local array = self:getArray(propStr) -- comparison function for sorting by a property local _byProperty = function(a, b) if not a then return true end if not b then return false end local aEnt, bEnt = EntityRegistry:get(a), EntityRegistry:get(b) local aVal, bVal = aEnt:query(propStr), bEnt:query(propStr) if aVal == nil then return true end if bVal == nil then return false end return aVal < bVal end table_sort(array, _byProperty) return array end -- return the size of the array function EntityArray:size() return self._count end -- iterate through the array function EntityArray:iterate() local array = self:getArray() local i = 0 return function() i = i + 1; return array[i] end end -- clear the array function EntityArray:clear() for k in pairs(self._entities) do self:remove(k) end self._count = 0 end -- the class return EntityArray
fix EntityArray size
fix EntityArray size
Lua
mit
scottcs/wyx
5ca386469071d606609beb19a7f09325f3a8ed29
modules/luci-base/luasrc/model/cbi/admin_network/proto_static.lua
modules/luci-base/luasrc/model/cbi/admin_network/proto_static.lua
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ifc = net:get_interface() local ipaddr, netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw local mtu, metric ipaddr = section:taboption("general", Value, "ipaddr", translate("IPv4 address")) ipaddr.datatype = "ip4addr" netmask = section:taboption("general", Value, "netmask", translate("IPv4 netmask")) netmask.datatype = "ip4addr" netmask:value("255.255.255.0") netmask:value("255.255.0.0") netmask:value("255.0.0.0") gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway")) gateway.datatype = "ip4addr" broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast")) broadcast.datatype = "ip4addr" dns = section:taboption("general", DynamicList, "dns", translate("Use custom DNS servers")) dns.datatype = "ipaddr" dns.cast = "string" if luci.model.network:has_ipv6() then local ip6assign = section:taboption("general", Value, "ip6assign", translate("IPv6 assignment length"), translate("Assign a part of given length of every public IPv6-prefix to this interface")) ip6assign:value("", translate("disabled")) ip6assign:value("64") ip6assign.datatype = "max(64)" local ip6hint = section:taboption("general", Value, "ip6hint", translate("IPv6 assignment hint"), translate("Assign prefix parts using this hexadecimal subprefix ID for this interface.")) for i=33,64 do ip6hint:depends("ip6assign", i) end ip6addr = section:taboption("general", Value, "ip6addr", translate("IPv6 address")) ip6addr.datatype = "ip6addr" ip6addr:depends("ip6assign", "") ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway")) ip6gw.datatype = "ip6addr" ip6gw:depends("ip6assign", "") local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("Public prefix routed to this device for distribution to clients.")) ip6prefix.datatype = "ip6addr" ip6prefix:depends("ip6assign", "") end luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address")) mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ifc = net:get_interface() local ipaddr, netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw local mtu, metric ipaddr = section:taboption("general", Value, "ipaddr", translate("IPv4 address")) ipaddr.datatype = "ip4addr" netmask = section:taboption("general", Value, "netmask", translate("IPv4 netmask")) netmask.datatype = "ip4addr" netmask:value("255.255.255.0") netmask:value("255.255.0.0") netmask:value("255.0.0.0") gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway")) gateway.datatype = "ip4addr" broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast")) broadcast.datatype = "ip4addr" dns = section:taboption("general", DynamicList, "dns", translate("Use custom DNS servers")) dns.datatype = "ipaddr" dns.cast = "string" if luci.model.network:has_ipv6() then local ip6assign = section:taboption("general", Value, "ip6assign", translate("IPv6 assignment length"), translate("Assign a part of given length of every public IPv6-prefix to this interface")) ip6assign:value("", translate("disabled")) ip6assign:value("64") ip6assign.datatype = "max(64)" local ip6hint = section:taboption("general", Value, "ip6hint", translate("IPv6 assignment hint"), translate("Assign prefix parts using this hexadecimal subprefix ID for this interface.")) for i=33,64 do ip6hint:depends("ip6assign", i) end ip6addr = section:taboption("general", Value, "ip6addr", translate("IPv6 address")) ip6addr.datatype = "ip6addr" ip6addr:depends("ip6assign", "") ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway")) ip6gw.datatype = "ip6addr" ip6gw:depends("ip6assign", "") local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("Public prefix routed to this device for distribution to clients.")) ip6prefix.datatype = "ip6addr" ip6prefix:depends("ip6assign", "") local ip6ifaceid = s:taboption("general", Value, "ip6ifaceid", translate("IPv6 suffix"), translate("Optional. Allowed values: 'eui64', 'random', fixed value like '::1' " .. "or '::1:2'. When IPv6 prefix (like 'a:b:c:d::') is received from a " .. "delegating server, use the suffix (like '::1') to form the IPv6 address " .. "('a:b:c:d::1') for the interface.")) ip6ifaceid.datatype = "ip6hostid" ip6ifaceid.placeholder = "::1" ip6ifaceid.rmempty = true end luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address")) mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
luci-base: support ip6ifaceid option for proto_static
luci-base: support ip6ifaceid option for proto_static Add support for 'ip6ifaceid' option for proto_static in LuCI. Information about the option: The option is optional and defaults to '::1'. Allowed values: 'eui64', 'random', fixed value like '::1' or '::1:2' When IPv6 prefix (like 'a:b:c:d::') is received from a delegating server, the ip6ifaceid suffix (like '::1') is used to form the IPv6 address ('a:b:c:d::1') for the interface. Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
Lua
apache-2.0
artynet/luci,oneru/luci,wongsyrone/luci-1,Noltari/luci,981213/luci-1,kuoruan/lede-luci,remakeelectric/luci,nmav/luci,Wedmer/luci,remakeelectric/luci,nmav/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,aa65535/luci,openwrt/luci,rogerpueyo/luci,aa65535/luci,oneru/luci,981213/luci-1,taiha/luci,rogerpueyo/luci,taiha/luci,Noltari/luci,kuoruan/luci,981213/luci-1,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,Noltari/luci,hnyman/luci,chris5560/openwrt-luci,Noltari/luci,openwrt/luci,Noltari/luci,lbthomsen/openwrt-luci,nmav/luci,nmav/luci,wongsyrone/luci-1,kuoruan/lede-luci,Noltari/luci,chris5560/openwrt-luci,remakeelectric/luci,kuoruan/lede-luci,hnyman/luci,Wedmer/luci,remakeelectric/luci,openwrt-es/openwrt-luci,nmav/luci,981213/luci-1,artynet/luci,taiha/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,taiha/luci,hnyman/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,oneru/luci,wongsyrone/luci-1,kuoruan/luci,rogerpueyo/luci,981213/luci-1,remakeelectric/luci,kuoruan/lede-luci,kuoruan/lede-luci,aa65535/luci,rogerpueyo/luci,Wedmer/luci,hnyman/luci,kuoruan/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,kuoruan/luci,lbthomsen/openwrt-luci,hnyman/luci,981213/luci-1,tobiaswaldvogel/luci,aa65535/luci,kuoruan/lede-luci,nmav/luci,Wedmer/luci,taiha/luci,oneru/luci,openwrt-es/openwrt-luci,remakeelectric/luci,Wedmer/luci,hnyman/luci,aa65535/luci,artynet/luci,kuoruan/lede-luci,rogerpueyo/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,oneru/luci,oneru/luci,aa65535/luci,artynet/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,taiha/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,wongsyrone/luci-1,oneru/luci,kuoruan/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,981213/luci-1,artynet/luci,taiha/luci,Wedmer/luci,hnyman/luci,chris5560/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,remakeelectric/luci,openwrt/luci,hnyman/luci,taiha/luci,kuoruan/luci,Wedmer/luci,kuoruan/luci,remakeelectric/luci,Noltari/luci,openwrt/luci,kuoruan/lede-luci,artynet/luci,openwrt/luci,openwrt/luci,openwrt/luci,wongsyrone/luci-1,kuoruan/luci,lbthomsen/openwrt-luci,Wedmer/luci,nmav/luci,nmav/luci,tobiaswaldvogel/luci,Noltari/luci,openwrt/luci,wongsyrone/luci-1,artynet/luci,Noltari/luci,wongsyrone/luci-1,chris5560/openwrt-luci,aa65535/luci,aa65535/luci,oneru/luci,tobiaswaldvogel/luci,artynet/luci
6e3f61cf47873c0b3dfa455fee1139919bf7fd3c
nodemcu/wifimodule.lua
nodemcu/wifimodule.lua
local wifimodule = {} -- Connect to Wi-Fi function wifimodule.connect(network, callback) wifi.setmode(wifi.STATION) wifi.sta.config(network.ssid, network.password) wifi.sta.eventMonReg(wifi.STA_IDLE, function() print('[Wi-Fi] Idle') end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print('[Wi-Fi] Connecting...') end) wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() print('[Wi-Fi] Wrong Password') end) wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print('[Wi-Fi] No access point found') end) wifi.sta.eventMonReg(wifi.STA_FAIL, function() print('[Wi-Fi] Failed to connect') end) wifi.sta.eventMonReg(wifi.STA_GOTIP, function() print('[Wi-Fi] Received valid IP') local conn = net.createConnection(net.TCP, false) ip, nm, gateway = wifi.sta.getip() local redirHost = gateway .. ':8002' -- Auto-accept HvA open wifi thingy conn:on('receive', function(sck, c) print('[Wi-Fi] Connected to ' .. network.ssid .. '!') callback() end) if network.ssid == 'HvA Open Wi-Fi' then conn:on('connection', function(sck, c) sck:send('POST / HTTP/1.1\r\nHost: ' .. redirHost .. '\r\nOrigin: http://' .. redirHost .. '\r\nContent-Type: application/x-www-form-urlencoded\r\nReferer: http://' .. redirHost .. '/index.php\r\nContent-Length: 52\r\n\r\nredirurl=http%3A%2F%2Fwww.hva.nl%2F&accept=Verbinden') end) end conn:connect(8002, gateway) end) wifi.sta.eventMonStart() wifi.sta.connect() end return wifimodule
local wifimodule = {} -- Connect to Wi-Fi function wifimodule.connect(network, callback) wifi.setmode(wifi.STATION) wifi.sta.config(network.ssid, network.password) wifi.sta.eventMonReg(wifi.STA_IDLE, function() print('[Wi-Fi] Idle') end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print('[Wi-Fi] Connecting...') end) wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() print('[Wi-Fi] Wrong Password') end) wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print('[Wi-Fi] No access point found') end) wifi.sta.eventMonReg(wifi.STA_FAIL, function() print('[Wi-Fi] Failed to connect') end) wifi.sta.eventMonReg(wifi.STA_GOTIP, function() print('[Wi-Fi] Received valid IP') local conn = net.createConnection(net.TCP, false) ip, nm, gateway = wifi.sta.getip() local redirHost = gateway .. ':8002' conn:on('receive', function(sck, c) print('[Wi-Fi] Connected to ' .. network.ssid .. '!') callback() end) conn:on('connection', function(sck, c) -- Auto-accept HvA open wifi if network.ssid == 'HvA Open Wi-Fi' then sck:send('POST / HTTP/1.1\r\nHost: ' .. redirHost .. '\r\nOrigin: http://' .. redirHost .. '\r\nContent-Type: application/x-www-form-urlencoded\r\nReferer: http://' .. redirHost .. '/index.php\r\nContent-Length: 52\r\n\r\nredirurl=http%3A%2F%2Fwww.hva.nl%2F&accept=Verbinden') else sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end end) -- conn:connect(8002, gateway) conn:connect(80,"httpbin.org") end) wifi.sta.eventMonStart() wifi.sta.connect() end return wifimodule
Fix wifi connection and receive for custom networks
Fix wifi connection and receive for custom networks
Lua
mit
rijkvanzanten/luaus
b954873d0f91b418ab3a92f94e93dbdbec671ede
libs/http/luasrc/http/protocol/conditionals.lua
libs/http/luasrc/http/protocol/conditionals.lua
--[[ HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI http protocol implementation - HTTP/1.1 bits. -- This class provides basic ETag handling and implements most of the -- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 . module("luci.http.protocol.conditionals", package.seeall) local date = require("luci.http.protocol.date") --- Implement 14.19 / ETag. -- @param stat A file.stat structure -- @return String containing the generated tag suitable for ETag headers function mk_etag( stat ) if stat ~= nil then return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime ) end end --- 14.24 / If-Match -- Test whether the given message object contains an "If-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-Match']) == "string" then for ent in h['If-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then return true end end return false, 412 end return true end --- 14.25 / If-Modified-Since -- Test whether the given message object contains an "If-Modified-Since" header -- and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_modified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Modified-Since']) == "string" then local since = date.to_unix( h['If-Modified-Since'] ) if stat == nil or since < stat.mtime then return true end return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } end return true end --- 14.26 / If-None-Match -- Test whether the given message object contains an "If-None-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_none_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-None-Match']) == "string" then for ent in h['If-None-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then if req.request_method == "get" or req.request_method == "head" then return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } else return false, 412 end end end end return true end --- 14.27 / If-Range -- The If-Range header is currently not implemented due to the lack of general -- byte range stuff in luci.http.protocol . This function will always return -- false, 412 to indicate a failed precondition. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_range( req, stat ) -- Sorry, no subranges (yet) return false, 412 end --- 14.28 / If-Unmodified-Since -- Test whether the given message object contains an "If-Unmodified-Since" -- header and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_unmodified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Unmodified-Since']) == "string" then local since = date.to_unix( h['If-Unmodified-Since'] ) if stat ~= nil and since <= stat.mtime then return false, 412 end end return true end
--[[ HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI http protocol implementation - HTTP/1.1 bits. -- This class provides basic ETag handling and implements most of the -- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 . module("luci.http.protocol.conditionals", package.seeall) local date = require("luci.http.protocol.date") --- Implement 14.19 / ETag. -- @param stat A file.stat structure -- @return String containing the generated tag suitable for ETag headers function mk_etag( stat ) if stat ~= nil then return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime ) end end --- 14.24 / If-Match -- Test whether the given message object contains an "If-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-Match']) == "string" then for ent in h['If-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then return true end end return false, 412 end return true end --- 14.25 / If-Modified-Since -- Test whether the given message object contains an "If-Modified-Since" header -- and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_modified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Modified-Since']) == "string" then local since = date.to_unix( h['If-Modified-Since'] ) if stat == nil or since < stat.mtime then return true end return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } end return true end --- 14.26 / If-None-Match -- Test whether the given message object contains an "If-None-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_none_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) local method = req.env and req.env.REQUEST_METHOD or "GET" -- Check for matching resource if type(h['If-None-Match']) == "string" then for ent in h['If-None-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then if method == "GET" or method == "HEAD" then return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } else return false, 412 end end end end return true end --- 14.27 / If-Range -- The If-Range header is currently not implemented due to the lack of general -- byte range stuff in luci.http.protocol . This function will always return -- false, 412 to indicate a failed precondition. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_range( req, stat ) -- Sorry, no subranges (yet) return false, 412 end --- 14.28 / If-Unmodified-Since -- Test whether the given message object contains an "If-Unmodified-Since" -- header and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_unmodified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Unmodified-Since']) == "string" then local since = date.to_unix( h['If-Unmodified-Since'] ) if stat ~= nil and since <= stat.mtime then return false, 412 end end return true end
libs/http: fix incorrent treatment of If-None-Match (#100)
libs/http: fix incorrent treatment of If-None-Match (#100) git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5635 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,jschmidlapp/luci,8devices/carambola2-luci,stephank/luci,saraedum/luci-packages-old,stephank/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,saraedum/luci-packages-old,Flexibity/luci,freifunk-gluon/luci,freifunk-gluon/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,Canaan-Creative/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,projectbismark/luci-bismark,ch3n2k/luci,eugenesan/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,gwlim/luci,gwlim/luci,vhpham80/luci,yeewang/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ch3n2k/luci,phi-psi/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,gwlim/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,jschmidlapp/luci,Flexibity/luci,stephank/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,zwhfly/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,jschmidlapp/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,Flexibity/luci,vhpham80/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,vhpham80/luci,Flexibity/luci,stephank/luci,stephank/luci,yeewang/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,stephank/luci,Flexibity/luci,vhpham80/luci,freifunk-gluon/luci,phi-psi/luci,jschmidlapp/luci,saraedum/luci-packages-old,gwlim/luci,Flexibity/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,ch3n2k/luci,8devices/carambola2-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci
3b6baaf20b3061a4df0290bfba151530214c89b3
script/c80600029.lua
script/c80600029.lua
--ヴァンパイア・ソーサラー function c80600029.initial_effect(c) --to grave local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_TO_GRAVE) e1:SetCondition(c80600029.condition) e1:SetTarget(c80600029.target) e1:SetOperation(c80600029.operation) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(80600029,0)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCost(c80600029.ntcost) e2:SetOperation(c80600029.ntop) c:RegisterEffect(e2) end function c80600029.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_DESTROY) and e:GetHandler():GetReasonPlayer()~=tp and e:GetHandler():GetPreviousControler()==tp end function c80600029.filter(c) return ( c:IsAttribute(ATTRIBUTE_DARK) and c:IsSetCard(0x92) or c:IsSetCard(0x92) and (c:IsType(TYPE_SPELL) or c:IsType(TYPE_TRAP)) ) and c:IsAbleToHand() end function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c80600029.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_DECREASE_TRIBUTE) e1:SetTargetRange(LOCATION_HAND,0) e1:SetTarget(c80600029.rfilter) e1:SetCountLimit(1) e1:SetValue(0x2) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c80600029.rfilter(e,c) return c:IsSetCard(0x92) end
--ヴァンパイア・ソーサラー function c80600029.initial_effect(c) --to grave local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_TO_GRAVE) e1:SetCondition(c80600029.condition) e1:SetTarget(c80600029.target) e1:SetOperation(c80600029.operation) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(80600029,0)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCost(c80600029.ntcost) e2:SetOperation(c80600029.ntop) c:RegisterEffect(e2) end function c80600029.condition(e,tp,eg,ep,ev,re,r,rp) return rp~=tp end function c80600029.filter(c) return ( c:IsAttribute(ATTRIBUTE_DARK) or c:IsType(TYPE_SPELL) or c:IsType(TYPE_TRAP) ) and c:IsAbleToHand() and c:IsSetCard(0x92) end function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c80600029.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_DECREASE_TRIBUTE) e1:SetTargetRange(LOCATION_HAND,0) e1:SetTarget(c80600029.rfilter) e1:SetCountLimit(1) e1:SetValue(0x2) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c80600029.rfilter(e,c) return c:IsSetCard(0x92) end
fix
fix fixed 1. effect sometimes not activating
Lua
mit
SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher
02719f8cd3348bf9c17891dbf916bc71f8ba5440
shared/monitor/detail.lua
shared/monitor/detail.lua
-- This file generates the data required for the two data tables -- in the server view -- Notice the deliberate pattern of defining private helper functions here -- This makes the code easier to maintain since we know this function is only -- used locally. require 'node' local function ConvertXmlToLua(Xml) local T = {} T.server = {} T.channels = {} local S = T.server local Ch = T.channels local MT = Xml.IguanaStatus trace(MT) for i = 1, #MT do if MT[i]:nodeType() == 'attribute' then S[MT[i]:nodeName()] = MT[i]:nodeValue() else -- We have to check that we have a channel node if (MT[i]:nodeName() == 'Channel') then local C = MT[i] local Cvars = {} for j = 1, #C do Cvars[C[j]:nodeName()] = C[j]:nodeValue() end Ch[C.Guid:S()] = Cvars end end end return T end function monitor.detail(Data) trace(Data) local C = monitor.connection() local D = C:query{sql= "SELECT name, ts, summary FROM status WHERE server_guid='" .. Data.params.guid .. "'", live=true} local Xml if #D > 0 then Xml = xml.parse(D[1].summary:S()) end local Details = ConvertXmlToLua(Xml) local Summary = { ChannelsInfo = {aaData = {}}, ServerInfo = {aaData = {}}, } -- Create chanels table headers. Summary.ServerInfo.aoColumns = { {['sTitle'] = 'Key', ['sType'] = 'string', sWidth = '%40'}, {['sTitle'] = 'Value', ['sType'] = 'string', sWidth = '%60'}, } -- Build up the servers info tables. local info = Details.server local CurrentTime = os.ts.time() Summary.Info = {Time=CurrentTime, AsString=os.ts.date("%c", CurrentTime)} Summary.ServerInfo.aaData = { { 'Date Time', info.DateTime }, { 'Channels', info.NumberOfChannels }, { 'Running Channels', info.NumberOfRunningChannels }, { 'Licensed Channels', info.NumberOfLicensedChannels }, { 'Service Errs', info.TotalServiceErrors }, { 'Version Valid', info.VersionValid }, { 'Version Build Id', info.VersionBuildId }, { 'Uptime', info.Uptime }, { 'Disk Size MB', info.DiskSizeMB }, { 'Disk Free MB', info.DiskFreeMB }, { 'Disk Used MB', info.DiskUsedMB }, { 'Logs Used', info.LogsUsedMB }, { 'Logs Used Last Wk KB', info.LogsUsedLastWeekKB }, { 'Logs Used Avg KB', info.LogsUsedAverageKB }, { 'Logs Used Avg Last Wk KB', info.LogsUsedAverageLastWeekKB }, { 'Logs Num Of Days', info.LogsNumberOfDays }, { 'Age Of Oldest File', info.AgeOfOldestFile }, { 'Iguana Id', info.IguanaId }, { 'Log Dir', info.LogDirectory }, { 'CPU Percent', info.CPUPercent }, { 'Memory KB', info.MemoryKB }, { 'Mem Rss KB', info.MemRssKB }, { 'Open FD', info.OpenFD }, { 'Server Name', info.ServerName }, { 'Cores', info.Cores }, { 'Permissions', info.Permissions }, { 'Start Time', info.StartTime }, { 'Thread Count', info.ThreadCount }, { 'Sockets Open', info.SocketsOpen }, { 'Sockets Limit', info.SocketsLimit }, } -- Create chanels table headers. Summary.ChannelsInfo.aoColumns = { {['sTitle'] = 'Name', ['sType'] = 'string'}, {['sTitle'] = 'Status', ['sType'] = 'string'}, {['sTitle'] = 'Type', ['sType'] = 'string'}, {['sTitle'] = 'Msgs Queued', ['sType'] = 'string'}, {['sTitle'] = 'Total Errs', ['sType'] = 'string'}, } -- Build up the channels table. local Statuses = { on='status-green', off='status-grey', error='status-red', transition='status-yellow'} local StatusHtml = '<div class="%s"></div>' local ComponentsHtml = [[ <img alt="%s" width="38" height="16"' border="0" title="" src="/monitor/icon_%s.gif"> <img alt="arrow" width="11" height="16" border="0" title="" src="/monitor/arrow.gif"> <img alt="%s" width="38" height="16"' border="0" title="" src="/monitor/icon_%s.gif"> ]] local Components = { ['From Translator'] = 'TRANS', ['To Translator'] = 'TRANS', ['From File'] = 'FILE', ['To File'] = 'FILE', ['From HTTPS'] = 'HTTPS', ['To HTTPS'] = 'HTTPS', ['LLP Listener'] = 'LLP', ['LLP Client'] = 'LLP', ['From Channel'] = 'QUE', ['To Channel'] = 'QUE', ['To Plugin'] = 'PLG-N', ['From Plugin'] = 'PLG-N'} local Row = 1 for _, Ch in pairs(Details.channels) do Summary.ChannelsInfo.aaData[Row] = { Ch.Name, string.format(StatusHtml, Statuses[Ch.Status]), string.format(ComponentsHtml, Components[Ch.Source], Components[Ch.Source], Components[Ch.Destination], Components[Ch.Destination]), Ch.MessagesQueued, Ch.TotalErrors } Row = Row + 1 end return Summary end
-- This file generates the data required for the two data tables -- in the server view -- Notice the deliberate pattern of defining private helper functions here -- This makes the code easier to maintain since we know this function is only -- used locally. require 'node' local function ConvertXmlToLua(Xml) local T = {} T.server = {} T.channels = {} local S = T.server local Ch = T.channels local MT = Xml.IguanaStatus trace(MT) for i = 1, #MT do if MT[i]:nodeType() == 'attribute' then S[MT[i]:nodeName()] = MT[i]:nodeValue() else -- We have to check that we have a channel node if (MT[i]:nodeName() == 'Channel') then local C = MT[i] local Cvars = {} for j = 1, #C do trace(j) if C[j]:nodeName() ~= "SocketStatus" then Cvars[C[j]:nodeName()] = C[j]:nodeValue() end end Ch[C.Guid:S()] = Cvars end end end return T end function monitor.detail(Data) trace(Data) local C = monitor.connection() local D = C:query{sql= "SELECT name, ts, summary FROM status WHERE server_guid='" .. Data.params.guid .. "'", live=true} local Xml if #D > 0 then Xml = xml.parse(D[1].summary:S()) end local Details = ConvertXmlToLua(Xml) local Summary = { ChannelsInfo = {aaData = {}}, ServerInfo = {aaData = {}}, } -- Create chanels table headers. Summary.ServerInfo.aoColumns = { {['sTitle'] = 'Key', ['sType'] = 'string', sWidth = '%40'}, {['sTitle'] = 'Value', ['sType'] = 'string', sWidth = '%60'}, } -- Build up the servers info tables. local info = Details.server local CurrentTime = os.ts.time() Summary.Info = {Time=CurrentTime, AsString=os.ts.date("%c", CurrentTime)} Summary.ServerInfo.aaData = { { 'Date Time', info.DateTime }, { 'Channels', info.NumberOfChannels }, { 'Running Channels', info.NumberOfRunningChannels }, { 'Licensed Channels', info.NumberOfLicensedChannels }, { 'Service Errs', info.TotalServiceErrors }, { 'Version Valid', info.VersionValid }, { 'Version Build Id', info.VersionBuildId }, { 'Uptime', info.Uptime }, { 'Disk Size MB', info.DiskSizeMB }, { 'Disk Free MB', info.DiskFreeMB }, { 'Disk Used MB', info.DiskUsedMB }, { 'Logs Used', info.LogsUsedMB }, { 'Logs Used Last Wk KB', info.LogsUsedLastWeekKB }, { 'Logs Used Avg KB', info.LogsUsedAverageKB }, { 'Logs Used Avg Last Wk KB', info.LogsUsedAverageLastWeekKB }, { 'Logs Num Of Days', info.LogsNumberOfDays }, { 'Age Of Oldest File', info.AgeOfOldestFile }, { 'Iguana Id', info.IguanaId }, { 'Log Dir', info.LogDirectory }, { 'CPU Percent', info.CPUPercent }, { 'Memory KB', info.MemoryKB }, { 'Mem Rss KB', info.MemRssKB }, { 'Open FD', info.OpenFD }, { 'Server Name', info.ServerName }, { 'Cores', info.Cores }, { 'Permissions', info.Permissions }, { 'Start Time', info.StartTime }, { 'Thread Count', info.ThreadCount }, { 'Sockets Open', info.SocketsOpen }, { 'Sockets Limit', info.SocketsLimit }, } -- Create chanels table headers. Summary.ChannelsInfo.aoColumns = { {['sTitle'] = 'Name', ['sType'] = 'string'}, {['sTitle'] = 'Status', ['sType'] = 'string'}, {['sTitle'] = 'Type', ['sType'] = 'string'}, {['sTitle'] = 'Msgs Queued', ['sType'] = 'string'}, {['sTitle'] = 'Total Errs', ['sType'] = 'string'}, } -- Build up the channels table. local Statuses = { on='status-green', off='status-grey', error='status-red', transition='status-yellow'} local StatusHtml = '<div class="%s"></div>' local ComponentsHtml = [[ <img alt="%s" width="38" height="16"' border="0" title="" src="/monitor/icon_%s.gif"> <img alt="arrow" width="11" height="16" border="0" title="" src="/monitor/arrow.gif"> <img alt="%s" width="38" height="16"' border="0" title="" src="/monitor/icon_%s.gif"> ]] local Components = { ['From Translator'] = 'TRANS', ['To Translator'] = 'TRANS', ['From File'] = 'FILE', ['To File'] = 'FILE', ['From HTTPS'] = 'HTTPS', ['To HTTPS'] = 'HTTPS', ['LLP Listener'] = 'LLP', ['LLP Client'] = 'LLP', ['From Channel'] = 'QUE', ['To Channel'] = 'QUE', ['To Plugin'] = 'PLG-N', ['From Plugin'] = 'PLG-N'} local Row = 1 for _, Ch in pairs(Details.channels) do Summary.ChannelsInfo.aaData[Row] = { Ch.Name, string.format(StatusHtml, Statuses[Ch.Status]), string.format(ComponentsHtml, Components[Ch.Source], Components[Ch.Source], Components[Ch.Destination], Components[Ch.Destination]), Ch.MessagesQueued, Ch.TotalErrors } Row = Row + 1 end return Summary end
Fixed up another change now that we have socket status info.
Fixed up another change now that we have socket status info.
Lua
mit
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
f9d744cc7907c33f13fba22334351b561a6fb2a9
sslobby/gamemode/init.lua
sslobby/gamemode/init.lua
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_scoreboard.lua") AddCSLuaFile("modules/sh_link.lua") AddCSLuaFile("modules/cl_link.lua") AddCSLuaFile("modules/sh_chairs.lua") AddCSLuaFile("modules/cl_chairs.lua") AddCSLuaFile("modules/cl_worldpicker.lua") AddCSLuaFile("modules/sh_minigame.lua") AddCSLuaFile("modules/cl_minigame.lua") AddCSLuaFile("modules/cl_worldpanel.lua") AddCSLuaFile("modules/sh_leaderboard.lua") AddCSLuaFile("modules/cl_leaderboard.lua") AddCSLuaFile("modules/sh_sound.lua") include("shared.lua") include("player_class/player_lobby.lua") include("player_extended.lua") include("modules/sv_socket.lua") include("modules/sh_link.lua") include("modules/sv_link.lua") include("modules/sh_chairs.lua") include("modules/sv_chairs.lua") include("modules/sv_worldpicker.lua") include("modules/sh_minigame.lua") include("modules/sv_minigame.lua") include("modules/sh_leaderboard.lua") include("modules/sv_leaderboard.lua") include("modules/sv_elevator.lua") include("modules/sh_sound.lua") -------------------------------------------------- -- -------------------------------------------------- function GM:InitPostEntity() self.spawnPoints = {lounge = {}} local spawns = ents.FindByClass("info_player_spawn") for k, entity in pairs(spawns) do if (entity.lounge) then table.insert(self.spawnPoints.lounge, entity) else if (!entity.minigames) then table.insert(self.spawnPoints, entity) end end end local slotMachines = ents.FindByClass("prop_physics_multiplayer") for k, entity in pairs(slotMachines) do if (IsValid(entity)) then local model = string.lower(entity:GetModel()) if (model == "models/sam/slotmachine.mdl") then local position, angles = entity:GetPos(), entity:GetAngles() local slotMachine = ents.Create("slot_machine") slotMachine:SetPos(position) slotMachine:SetAngles(angles) slotMachine:Spawn() entity:Remove() end end end timer.Simple(5,function() socket.SetupHost("192.168.1.152", 40000) timer.Simple(2,function() socket.AddServer("192.168.1.152", 40001) end) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerInitialSpawn(player) self.BaseClass:PlayerInitialSpawn(player) player:SetTeam(TEAM_READY) player:SetCollideWithTeammates(true) player:SetModel("models/player/group01/male_01.mdl") timer.Simple(0.4,function() for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do SS.Lobby.LeaderBoard.Network(i, player) end SS.Lobby.Minigame:UpdateScreen(player) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSpawn(player) self.BaseClass:PlayerSpawn(player) player:SetJumpPower(205) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerLoadout(player) player:StripWeapons() player:RemoveAllAmmo() SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player) end -------------------------------------------------- -- -------------------------------------------------- function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable ) local Pos = spawnpointent:GetPos() -- Note that we're searching the default hull size here for a player in the way of our spawning. -- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job -- (HL2DM kills everything within a 128 unit radius) local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) ) if ( pl:Team() == TEAM_SPECTATOR ) then return true end local Blockers = 0 for k, v in pairs( Ents ) do if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then Blockers = Blockers + 1 if ( bMakeSuitable ) then v:Kill() end end end if ( bMakeSuitable ) then return true end if ( Blockers > 0 ) then return false end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSelectSpawn(player, minigame) local spawnPoint = self.spawnPoints.lounge if (player:Team() > TEAM_READY) then if (minigame) then spawnPoint = minigame:GetSpawnPoints(player) else spawnPoint = self.spawnPoints end end for i = 1, #spawnPoint do local entity = spawnPoint[i] local suitAble = self:IsSpawnpointSuitable(player, entity, false) if (suitAble) then return entity end end -- IS THIS SHIT SPAWNING THE PLAYER AT THE QUEUE AGAIN???? spawnPoint = table.Random(spawnPoint) return spawnPoint end -------------------------------------------------- -- -------------------------------------------------- function GM:KeyPress(player, key) if (key == IN_USE) then local trace = player:EyeTrace(84) if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then local canSlap = player:CanSlap(trace.Entity) if (canSlap) then player:Slap(trace.Entity) end end end SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key) end -------------------------------------------------- -- -------------------------------------------------- function GM:DoPlayerDeath(victim, inflictor, dmginfo) SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo) return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo) end -------------------------------------------------- -- -------------------------------------------------- function GM:CanPlayerSuicide(player) local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player) if (bool != nil) then return bool end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:EntityKeyValue(entity, key, value) if (IsValid(entity)) then local class = entity:GetClass() if (class == "func_door" and key == "hammerid") then entity.id = tonumber(value) end end end -------------------------------------------------- -- -------------------------------------------------- function GM:AllowPlayerPickup( ply, object ) return false end -- dev concommand.Add("poo",function() RunConsoleCommand("bot") timer.Simple(0,function() for k, bot in pairs(player.GetBots()) do bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE)) bot:SetPos(Vector(-607.938110, -447.018799, 16.031250)) bot:Freeze(true) end end) end)
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_scoreboard.lua") AddCSLuaFile("modules/sh_link.lua") AddCSLuaFile("modules/cl_link.lua") AddCSLuaFile("modules/sh_chairs.lua") AddCSLuaFile("modules/cl_chairs.lua") AddCSLuaFile("modules/cl_worldpicker.lua") AddCSLuaFile("modules/sh_minigame.lua") AddCSLuaFile("modules/cl_minigame.lua") AddCSLuaFile("modules/cl_worldpanel.lua") AddCSLuaFile("modules/sh_leaderboard.lua") AddCSLuaFile("modules/cl_leaderboard.lua") AddCSLuaFile("modules/sh_sound.lua") include("shared.lua") include("player_class/player_lobby.lua") include("player_extended.lua") include("modules/sv_socket.lua") include("modules/sh_link.lua") include("modules/sv_link.lua") include("modules/sh_chairs.lua") include("modules/sv_chairs.lua") include("modules/sv_worldpicker.lua") include("modules/sh_minigame.lua") include("modules/sv_minigame.lua") include("modules/sh_leaderboard.lua") include("modules/sv_leaderboard.lua") include("modules/sv_elevator.lua") include("modules/sh_sound.lua") -------------------------------------------------- -- -------------------------------------------------- function GM:InitPostEntity() self.spawnPoints = {lounge = {}} local spawns = ents.FindByClass("info_player_spawn") for k, entity in pairs(spawns) do if (entity.lounge) then table.insert(self.spawnPoints.lounge, entity) else if (!entity.minigames) then table.insert(self.spawnPoints, entity) end end end local slotMachines = ents.FindByClass("prop_physics_multiplayer") for k, entity in pairs(slotMachines) do if (IsValid(entity)) then local model = string.lower(entity:GetModel()) if (model == "models/sam/slotmachine.mdl") then local position, angles = entity:GetPos(), entity:GetAngles() local slotMachine = ents.Create("slot_machine") slotMachine:SetPos(position) slotMachine:SetAngles(angles) slotMachine:Spawn() entity:Remove() end end end timer.Simple(5,function() socket.SetupHost("192.168.1.152", 40000) timer.Simple(2,function() socket.AddServer("192.168.1.152", 40001) end) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerInitialSpawn(player) self.BaseClass:PlayerInitialSpawn(player) player:SetTeam(TEAM_READY) player:SetCollideWithTeammates(true) player:SetModel("models/player/group01/male_01.mdl") timer.Simple(0.4,function() for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do SS.Lobby.LeaderBoard.Network(i, player) end SS.Lobby.Minigame:UpdateScreen(player) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSpawn(player) self.BaseClass:PlayerSpawn(player) player:SetJumpPower(205) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerLoadout(player) player:StripWeapons() player:RemoveAllAmmo() SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player) end -------------------------------------------------- -- -------------------------------------------------- function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable ) local Pos = spawnpointent:GetPos() -- Note that we're searching the default hull size here for a player in the way of our spawning. -- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job -- (HL2DM kills everything within a 128 unit radius) local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) ) if ( pl:Team() == TEAM_SPECTATOR ) then return true end local Blockers = 0 for k, v in pairs( Ents ) do if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then Blockers = Blockers + 1 if ( bMakeSuitable ) then v:Kill() end end end if ( bMakeSuitable ) then return true end if ( Blockers > 0 ) then return false end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSelectSpawn(player, minigame) local spawnPoint = self.spawnPoints.lounge if (player:Team() > TEAM_READY) then if (minigame) then spawnPoint = minigame:GetSpawnPoints(player) else spawnPoint = self.spawnPoints end end for i = 1, #spawnPoint do local entity = spawnPoint[i] local suitAble = self:IsSpawnpointSuitable(player, entity, false) if (suitAble) then return entity end end -- IS THIS SHIT SPAWNING THE PLAYER AT THE QUEUE AGAIN???? spawnPoint = table.Random(spawnPoint) return spawnPoint end -------------------------------------------------- -- -------------------------------------------------- function GM:KeyPress(player, key) if (key == IN_USE) then local trace = player:EyeTrace(84) if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then local canSlap = player:CanSlap(trace.Entity) if (canSlap) then player:Slap(trace.Entity) end end end SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key) end -------------------------------------------------- -- -------------------------------------------------- function GM:DoPlayerDeath(victim, inflictor, dmginfo) SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo) return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo) end -------------------------------------------------- -- -------------------------------------------------- function GM:CanPlayerSuicide(player) local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player) if (bool != nil) then return bool end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:EntityKeyValue(entity, key, value) if (IsValid(entity)) then local class = entity:GetClass() if (class == "func_door" and key == "hammerid") then entity.id = tonumber(value) end end end -------------------------------------------------- -- -------------------------------------------------- function GM:AllowPlayerPickup( ply, object ) return false end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerCanPickupItem( player, entity ) return false end -- dev concommand.Add("poo",function() RunConsoleCommand("bot") timer.Simple(0,function() for k, bot in pairs(player.GetBots()) do bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE)) bot:SetPos(Vector(-607.938110, -447.018799, 16.031250)) bot:Freeze(true) end end) end)
Hopefully fixed it this time
Hopefully fixed it this time
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
0eeda0b8f5ee17d4cb608ccab56da578e21ae324
testserver/item/keys.lua
testserver/item/keys.lua
require("base.keys") require("base.common") require("base.lookat") module("item.keys", package.seeall) -- UPDATE common SET com_script='item.keys' WHERE com_itemid IN (2121,2122,2123,2124,2141,2144,2145,2161,2556,2558,3054,3055,3056); function UseItem(User, SourceItem) local DoorItem = base.common.GetFrontItem( User ); if SourceItem:getData("prisonKeyOf") ~= "" then -- sentence char to forced labour SentenceCharacter(User,SourceItem) return end if base.keys.CheckKey(SourceItem,DoorItem) then if base.keys.LockDoor(DoorItem) then base.common.InformNLS(User,"Du sperrst die Tr ab.","You lock the door."); elseif base.keys.UnlockDoor(DoorItem) then base.common.InformNLS(User,"Du sperrst die Tr auf.","You unlock the door."); end else base.common.InformNLS(User,"Der Schlssel passt hier nicht.","The key doesn't fit here."); end end function SentenceCharacter(User,SourceItem) if User:isAdmin() == false then return -- for now only GMs are supposed to use the keys end local myTown = SourceItem:getData("prisonKeyOf") local townId if myTown == "Cadomyr" then townId = 1 elseif myTown == "Runewick" then townId = 2 elseif myTown == "Galmair" then townId = 3 else User:inform("This prison key does not belong to any town.") return end local callback = function(dialog) if not dialog:getSuccess() then User:inform("Abortion. No one was sentenced to anything.") return else local myString = dialog:getInput() local myPrisonerId local myPrisonerName local workLoad local allFound = false local a; local b if string.find(myString,"(%d+) (%d+)") then a,b,myPrisonerId,workLoad = string.find(myString,"(%d+) (%d+)") myPrisonerId = tonumber(myPrisonerId); workLoad = tonumber(workLoad) allFound = true elseif string.find(myString,"(%d+)") then a,b,workLoad = string.find(myString,"(%d+)") workLoad = tonumber(workLoad) if a-2 > 1 then myPrisonerName=string.sub (myString, 1,a-2) allFound = true end end if allFound then local onlineChars = world:getPlayersOnline() local thePrisoner for i=1,#onlineChars do local checkChar = onlineChars[i] if myPrisonerId then if checkChar.id == myPrisonerId then thePrisoner = checkChar break end else if checkChar.name == myPrisonerName then thePrisoner = checkChar break end end end if not thePrisoner then User:inform("Character has not been found.") else thePrisoner:setQuestProgress(25,workLoad) thePrisoner:setQuestProgress(26,townId) world:gfx(41,thePrisoner.pos); world:makeSound(1,thePrisoner.pos); thePrisoner:warp( position(-495,-484,-40) ) world:gfx(41,thePrisoner.pos) local callbackLabour = function(dialogLabour) end if thePrisoner:getPlayerLanguage() == 0 then dialogLabour = MessageDialog("Arbeitslager","Du wurdest verurteilt "..workLoad.." Rohstoffe aus der Mine abzubauen. Erflle deine Strafe und du darfst wieder gehen. Spitzhacke und Essen bekommst du beim Aufseher.", callbackLabour) else dialogLabour = MessageDialog("Labour camp" ,"You have been sentenced to collect "..workLoad.." resources in the mine. If you have served your sentence, you are free to go. You can get a pick-axe and food from the guard.", callbackLabour) end thePrisoner:requestMessageDialog(dialogLabour) User:createItem(2763,1,777,nil) end else User:inform("You haven't put in all necessary informations.") end end end local dialog = InputDialog("Sentence to forced labour","Insert: [Name|ID] [workload] Example: John Doe 300",false,255,callback) User:requestInputDialog(dialog) end function LookAtItem(User,Item) world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) ) end function MoveItemBeforeMove(User, SourceItem, TargetItem) if ((TargetItem.data~=3001) and (TargetItem.data~=3002)) then return true; end if (User:getRace() == 1) then return true; end if User:isAdmin() then return true; end if (TargetItem:getType()~=3) then base.common.InformNLS(User, "Der Schlssel rutscht dir seltsamerweise aus der Hand.", "The key slips out of your hand for a strange reason."); return false; end return true; end function MoveItemAfterMove( User, SourceItem, TargetItem ) return true; end
require("base.keys") require("base.common") require("base.lookat") module("item.keys", package.seeall) -- UPDATE common SET com_script='item.keys' WHERE com_itemid IN (2121,2122,2123,2124,2141,2144,2145,2161,2556,2558,3054,3055,3056); function UseItem(User, SourceItem) local DoorItem = base.common.GetFrontItem( User ); if SourceItem:getData("prisonKeyOf") ~= "" then -- sentence char to forced labour SentenceCharacter(User,SourceItem) return end if base.keys.CheckKey(SourceItem,DoorItem) then if base.keys.LockDoor(DoorItem) then base.common.InformNLS(User,"Du sperrst die Tr ab.","You lock the door."); elseif base.keys.UnlockDoor(DoorItem) then base.common.InformNLS(User,"Du sperrst die Tr auf.","You unlock the door."); end else base.common.InformNLS(User,"Der Schlssel passt hier nicht.","The key doesn't fit here."); end end function SentenceCharacter(User,SourceItem) if User:isAdmin() == false then local charname = User.name; if not charname == "Elvaine Morgan" and not charname == "Valerio Guilianni" and not charname == "Rosaline Edwards" and not charname == "Reflux" then return; -- for now only GMs are supposed to use the keys end; end; local myTown = SourceItem:getData("prisonKeyOf") local townId if myTown == "Cadomyr" then townId = 1 elseif myTown == "Runewick" then townId = 2 elseif myTown == "Galmair" then townId = 3 else User:inform("This prison key does not belong to any town.") return end local callback = function(dialog) if not dialog:getSuccess() then User:inform("Abortion. No one was sentenced to anything.") return else local myString = dialog:getInput() local myPrisonerId local myPrisonerName local workLoad local allFound = false local a; local b if string.find(myString,"(%d+) (%d+)") then a,b,myPrisonerId,workLoad = string.find(myString,"(%d+) (%d+)") myPrisonerId = tonumber(myPrisonerId); workLoad = tonumber(workLoad) allFound = true elseif string.find(myString,"(%d+)") then a,b,workLoad = string.find(myString,"(%d+)") workLoad = tonumber(workLoad) if a-2 > 1 then myPrisonerName=string.sub (myString, 1,a-2) allFound = true end end if allFound then local onlineChars = world:getPlayersOnline() local thePrisoner for i=1,#onlineChars do local checkChar = onlineChars[i] if myPrisonerId then if checkChar.id == myPrisonerId then thePrisoner = checkChar break end else if checkChar.name == myPrisonerName then thePrisoner = checkChar break end end end if not thePrisoner then User:inform("Character has not been found.") else thePrisoner:setQuestProgress(25,workLoad) thePrisoner:setQuestProgress(26,townId) world:gfx(41,thePrisoner.pos); world:makeSound(1,thePrisoner.pos); thePrisoner:warp( position(-495,-484,-40) ) world:gfx(41,thePrisoner.pos) local callbackLabour = function(dialogLabour) end if thePrisoner:getPlayerLanguage() == 0 then dialogLabour = MessageDialog("Arbeitslager","Du wurdest verurteilt "..workLoad.." Rohstoffe aus der Mine abzubauen. Erflle deine Strafe und du darfst wieder gehen. Spitzhacke und Essen bekommst du beim Aufseher.", callbackLabour) else dialogLabour = MessageDialog("Labour camp" ,"You have been sentenced to collect "..workLoad.." resources in the mine. If you have served your sentence, you are free to go. You can get a pick-axe and food from the guard.", callbackLabour) end thePrisoner:requestMessageDialog(dialogLabour) User:createItem(2763,1,777,nil) end else User:inform("You haven't put in all necessary informations.") end end end local dialog = InputDialog("Sentence to forced labour","Insert: [Name|ID] [workload] Example: John Doe 300",false,255,callback) User:requestInputDialog(dialog) end function LookAtItem(User,Item) world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) ) end function MoveItemBeforeMove(User, SourceItem, TargetItem) if ((TargetItem.data~=3001) and (TargetItem.data~=3002)) then return true; end if (User:getRace() == 1) then return true; end if User:isAdmin() then return true; end if (TargetItem:getType()~=3) then base.common.InformNLS(User, "Der Schlssel rutscht dir seltsamerweise aus der Hand.", "The key slips out of your hand for a strange reason."); return false; end return true; end function MoveItemAfterMove( User, SourceItem, TargetItem ) return true; end
Fixing GMs not being able to use keys
Fixing GMs not being able to use keys
Lua
agpl-3.0
LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
70513faf55bf4069295200b86b22d806679a34b0
mods/solarmana/init.lua
mods/solarmana/init.lua
--[[ Solar Mana mod [solarmana] ========================== A mana regeneration controller: only regenerate mana in sunlight. Copyright (C) 2015 Ben Deutsch <ben@bendeutsch.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ]] local time_total_regen_check = 0.5 local time_next_regen_check = time_total_regen_check -- TODO: make this globally accessible local mana_from_node = { ['default:goldblock'] = 5, ['runes:rune_heal_minor'] = 1, ['runes:rune_heal_medium'] = 3, ['runes:rune_heal_major'] = 8, ['default:wood'] = 1, ['default:junglewood'] = 1, ['default:pinewood'] = 1, ['group:wood'] = 1, } -- just for debugging: see below local time_total_mana_reset = 10.0 local time_next_mana_reset = time_total_mana_reset minetest.register_globalstep(function(dtime) -- We do not care if this does not run as often as possible, -- as all it does is change the regeneration to a fixed number time_next_regen_check = time_next_regen_check - dtime if time_next_regen_check < 0.0 then time_next_regen_check = time_total_regen_check for _,player in ipairs(minetest.get_connected_players()) do local name = player:get_player_name() local pos = player:getpos() local pos_y = pos.y -- the middle of the block with the player's head pos.y = math.floor(pos_y) + 1.5 local node = minetest.get_node(pos) -- Currently uses 'get_node_light' to determine whether -- a node is "in sunlight". local light_day = minetest.get_node_light(pos, 0.5) local light_night = minetest.get_node_light(pos, 0.0) local light_now = minetest.get_node_light(pos) or 0 local regen_to = 0 -- simplest version checks for "full sunlight now" if light_now >= 15 then regen_to = 1 end -- we can get a bit more lenience by testing whether -- * a node is "affected by sunlight" (day > night) -- * the node is "bright enough now" -- However: you could deny yourself mana regeneration -- with torches :-/ --[[ if light_day > light_night and light_now > 12 then regen_to = 1 end --]] -- next, check the block we're standing on. pos.y = math.floor(pos_y) - 0.5 node = minetest.get_node(pos) if mana_from_node[node.name] then regen_to = math.max(regen_to, mana_from_node[node.name]) --print("Regen to "..regen_to.." : "..node.name) end for key, value in pairs(mana_from_node) do if key:split(":")[1] == "group" then local groupname = key:split(":")[2] if minetest.get_node_group(node.name, groupname) > 0 then regen_to = math.max(regen_to, value) -- We get the greater one (if the node is part of 2 or more groups) end end end mana.setregen(name, regen_to) --print("Regen to "..regen_to.." : "..light_day.."/"..light_now.."/"..light_night) end end --[[ Comment this in for testing if you have no mana sink time_next_mana_reset = time_next_mana_reset - dtime if time_next_mana_reset < 0.0 then time_next_mana_reset = time_total_mana_reset mana.set('singleplayer', 100) print("Resetting mana") end --]] end)
--[[ Solar Mana mod [solarmana] ========================== A mana regeneration controller: only regenerate mana in sunlight. Copyright (C) 2015 Ben Deutsch <ben@bendeutsch.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ]] local time_total_regen_check = 0.5 local time_next_regen_check = time_total_regen_check -- TODO: make this globally accessible local mana_from_node = { ['default:goldblock'] = 5, ['runes:rune_heal_minor'] = 1, ['runes:rune_heal_medium'] = 3, ['runes:rune_heal_major'] = 8, ['default:wood'] = 1, ['default:junglewood'] = 1, ['default:pinewood'] = 1, ['group:wood'] = 1, } -- just for debugging: see below local time_total_mana_reset = 10.0 local time_next_mana_reset = time_total_mana_reset minetest.register_globalstep(function(dtime) -- We do not care if this does not run as often as possible, -- as all it does is change the regeneration to a fixed number time_next_regen_check = time_next_regen_check - dtime if time_next_regen_check < 0.0 then time_next_regen_check = time_total_regen_check for _,player in ipairs(minetest.get_connected_players()) do local name = player:get_player_name() local pos = player:getpos() local pos_y = pos.y -- the middle of the block with the player's head pos.y = math.floor(pos_y) + 1.5 local node = minetest.get_node(pos) -- Currently uses 'get_node_light' to determine whether -- a node is "in sunlight". local light_day = minetest.get_node_light(pos, 0.5) local light_night = minetest.get_node_light(pos, 0.0) local light_now = minetest.get_node_light(pos) or 0 local regen_to = 0 -- simplest version checks for "full sunlight now" if light_now >= 15 then regen_to = 1 end -- we can get a bit more lenience by testing whether -- * a node is "affected by sunlight" (day > night) -- * the node is "bright enough now" -- However: you could deny yourself mana regeneration -- with torches :-/ --[[ if light_day > light_night and light_now > 12 then regen_to = 1 end --]] -- next, check the block we're standing on. pos.y = math.floor(pos_y) - 0.5 node = minetest.get_node(pos) if mana_from_node[node.name] then regen_to = math.max(regen_to, mana_from_node[node.name]) --print("Regen to "..regen_to.." : "..node.name) end for key, value in pairs(mana_from_node) do if key:split(":")[1] == "group" then local groupname = key:split(":")[2] if minetest.get_node_group(node.name, groupname) > 0 then regen_to = math.max(regen_to, value) -- We get the greater one (if the node is part of 2 or more groups) end end end mana.setregen(name, regen_to) --print("Regen to "..regen_to.." : "..light_day.."/"..light_now.."/"..light_night) end end --[[ Comment this in for testing if you have no mana sink time_next_mana_reset = time_next_mana_reset - dtime if time_next_mana_reset < 0.0 then time_next_mana_reset = time_total_mana_reset mana.set('singleplayer', 100) print("Resetting mana") end --]] end)
Updated solarmana_add - Updated solarmana_add/README.txt - Fixed indentation for groups handler
Updated solarmana_add - Updated solarmana_add/README.txt - Fixed indentation for groups handler
Lua
unlicense
crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server
4bc00468882b3a25ba8b41cd2c0d3a2fedcc899d
check/filesystem.lua
check/filesystem.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 fmt = require('string').format local upper = require('string').upper local BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local table = require('table') local os = require('os') local FileSystemCheck = BaseCheck:extend() local METRICS = { 'total', 'free', 'used', 'avail', 'files', 'free_files', } local UNITS = { total = 'kilobytes', free = 'kilobytes', used = 'kilobytes', avail = 'kilobytes', files = 'files', free_files = 'free_files' } function FileSystemCheck:initialize(params) BaseCheck.initialize(self, params) if params.details == nil then params.details = {} end self.mount_point = params.details.target and params.details.target or nil end function FileSystemCheck:getType() return 'agent.filesystem' end function FileSystemCheck:getTargets(callback) local s = sigar:new() local fses = s:filesystems() local info, fs local targets = {} for i=1, #fses do fs = fses[i] info = fs:info() table.insert(targets, info['dir_name']) end callback(nil, targets) end function FileSystemCheck:flattenTargetsToString() local s = "" self:getTargets(function (err, targets) for i=1, #targets do if i ~= 1 then s = s .. "," end s = s .. targets[i] end end) return s end -- Dimension key is the mount point name, e.g. /, /home function FileSystemCheck:run(callback) -- Perform Check local s = sigar:new() local fses = s:filesystems() local checkResult = CheckResult:new(self, {}) local fs, info, usage, value local found = false if self.mount_point == nil then checkResult:setError('Missing target parameter, available: %s', self:flattenTargetsToString()) callback(checkResult) return end for i=1, #fses do fs = fses[i] info = fs:info() -- Search for the mount point we want. TODO: modify sigar bindings to -- let us do a lookup from this. if os.type() == "win32" then if upper(info['dir_name']) == upper(self.mount_point) then found = true end else if info['dir_name'] == self.mount_point then found = true end end if found then usage = fs:usage() if usage then for _, key in pairs(METRICS) do value = usage[key] if value ~= nil then checkResult:addMetric(key, nil, nil, value, UNITS[key]) end end end -- Return Result callback(checkResult) return end end checkResult:setError(fmt('No filesystem mounted at %s, available: %s', self.mount_point, self:flattenTargetsToString())) callback(checkResult) end local exports = {} exports.FileSystemCheck = FileSystemCheck 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 fmt = require('string').format local upper = require('string').upper local BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local table = require('table') local os = require('os') local FileSystemCheck = BaseCheck:extend() local METRICS = { 'total', 'free', 'used', 'avail', 'files', 'free_files', } local UNITS = { total = 'kilobytes', free = 'kilobytes', used = 'kilobytes', avail = 'kilobytes', files = 'files', free_files = 'free_files', options = 'options' } function FileSystemCheck:initialize(params) BaseCheck.initialize(self, params) if params.details == nil then params.details = {} end self.mount_point = params.details.target and params.details.target or nil end function FileSystemCheck:getType() return 'agent.filesystem' end function FileSystemCheck:getTargets(callback) local s = sigar:new() local fses = s:filesystems() local info, fs local targets = {} for i=1, #fses do fs = fses[i] info = fs:info() table.insert(targets, info['dir_name']) end callback(nil, targets) end function FileSystemCheck:flattenTargetsToString() local s = "" self:getTargets(function (err, targets) for i=1, #targets do if i ~= 1 then s = s .. "," end s = s .. targets[i] end end) return s end -- Dimension key is the mount point name, e.g. /, /home function FileSystemCheck:run(callback) -- Perform Check local s = sigar:new() local fses = s:filesystems() local checkResult = CheckResult:new(self, {}) local fs, info, usage, value local found = false if self.mount_point == nil then checkResult:setError('Missing target parameter, available: %s', self:flattenTargetsToString()) callback(checkResult) return end for i=1, #fses do fs = fses[i] info = fs:info() -- Search for the mount point we want. TODO: modify sigar bindings to -- let us do a lookup from this. if os.type() == "win32" then if upper(info['dir_name']) == upper(self.mount_point) then found = true end else if info['dir_name'] == self.mount_point then found = true end end if found then usage = fs:usage() if usage then for _, key in pairs(METRICS) do value = usage[key] if value ~= nil then checkResult:addMetric(key, nil, nil, value, UNITS[key]) end end end checkResult:addMetric('options', nil, nil, info['options'], UNITS['options']) -- Return Result callback(checkResult) return end end checkResult:setError(fmt('No filesystem mounted at %s, available: %s', self.mount_point, self:flattenTargetsToString())) callback(checkResult) end local exports = {} exports.FileSystemCheck = FileSystemCheck return exports
fixes(filesystem): add options for filesystem
fixes(filesystem): add options for filesystem
Lua
apache-2.0
christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
9d568d382784a16265744c8d3db77d1d4eaa5167
core/frame.lua
core/frame.lua
local framePrototype = { next= nil, id= nil, previous= nil, balanced= 0 }; function framePrototype:top() if (type(self._top) == "function" ) then return self:_top() else return self._top end end function framePrototype:left () if (type(self._left) == "function" ) then return self:_left() else return self._left end end function framePrototype:right () if (type(self._right) == "function") then return self:_right() end if (not self._right and self._width) then return self:left() + self:width() end return self._right end function framePrototype:bottom () if (type(self._bottom) == "function" ) then return self:_bottom() end if (not self._bottom and self._height) then return self:top() + self:height() end return self._bottom end function framePrototype:width () if (type(self._width) == "function" ) then return self:_width() end if (not self._width) then return self:right() - self:left() end return self._width end function framePrototype:height() if (type(self._height) == "function" ) then return self:_height() end if (self._height) then return self._height end if (self._bottom and self._top) then return self:bottom() - self:top() end return Infinity end SILE.newFrame = function(spec) local frame = std.tree.clone(framePrototype) local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} for method, dimension in pairs(dims) do if spec[method] then if not(type(spec[method]) == "function") then local old = spec[method] -- Closure me harder if type(old) == "string" and string.find(old, "%%") then -- Defer relative calculations until page size is known spec[method] = function() return SILE.toPoints(old, "%", dimension) end else spec[method] = SILE.toPoints(spec[method]) end end frame["_"..method] = spec[method] end end return frame end SILE.getFrame = function(id) return SILE.documentState.thisPageTemplate.frames[id] end SILE._frameParser = require("core/frameparser") SILE.parseComplexFrameDimension = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser return SILE._frameParser:match(d); end
local framePrototype = std.object { next= nil, id= nil, previous= nil, balanced= 0 }; function framePrototype:top() if (type(self._top) == "function" ) then return self:_top() else return self._top end end function framePrototype:left () if (type(self._left) == "function" ) then return self:_left() else return self._left end end function framePrototype:right () if (type(self._right) == "function") then return self:_right() end if (not self._right and self._width) then return self:left() + self:width() end return self._right end function framePrototype:bottom () if (type(self._bottom) == "function" ) then return self:_bottom() end if (not self._bottom and self._height) then return self:top() + self:height() end return self._bottom end function framePrototype:width () if (type(self._width) == "function" ) then return self:_width() end if (not self._width) then return self:right() - self:left() end return self._width end function framePrototype:height() if (type(self._height) == "function" ) then return self:_height() end if (self._height) then return self._height end if (self._bottom and self._top) then return self:bottom() - self:top() end return Infinity end SILE.newFrame = function(spec) local frame = framePrototype {} local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} for method, dimension in pairs(dims) do if spec[method] then if not(type(spec[method]) == "function") then local old = spec[method] -- Closure me harder if type(old) == "string" and string.find(old, "%%") then -- Defer relative calculations until page size is known spec[method] = function() return SILE.toPoints(old, "%", dimension) end else spec[method] = SILE.toPoints(spec[method]) end end frame["_"..method] = spec[method] end end frame.id = spec.id frame.next = spec.next return frame end SILE.getFrame = function(id) return SILE.documentState.thisPageTemplate.frames[id] end SILE._frameParser = require("core/frameparser") SILE.parseComplexFrameDimension = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser return SILE._frameParser:match(d); end
Use objects, some fixes.
Use objects, some fixes.
Lua
mit
simoncozens/sile,neofob/sile,anthrotype/sile,simoncozens/sile,shirat74/sile,shirat74/sile,alerque/sile,anthrotype/sile,simoncozens/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,neofob/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,shirat74/sile,neofob/sile,neofob/sile,alerque/sile,shirat74/sile,Nathan22Miles/sile,alerque/sile,anthrotype/sile,Nathan22Miles/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,simoncozens/sile,anthrotype/sile,alerque/sile
152d2ab697f7f76c942445abd66f2c515e5f187a
core/xmlhandlers.lua
core/xmlhandlers.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. -- require "util.stanza" local st = stanza; local tostring = tostring; local pairs = pairs; local ipairs = ipairs; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmlhandlers"); local error = error; module "xmlhandlers" local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; } local xmlns_streams = "http://etherx.jabber.org/streams"; local ns_separator = "\1"; local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$"; function init_xmlhandlers(session, stream_callbacks) local ns_stack = { "" }; local curr_tag; local chardata = {}; local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_ns = stream_callbacks.stream_ns or xmlns_streams; local stream_tag = stream_ns..ns_separator..(stream_callbacks.stream_tag or "stream"); local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error"); local stream_default_ns = stream_callbacks.default_ns; local stanza function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match(ns_pattern); if nm ~= "" then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); curr_tag = stanza; else -- we are inside a stanza, so add a tag attr.xmlns = nil; if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if not stanza then if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end else cb_error(session, "parse-error", "unexpected-element-close", name); end stanza, chardata = nil, {}; return; end if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza if #stanza.last_add == 0 then if tagname ~= stream_error_tag then cb_handlestanza(session, stanza); else cb_error(session, "stream-error", stanza); end stanza = nil; else stanza:up(); end end return xml_handlers; end return init_xmlhandlers;
-- 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. -- require "util.stanza" local st = stanza; local tostring = tostring; local pairs = pairs; local ipairs = ipairs; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmlhandlers"); local error = error; module "xmlhandlers" local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; }; local xmlns_streams = "http://etherx.jabber.org/streams"; local ns_separator = "\1"; local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$"; function init_xmlhandlers(session, stream_callbacks) local ns_stack = { "" }; local curr_tag; local chardata = {}; local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function(session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_ns = stream_callbacks.stream_ns or xmlns_streams; local stream_tag = stream_ns..ns_separator..(stream_callbacks.stream_tag or "stream"); local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error"); local stream_default_ns = stream_callbacks.default_ns; local stanza; function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match(ns_pattern); if nm ~= "" then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); curr_tag = stanza; else -- we are inside a stanza, so add a tag attr.xmlns = nil; if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if not stanza then if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end else cb_error(session, "parse-error", "unexpected-element-close", name); end stanza, chardata = nil, {}; return; end if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza if #stanza.last_add == 0 then if tagname ~= stream_error_tag then cb_handlestanza(session, stanza); else cb_error(session, "stream-error", stanza); end stanza = nil; else stanza:up(); end end return xml_handlers; end return init_xmlhandlers;
xmlhandlers: Fixed indentation and added some semicolons.
xmlhandlers: Fixed indentation and added some semicolons.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
f79a28760765c4d91c0e22bc721a4a2ab662f6a6
timeline_0.0.1/control.lua
timeline_0.0.1/control.lua
require "defines" require "interface" script.on_init(function() global.forces = global.forces or {} global.players = global.players or {} initPlayers() end) script.on_event(defines.events.on_player_created, function(event) playerCreated(event) end) script.on_event(defines.events.on_built_entity, function(event) local player = game.players[event.player_index] local force = player.force markTimeline(force, "built-entity", event.created_entity.name) end) function markTimeline(force, name, params) local mark = { name = name, param = params, tick = game.tick } local forceData = global.forces[force.name] if not forceData then forceData = {} global.forces[force.name] = forceData end if not forceData.marks then forceData.marks = {} end if not forceData.marks[name] then forceData.marks[name] = {} end forceData.allMarks = forceData.allMarks or {} local marks = forceData.marks[name] if marks[params] then -- timeline was already marked return marks[params] end -- mark timeline marks[params] = mark table.insert(forceData.allMarks, mark) for i, player in pairs(force.players) do player.print("Timeline: " .. mark.name .. " - " .. mark.param .. " at " .. mark.tick) end end function initPlayers() for _, player in ipairs(game.players) do initPlayer(player) end end function playerCreated(event) local player = game.players[event.player_index] initPlayer(player) end function initPlayer(player) player.gui.top.add { type = "button", name = "timeline", caption = "Timeline" } end script.on_event(defines.events.on_gui_click, function(event) local element = event.element local playerIndex = event.player_index local player = game.players[playerIndex] local force = player.force if element.name == "timeline" then showTimeline(player) end if element.name == "hideTimeline" then local frame = player.gui.center.timelineFrame if frame then frame.destroy() return end end if element.name == "nextMark" then nextMark(player) end end) function nextMark(player) if not global.players[player.index] then global.players[player.index] = { markIndex = 0 } end local marks = global.forces[player.force.name].allMarks local playerData = global.players[player.index] if playerData.markIndex <= 1 then playerData.markIndex = #marks else playerData.markIndex = playerData.markIndex - 1 end local showMark = marks[playerData.markIndex] player.gui.center.timelineFrame.currentMark.caption = showMark.name .. " - " .. showMark.param .. " - " .. showMark.tick end function showTimeline(player) local frame = player.gui.center.add { type = "frame", name = "timelineFrame", direction = "vertical" } frame.add { type = "label", name = "currentMark", caption = "current" } frame.add { type = "button", name = "nextMark", caption = "Next" } frame.add { type = "button", name = "hideTimeline", caption = "Hide" } nextMark(player) end
require "defines" require "interface" script.on_init(function() global.forces = global.forces or {} global.players = global.players or {} initPlayers() end) script.on_event(defines.events.on_player_created, function(event) playerCreated(event) end) script.on_event(defines.events.on_built_entity, function(event) local player = game.players[event.player_index] local force = player.force markTimeline(force, "built-entity", event.created_entity.name) end) function markTimeline(force, name, params) local mark = { name = name, param = params, tick = game.tick } local forceData = global.forces[force.name] if not forceData then forceData = {} global.forces[force.name] = forceData end if not forceData.marks then forceData.marks = {} end if not forceData.marks[name] then forceData.marks[name] = {} end forceData.allMarks = forceData.allMarks or {} local marks = forceData.marks[name] if marks[params] then -- timeline was already marked return marks[params] end -- mark timeline marks[params] = mark table.insert(forceData.allMarks, mark) for i, player in pairs(force.players) do player.print("Timeline: " .. mark.name .. " - " .. mark.param .. " at " .. mark.tick) end end function initPlayers() for _, player in ipairs(game.players) do initPlayer(player) end end function playerCreated(event) local player = game.players[event.player_index] initPlayer(player) end function initPlayer(player) player.gui.top.add { type = "button", name = "timeline", caption = "Timeline" } end script.on_event(defines.events.on_gui_click, function(event) local element = event.element local playerIndex = event.player_index local player = game.players[playerIndex] local force = player.force if element.name == "timeline" then showTimeline(player) end if element.name == "hideTimeline" then hideTimeline(player) end if element.name == "nextMark" then nextMark(player) end end) function nextMark(player) if not global.players[player.index] then global.players[player.index] = { markIndex = 0 } end local marks = global.forces[player.force.name].allMarks local playerData = global.players[player.index] if playerData.markIndex <= 1 then playerData.markIndex = #marks else playerData.markIndex = playerData.markIndex - 1 end local showMark = marks[playerData.markIndex] player.gui.center.timelineFrame.currentMark.caption = showMark.name .. " - " .. showMark.param .. " - " .. showMark.tick end function hideTimeline(player) local frame = player.gui.center.timelineFrame if frame then frame.destroy() return end end function showTimeline(player) if player.gui.center.timelineFrame then hideTimeline(player) return end local frame = player.gui.center.add { type = "frame", name = "timelineFrame", direction = "vertical" } frame.add { type = "label", name = "currentMark", caption = "current" } frame.add { type = "button", name = "nextMark", caption = "Next" } frame.add { type = "button", name = "hideTimeline", caption = "Hide" } nextMark(player) end
Fix crash when click Timeline button again by toggling the timeline
Fix crash when click Timeline button again by toggling the timeline
Lua
mit
Zomis/FactorioMods
1caa531b12cd8a9333035e3cf439842c27dc38e4
wyx/ui/Slot.lua
wyx/ui/Slot.lua
local Class = require 'lib.hump.class' local Frame = getClass 'wyx.ui.Frame' local setColor = love.graphics.setColor local draw = love.graphics.draw local colors = colors -- Slot -- A place to stick a StickyButton. local Slot = Class{name='Slot', inherits=Frame, function(self, ...) Frame.construct(self, ...) end } -- destructor function Slot:destroy() self._button = nil self:_clearVerificationCallback() self:_clearInsertCallback() self:_clearRemoveCallback() self._verificationCallback = nil self._insertCallback = nil self._removeCallback = nil self._hideTooltips = nil Frame.destroy(self) end -- verify that a button is allowed to be socketed in this Slot function Slot:verifyButton(button) local verified = true if self._verificationCallback then local args = self._verificationCallbackArgs if args then verified = self._verificationCallback(button, unpack(args)) else verified = self._verificationCallback(button) end end return verified end -- swap the given StickyButton with the current one function Slot:swap(button) verifyClass('wyx.ui.StickyButton', button) local otherSlot = button:getSlot() local otherButton local oldButton = self:remove() if not otherSlot:isEmpty() then otherButton = otherSlot:remove() end local verified, oldVerified = false, true if oldButton then oldVerified = otherSlot:verifyButton(oldButton) end verified = self:verifyButton(button) if verified and oldVerified then if oldButton then otherSlot:insert(oldButton, oldVerified) end self:insert(button, verified) else if oldButton then self:insert(oldButton, true) end otherSlot:insert(button, true) end end -- insert the given button function Slot:insert(button, verified) local inserted = false if not self._button then verified = verified or self:verifyButton(button) if verified then inserted = true self._button = button self:addChild(self._button, self._depth - 1) self._button:setSlot(self, self._hideTooltips) self._button:setCenter(self:getCenter()) if self._insertCallback then local args = self._insertCallbackArgs if args then self._insertCallback(button, unpack(args)) else self._insertCallback(button) end end end end return inserted end -- remove the current button function Slot:remove() local oldButton if self._button then self:removeChild(self._button) oldButton = self._button self._button = nil if self._removeCallback then local args = self._removeCallbackArgs if args then self._removeCallback(oldButton, unpack(args)) else self._removeCallback(oldButton) end end end return oldButton end function Slot:setVerificationCallback(func, ...) verify('function', func) self:_clearVerificationCallback() self._verificationCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._verificationCallbackArgs = {...} end end function Slot:setInsertCallback(func, ...) verify('function', func) self:_clearInsertCallback() self._insertCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._insertCallbackArgs = {...} end end function Slot:setRemoveCallback(func, ...) verify('function', func) self:_clearRemoveCallback() self._removeCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._removeCallbackArgs = {...} end end -- clear the verification callback function Slot:_clearVerificationCallback() self._verificationCallback = nil if self._verificationCallbackArgs then for k,v in pairs(self._verificationCallbackArgs) do self._verificationCallbackArgs[k] = nil end self._verificationCallbackArgs = nil end end -- clear the insert callback function Slot:_clearInsertCallback() self._insertCallback = nil if self._insertCallbackArgs then for k,v in pairs(self._insertCallbackArgs) do self._insertCallbackArgs[k] = nil end self._insertCallbackArgs = nil end end -- clear the remove callback function Slot:_clearRemoveCallback() self._removeCallback = nil if self._removeCallbackArgs then for k,v in pairs(self._removeCallbackArgs) do self._removeCallbackArgs[k] = nil end self._removeCallbackArgs = nil end end -- return true if the slot is empty function Slot:isEmpty() return self._button == nil end -- return the current button without removing it function Slot:getButton() return self._button end -- hide tooltips of attached buttons function Slot:hideTooltips() self._hideTooltips = true end function Slot:showTooltips() self._hideTooltips = false end -- override Frame:_drawForeground() to not draw if a button is in the slot function Slot:_drawForeground() if not self._button then Frame._drawForeground(self) end end -- the class return Slot
local Class = require 'lib.hump.class' local Frame = getClass 'wyx.ui.Frame' local setColor = love.graphics.setColor local draw = love.graphics.draw local colors = colors -- Slot -- A place to stick a StickyButton. local Slot = Class{name='Slot', inherits=Frame, function(self, ...) Frame.construct(self, ...) end } -- destructor function Slot:destroy() self._button = nil self:_clearVerificationCallback() self:_clearInsertCallback() self:_clearRemoveCallback() self._verificationCallback = nil self._insertCallback = nil self._removeCallback = nil self._hideTooltips = nil Frame.destroy(self) end -- verify that a button is allowed to be socketed in this Slot function Slot:verifyButton(button) local verified = true if self._verificationCallback then local args = self._verificationCallbackArgs if args then verified = self._verificationCallback(button, unpack(args)) else verified = self._verificationCallback(button) end end return verified end -- swap the given StickyButton with the current one function Slot:swap(button) verifyClass('wyx.ui.StickyButton', button) local otherSlot = button:getSlot() local myButtonOK = true local yourButtonOK = self:verifyButton(button) if self._button then myButtonOK = otherSlot:verifyButton(self._button) end if myButtonOK and yourButtonOK then local myButton = self:remove() local yourButton = otherSlot:remove() if myButton then otherSlot:insert(myButton, true) end self:insert(yourButton, true) end end -- insert the given button function Slot:insert(button, verified) local inserted = false if not self._button then verified = verified or self:verifyButton(button) if verified then inserted = true self._button = button self:addChild(self._button, self._depth - 1) self._button:setSlot(self, self._hideTooltips) self._button:setCenter(self:getCenter()) if self._insertCallback then local args = self._insertCallbackArgs if args then self._insertCallback(button, unpack(args)) else self._insertCallback(button) end end end end return inserted end -- remove the current button function Slot:remove() local oldButton if self._button then self:removeChild(self._button) oldButton = self._button self._button = nil if self._removeCallback then local args = self._removeCallbackArgs if args then self._removeCallback(oldButton, unpack(args)) else self._removeCallback(oldButton) end end end return oldButton end function Slot:setVerificationCallback(func, ...) verify('function', func) self:_clearVerificationCallback() self._verificationCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._verificationCallbackArgs = {...} end end function Slot:setInsertCallback(func, ...) verify('function', func) self:_clearInsertCallback() self._insertCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._insertCallbackArgs = {...} end end function Slot:setRemoveCallback(func, ...) verify('function', func) self:_clearRemoveCallback() self._removeCallback = func local numArgs = select('#', ...) if numArgs > 0 then self._removeCallbackArgs = {...} end end -- clear the verification callback function Slot:_clearVerificationCallback() self._verificationCallback = nil if self._verificationCallbackArgs then for k,v in pairs(self._verificationCallbackArgs) do self._verificationCallbackArgs[k] = nil end self._verificationCallbackArgs = nil end end -- clear the insert callback function Slot:_clearInsertCallback() self._insertCallback = nil if self._insertCallbackArgs then for k,v in pairs(self._insertCallbackArgs) do self._insertCallbackArgs[k] = nil end self._insertCallbackArgs = nil end end -- clear the remove callback function Slot:_clearRemoveCallback() self._removeCallback = nil if self._removeCallbackArgs then for k,v in pairs(self._removeCallbackArgs) do self._removeCallbackArgs[k] = nil end self._removeCallbackArgs = nil end end -- return true if the slot is empty function Slot:isEmpty() return self._button == nil end -- return the current button without removing it function Slot:getButton() return self._button end -- hide tooltips of attached buttons function Slot:hideTooltips() self._hideTooltips = true end function Slot:showTooltips() self._hideTooltips = false end -- override Frame:_drawForeground() to not draw if a button is in the slot function Slot:_drawForeground() if not self._button then Frame._drawForeground(self) end end -- the class return Slot
fix (and simplify) Slot:swap
fix (and simplify) Slot:swap
Lua
mit
scottcs/wyx
9e31e8a7957589f1891f68f01805d9ee13b5ad66
lua/job.lua
lua/job.lua
local _M = { _VERSION = "1.8.6" } local lock = require "resty.lock" local shdict = require "shdict" local JOBS = shdict.new("jobs") local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN, DEBUG = ngx.INFO, ngx.ERR, ngx.WARN, ngx.DEBUG local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local assert = assert local random = math.random local workers = ngx.worker.count() local function now() update_time() return ngx_now() end local main local function set_next_time(self, interval) interval = interval or self.interval JOBS:set(self.key .. ":next", now() + interval or self.interval) end local function get_next_time(self) return JOBS:get(self.key .. ":next") end --- @param #Job self local function run_job(self, delay, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() return false end return true end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then return run_job(self, 0.1, ...) end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(self, 0.1, ...) end return end if self:suspended() then run_job(self, 0.1, ...) mtx:unlock() return end if not self:running() then mtx:unlock() return self:finish(...) end if now() >= get_next_time(self) then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end set_next_time(self) end mtx:unlock() run_job(self, get_next_time(self) - now() + random(0, workers - 1) / 10, ...) end --- @type Job local job = {} -- public api --- @return #Job function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end --- @param #Job self function job:run(...) if not self:completed() then if not self:running() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) end set_next_time(self, 1) return assert(run_job(self, 0, ...)) end ngx_log(DEBUG, "job ", self.key, " already completed") return nil, "completed" end --- @param #Job self function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end --- @param #Job self function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end --- @param #Job self function job:stop() JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) ngx_log(INFO, "job ", self.key, " stopped") end --- @param #Job self function job:completed() return JOBS:get(self.key .. ":completed") == 1 end --- @param #Job self function job:running() return JOBS:get(self.key .. ":running") == 1 end --- @param #Job self function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end --- @param #Job self function job:finish(...) if self.finish_fn then self.finish_fn(...) end return true end --- @param #Job self function job:wait_for(other) tinsert(self.wait_others, other) end --- @param #Job self function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
local _M = { _VERSION = "1.8.6" } local lock = require "resty.lock" local shdict = require "shdict" local JOBS = shdict.new("jobs") local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN, DEBUG = ngx.INFO, ngx.ERR, ngx.WARN, ngx.DEBUG local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local assert = assert local random = math.random local workers = ngx.worker.count() local function now() update_time() return ngx_now() end local main local function set_next_time(self, interval) interval = interval or self.interval JOBS:set(self.key .. ":next", now() + interval or self.interval) end local function get_next_time(self) return JOBS:get(self.key .. ":next") or now() end --- @param #Job self local function run_job(self, delay, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() return false end return true end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then return run_job(self, 0.1, ...) end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(self, 0.1, ...) end return end if self:suspended() then run_job(self, 0.1, ...) mtx:unlock() return end if not self:running() then mtx:unlock() return self:finish(...) end if now() >= get_next_time(self) then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end set_next_time(self) end mtx:unlock() run_job(self, get_next_time(self) - now() + random(0, workers - 1) / 10, ...) end --- @type Job local job = {} -- public api --- @return #Job function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end --- @param #Job self function job:run(...) if not self:completed() then if not self:running() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) end return assert(run_job(self, 0, ...)) end ngx_log(DEBUG, "job ", self.key, " already completed") return nil, "completed" end --- @param #Job self function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end --- @param #Job self function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end --- @param #Job self function job:stop() JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) ngx_log(INFO, "job ", self.key, " stopped") end --- @param #Job self function job:completed() return JOBS:get(self.key .. ":completed") == 1 end --- @param #Job self function job:running() return JOBS:get(self.key .. ":running") == 1 end --- @param #Job self function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end --- @param #Job self function job:finish(...) if self.finish_fn then self.finish_fn(...) end return true end --- @param #Job self function job:wait_for(other) tinsert(self.wait_others, other) end --- @param #Job self function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
fix run job on reloads
fix run job on reloads
Lua
bsd-2-clause
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
b422da651d5083a52998c25190f37ad7b992387f
generator/json-generator.lua
generator/json-generator.lua
local json = require 'dkjson' -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local OUTPUT_FILE = 'love-completions.json' local WIKI_URL = 'https://love2d.org/wiki/' local LOVE_MODULE_STRING = 'love.' -- JSON Output control local DEBUG = false local KEY_ORDER = { 'luaVersion', 'packagePath', 'global', 'namedTypes', 'type', 'description', 'fields', 'args', 'returnTypes', 'link' } -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Generates a sequence containing subtables of all the arguments -- local function createArguments( args ) local arguments = {} for i, v in ipairs( args ) do arguments[i] = {} arguments[i].name = v.name -- Use [foo] notation as display name for optional arguments. if v.default then arguments[i].displayName = string.format( '[%s]', v.name ) end end return arguments end local function getType( type ) if type == 'string' or type == 'number' or type == 'table' or type == 'boolean' or type == 'function' then return { type = type } end return { type = 'ref', name = type } end local function createReturnTypes( returns ) local returnTypes = {} for i, v in ipairs( returns ) do returnTypes[i] = getType( v.type ) end return returnTypes end -- TODO handle functions with neither args nor return variables. local function createVariant( vdef ) local variant = {} if vdef.description then variant.description = vdef.description end if vdef.arguments then variant.args = createArguments( vdef.arguments ) end return variant end local function createFunction( f, parent, moduleString ) local name = f.name parent[name] = {} parent[name].type = 'function' parent[name].link = string.format( "%s%s%s", WIKI_URL, moduleString, name ) -- NOTE Currently atom-autocomplete-lua doesn't support return types which -- have been defined inside of variants. So for now we only use the -- return types of the first variant. -- @see https://github.com/dapetcu21/atom-autocomplete-lua/issues/15 if f.variants[1].returns then parent[name].returnTypes = createReturnTypes( f.variants[1].returns ) end -- Create normal function if there is just one variant. if #f.variants == 1 then local v = createVariant( f.variants[1] ) parent[name].description = f.description parent[name].args = v.args return end -- Generate multiple variants. parent[name].variants = {} for i, v in ipairs( f.variants ) do local variant = createVariant( v ) -- Use default description if there is no specific variant description. if not variant.description then variant.description = f.description end parent[name].variants[i] = variant end end local function createLoveFunctions( functions, parent ) for _, f in pairs( functions ) do createFunction( f, parent, LOVE_MODULE_STRING ) end end local function createLoveModuleFunctions( modules, parent ) for _, m in pairs( modules ) do local name = m.name parent[name] = {} parent[name].type = 'table' parent[name].description = m.description parent[name].link = string.format( "%s%s%s", WIKI_URL, LOVE_MODULE_STRING, name ) parent[name].fields = {} for _, f in pairs( m.functions ) do createFunction( f, parent[name].fields, string.format( '%s%s.', LOVE_MODULE_STRING, name )) end end end local function createGlobals( api, global ) global.type = 'table' global.fields = {} global.fields.love = {} global.fields.love.type = 'table' global.fields.love.fields = {} createLoveFunctions( api.functions, global.fields.love.fields ) createLoveFunctions( api.callbacks, global.fields.love.fields ) createLoveModuleFunctions( api.modules, global.fields.love.fields ) end -- ------------------------------------------------ -- Creation methods for named types -- ------------------------------------------------ local function collectTypes( api ) local types = {} for _, type in pairs( api.types ) do assert( not types[type.name] ) types[type.name] = type end for _, module in pairs( api.modules ) do if module.types then -- Not all modules define types. for _, type in pairs( module.types ) do assert( not types[type.name] ) types[type.name] = type end end end return types end local function createTypes( types, namedTypes ) for name, type in pairs( types ) do print( ' ' .. name ) namedTypes[name] = {} namedTypes[name].type = 'table' namedTypes[name].fields = {} if type.functions then for _, f in pairs( type.functions ) do createFunction( f, namedTypes[name].fields, name .. ':' ) end end if type.supertypes then namedTypes[name].metatable = {} namedTypes[name].metatable.type = 'table' namedTypes[name].metatable.fields = { __index = { type = 'ref', name = type.parenttype } } end end end local function createJSON() print( 'Generating LOVE snippets ... ' ) -- Load the LÖVE api files. local api = require( 'api.love_api' ) assert( api, 'No api file found!' ) print( 'Found API file for LÖVE version ' .. api.version ) -- Create main table. local output = { global = {}, namedTypes = {}, packagePath = "./?.lua,./?/init.lua" } print( 'Generating functions ...' ) createGlobals( api, output.global ) print( 'Generating types ...' ) local types = collectTypes( api ) createTypes( types, output.namedTypes ) local jsonString = json.encode( output, { indent = DEBUG, keyorder = KEY_ORDER }) local file = io.open( OUTPUT_FILE, 'w' ) assert( file, "ERROR: Can't write file: " .. OUTPUT_FILE ) file:write( jsonString ) print( 'DONE!' ) end createJSON()
local json = require 'dkjson' -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local OUTPUT_FILE = 'love-completions.json' local WIKI_URL = 'https://love2d.org/wiki/' local LOVE_MODULE_STRING = 'love.' -- JSON Output control local DEBUG = false local KEY_ORDER = { 'luaVersion', 'packagePath', 'global', 'namedTypes', 'type', 'description', 'fields', 'args', 'returnTypes', 'link' } -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Generates a sequence containing subtables of all the arguments -- local function createArguments( args, includeDummy ) local arguments = {} -- Includes a dummy "self" variant, because apparently love-autocomplete-lua -- automatically omits the first argument of methods preceeded by the : operator. if includeDummy then arguments[#arguments + 1] = {} arguments[#arguments].name = 'self' end for _, v in ipairs( args ) do arguments[#arguments + 1] = {} arguments[#arguments].name = v.name -- Use [foo] notation as display name for optional arguments. if v.default then arguments[#arguments].displayName = string.format( '[%s]', v.name ) end end return arguments end local function getType( type ) if type == 'string' or type == 'number' or type == 'table' or type == 'boolean' or type == 'function' then return { type = type } end return { type = 'ref', name = type } end local function createReturnTypes( returns ) local returnTypes = {} for i, v in ipairs( returns ) do returnTypes[i] = getType( v.type ) end return returnTypes end -- TODO handle functions with neither args nor return variables. local function createVariant( vdef, includeDummy ) local variant = {} if vdef.description then variant.description = vdef.description end if vdef.arguments then variant.args = createArguments( vdef.arguments, includeDummy ) end return variant end local function createFunction( f, parent, moduleString, includeDummy ) local name = f.name parent[name] = {} parent[name].type = 'function' parent[name].link = string.format( "%s%s%s", WIKI_URL, moduleString, name ) -- NOTE Currently atom-autocomplete-lua doesn't support return types which -- have been defined inside of variants. So for now we only use the -- return types of the first variant. -- @see https://github.com/dapetcu21/atom-autocomplete-lua/issues/15 if f.variants[1].returns then parent[name].returnTypes = createReturnTypes( f.variants[1].returns ) end -- Create normal function if there is just one variant. if #f.variants == 1 then local v = createVariant( f.variants[1], includeDummy ) parent[name].description = f.description parent[name].args = v.args return end -- Generate multiple variants. parent[name].variants = {} for i, v in ipairs( f.variants ) do local variant = createVariant( v, includeDummy ) -- Use default description if there is no specific variant description. if not variant.description then variant.description = f.description end parent[name].variants[i] = variant end end local function createLoveFunctions( functions, parent ) for _, f in pairs( functions ) do createFunction( f, parent, LOVE_MODULE_STRING ) end end local function createLoveModuleFunctions( modules, parent ) for _, m in pairs( modules ) do local name = m.name parent[name] = {} parent[name].type = 'table' parent[name].description = m.description parent[name].link = string.format( "%s%s%s", WIKI_URL, LOVE_MODULE_STRING, name ) parent[name].fields = {} for _, f in pairs( m.functions ) do createFunction( f, parent[name].fields, string.format( '%s%s.', LOVE_MODULE_STRING, name )) end end end local function createGlobals( api, global ) global.type = 'table' global.fields = {} global.fields.love = {} global.fields.love.type = 'table' global.fields.love.fields = {} createLoveFunctions( api.functions, global.fields.love.fields ) createLoveFunctions( api.callbacks, global.fields.love.fields ) createLoveModuleFunctions( api.modules, global.fields.love.fields ) end -- ------------------------------------------------ -- Creation methods for named types -- ------------------------------------------------ local function collectTypes( api ) local types = {} for _, type in pairs( api.types ) do assert( not types[type.name] ) types[type.name] = type end for _, module in pairs( api.modules ) do if module.types then -- Not all modules define types. for _, type in pairs( module.types ) do assert( not types[type.name] ) types[type.name] = type end end end return types end local function createTypes( types, namedTypes ) for name, type in pairs( types ) do print( ' ' .. name ) namedTypes[name] = {} namedTypes[name].type = 'table' namedTypes[name].fields = {} if type.functions then for _, f in pairs( type.functions ) do createFunction( f, namedTypes[name].fields, name .. ':', true ) end end if type.supertypes then namedTypes[name].metatable = {} namedTypes[name].metatable.type = 'table' namedTypes[name].metatable.fields = { __index = { type = 'ref', name = type.parenttype } } end end end local function createJSON() print( 'Generating LOVE snippets ... ' ) -- Load the LÖVE api files. local api = require( 'api.love_api' ) assert( api, 'No api file found!' ) print( 'Found API file for LÖVE version ' .. api.version ) -- Create main table. local output = { global = {}, namedTypes = {}, packagePath = "./?.lua,./?/init.lua" } print( 'Generating functions ...' ) createGlobals( api, output.global ) print( 'Generating types ...' ) local types = collectTypes( api ) createTypes( types, output.namedTypes ) local jsonString = json.encode( output, { indent = DEBUG, keyorder = KEY_ORDER }) local file = io.open( OUTPUT_FILE, 'w' ) assert( file, "ERROR: Can't write file: " .. OUTPUT_FILE ) file:write( jsonString ) print( 'DONE!' ) end createJSON()
Include dummy self arg for Type methods
Include dummy self arg for Type methods Fixes an issue where atom-autocomplete-lua would omit the first argument of a type variant because by default it expects a "self" variable as a first argument for methods with a : operator. Fixes #15.
Lua
mit
rm-code/love-atom,rm-code/love-atom
161266ddbe8293b6874e0b31eee8f66c16f06404
src/premake/PGTA.lua
src/premake/PGTA.lua
-- Procedurally Generated Transitional Audio Build -- function run_include(script, rel_dir) local script_full = "../external/build-tools/premake_scripts/" .. script local incl_prefix = iif(string.find(_ACTION, "vs20"), "$(ProjectDir)../../external/", "../../") local files_prefix = "../../" assert(loadfile(script_full))(incl_prefix, files_prefix, rel_dir) end solution "PGTA" location(_ACTION) targetdir(_ACTION) startproject "EngineTest" language "C++" platforms { "x64", "x32" } configurations { "Debug", "Release" } flags { "Symbols", "StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile" } filter "action:vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_SCL_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } filter "system:macosx or system:linux" buildoptions { "-std=c++11", "-fPIC" } filter "Debug" defines { "DEBUG", "_DEBUG" } filter "Release" flags "LinkTimeOptimization" defines "NDEBUG" optimize "Full" filter {} group "Externals" run_include("flatbuffers.lua", "flatbuffers") group "PGTA" dofile "AudioMixer.lua" group "PGTA" dofile "PGTALib.lua" group "BuildTools" dofile "SchemaCompiler.lua" group "Tests" assert(loadfile("Test.lua"))("AudioMixerTest") group "Tests" assert(loadfile("Test.lua"))("EngineTest") group "Tests" assert(loadfile("TestC.lua"))("CInterfaceTest") group ""
-- Procedurally Generated Transitional Audio Build -- function run_include(script, rel_dir) local script_full = "../external/build-tools/premake_scripts/" .. script local incl_prefix = iif(string.find(_ACTION, "vs20"), "$(ProjectDir)../../external/", "../../") local files_prefix = "../../" assert(loadfile(script_full))(incl_prefix, files_prefix, rel_dir) end solution "PGTA" location(_ACTION) targetdir(_ACTION) startproject "EngineTest" language "C++" platforms { "x64", "x32" } configurations { "Debug", "Release" } flags { "Symbols", "StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile" } filter "action:vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_SCL_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } filter { "action:not vs*" } buildoptions "-fPIC" filter { "action:not vs*", "language:C++" } buildoptions "-std=c++11" filter "Debug" defines { "DEBUG", "_DEBUG" } filter "Release" flags "LinkTimeOptimization" defines "NDEBUG" optimize "Full" filter {} group "Externals" run_include("flatbuffers.lua", "flatbuffers") group "PGTA" dofile "AudioMixer.lua" group "PGTA" dofile "PGTALib.lua" group "BuildTools" dofile "SchemaCompiler.lua" group "Tests" assert(loadfile("Test.lua"))("AudioMixerTest") group "Tests" assert(loadfile("Test.lua"))("EngineTest") group "Tests" assert(loadfile("TestC.lua"))("CInterfaceTest") group ""
Fixed gcc warning for -std=c++11 in a C build
Fixed gcc warning for -std=c++11 in a C build
Lua
mit
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
72c1dd570c687fe14e1ab9253221466deb0df93c
lua/wire/gates/highspeed.lua
lua/wire/gates/highspeed.lua
GateActions("Highspeed") GateActions["highspeed_write"] = { name = "Highspeed Write", inputs = { "Clk", "Memory", "Address", "Data" }, inputtypes = { "NORMAL", "WIRELINK", "NORMAL", "NORMAL" }, output = function(gate, Clk, Memory, Address, Data) if not Memory then return 0 end if not Memory.WriteCell then return 0 end if Clk <= 0 then return 0 end Address = math.floor(Address) if Address < 0 then return 0 end return Memory:WriteCell(Address, Data) and 1 or 0 end, label = function(Out, Clk, Memory, Address, Data) return "Clock:"..Clk.." Memory:"..Memory.." Address:"..Address.." Data:"..Data.." = "..Out end } GateActions["highspeed_read"] = { name = "Highspeed Read", inputs = { "Clk", "Memory", "Address" }, inputtypes = { "NORMAL", "WIRELINK", "NORMAL" }, output = function(gate, Clk, Memory, Address) if not Memory then return 0 end if not Memory.ReadCell then return 0 end if Clk <= 0 then return 0 end Address = math.floor(Address) if Address < 0 then return 0 end return Memory:ReadCell(Address) or 0 end, label = function(Out, Clk, Memory, Address) return "Clock:"..Clk.." Memory:"..Memory.." Address:"..Address.." = "..Out end } GateActions()
GateActions("Highspeed") GateActions["highspeed_write"] = { name = "Highspeed Write", inputs = { "Clk", "Memory", "Address", "Data" }, inputtypes = { "NORMAL", "WIRELINK", "NORMAL", "NORMAL" }, output = function(gate, Clk, Memory, Address, Data) if not Memory then return 0 end if not Memory.WriteCell then return 0 end if Clk <= 0 then return 0 end Address = math.floor(Address) if Address < 0 then return 0 end return Memory:WriteCell(Address, Data) and 1 or 0 end, label = function(Out, Clk, Memory, Address, Data) return string.format("Clock:%s Memory:%s Address:%s Data:%s = %s", Clk, Memory, Address, Data, Out) end } GateActions["highspeed_read"] = { name = "Highspeed Read", inputs = { "Clk", "Memory", "Address" }, inputtypes = { "NORMAL", "WIRELINK", "NORMAL" }, output = function(gate, Clk, Memory, Address) if not Memory then return 0 end if not Memory.ReadCell then return 0 end if Clk <= 0 then return 0 end Address = math.floor(Address) if Address < 0 then return 0 end return Memory:ReadCell(Address) or 0 end, label = function(Out, Clk, Memory, Address) return string.format("Clock:%s Memory:%s Address:%s = %s", Clk, Memory, Address, Out) end } GateActions()
Fix highspeed gate label error
Fix highspeed gate label error The inputs to a gate's label function aren't converted to strings before being passed in, so it's incorrect for highspeed_read and highspeed_write to try and concatenate with them. (This works for arithmetic gates, as `"1" .. 2 == "12"`, but `"1" .. nil` is a runtime error.)
Lua
apache-2.0
garrysmodlua/wire,Grocel/wire,sammyt291/wire,wiremod/wire,dvdvideo1234/wire,NezzKryptic/Wire
1d3e4729f8216551904885481c326e4ead97cf66
lib/Utils.lua
lib/Utils.lua
--- -- Escape a value to avoid SQL injection -- -- @param value -- -- @return string -- function MySQL.Utils.escape(value) return value -- return MySQL.mysql.MySqlHelper.EscapeString(value) end --- -- Create a MySQL Command from a query string and its parameters -- -- @param Query -- @param Parameters -- -- @return DbCommand -- function MySQL.Utils.CreateCommand(Query, Parameters) local Command = MySQL:createConnection().CreateCommand() Command.CommandText = Query if type(Parameters) == "table" then for Param in pairs(Parameters) do Command.CommandText = string.gsub(Command.CommandText, Param, MySQL.Utils.escape(Parameters[Param])) end end return Command end --- -- Convert a result from MySQL to an object in lua -- Take not that the reader will be closed after that -- -- @param MySqlDataReader -- -- @return object -- function MySQL.Utils.ConvertResultToTable(MySqlDataReader) local result = {} while MySqlDataReader:Read() do for i=0,MySqlDataReader.FieldCount-1 do local line = {} line[MySqlDataReader.GetName(i)] = MySQL.Utils.ConvertFieldValue(MySqlDataReader, i); result[#result+1] = line; end end MySqlDataReader:Close() return result; end --- -- Convert a indexed field into a good value for lua -- -- @param MysqlDataReader -- @param index -- -- @return mixed -- function MySQL.Utils.ConvertFieldValue(MysqlDataReader, index) local type = tostring(MysqlDataReader:GetFieldType(index)) if type == "System.DateTime" then return MysqlDataReader:GetDateTime(index) end if type == "System.Double" then return MysqlDataReader:GetDouble(index) end if type == "System.Int32" then return MysqlDataReader:GetInt32(index) end if type == "System.Int64" then return MysqlDataReader:GetInt64(index) end return MysqlDataReader:GetString(index) end --- -- Create a lua coroutine from a C# Task (System.Threading.Tasks.Task) -- -- @param Task Task that comes from C# -- @param Transformer Delegate (function) to transform the result into another one -- -- @return coroutine -- function MySQL.Utils.CreateCoroutineFromTask(Task, Transformer) return coroutine.create(function() coroutine.yield(Transformer(Task.GetAwaiter().GetResult())) end) end
--- -- Escape a value to avoid SQL injection -- -- @param value -- -- @return string -- function MySQL.Utils.escape(value) return value -- return MySQL.mysql.MySqlHelper.EscapeString(value) end --- -- Create a MySQL Command from a query string and its parameters -- -- @param Query -- @param Parameters -- -- @return DbCommand -- function MySQL.Utils.CreateCommand(Query, Parameters) local Command = MySQL:createConnection().CreateCommand() Command.CommandText = Query if type(Parameters) == "table" then for Param in pairs(Parameters) do Command.CommandText = string.gsub(Command.CommandText, Param, MySQL.Utils.escape(Parameters[Param])) end end return Command end --- -- Convert a result from MySQL to an object in lua -- Take not that the reader will be closed after that -- -- @param MySqlDataReader -- -- @return object -- function MySQL.Utils.ConvertResultToTable(MySqlDataReader) local result = {} while MySqlDataReader:Read() do local line = {} for i=0,MySqlDataReader.FieldCount-1 do line[MySqlDataReader.GetName(i)] = MySQL.Utils.ConvertFieldValue(MySqlDataReader, i); end result[#result+1] = line; end MySqlDataReader:Close() return result; end --- -- Convert a indexed field into a good value for lua -- -- @param MysqlDataReader -- @param index -- -- @return mixed -- function MySQL.Utils.ConvertFieldValue(MysqlDataReader, index) local type = tostring(MysqlDataReader:GetFieldType(index)) if type == "System.DateTime" then return MysqlDataReader:GetDateTime(index) end if type == "System.Double" then return MysqlDataReader:GetDouble(index) end if type == "System.Int32" then return MysqlDataReader:GetInt32(index) end if type == "System.Int64" then return MysqlDataReader:GetInt64(index) end return MysqlDataReader:GetString(index) end --- -- Create a lua coroutine from a C# Task (System.Threading.Tasks.Task) -- -- @param Task Task that comes from C# -- @param Transformer Delegate (function) to transform the result into another one -- -- @return coroutine -- function MySQL.Utils.CreateCoroutineFromTask(Task, Transformer) return coroutine.create(function() coroutine.yield(Transformer(Task.GetAwaiter().GetResult())) end) end
Fix creating result from data reader
Fix creating result from data reader
Lua
mit
brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async
31d92a13ff0841f597960c399066f8e2f80b4b5d
modules/romaji.lua
modules/romaji.lua
require'chasen' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local pre = { ['キャ'] = 'kya', ['キュ'] = 'kyu', ['キョ'] = 'kyo', ['シャ'] = 'sha', ['シュ'] = 'shu', ['ショ'] = 'sho', ['チャ'] = 'cha', ['チュ'] = 'chu', ['チョ'] = 'cho', ['ニャ'] = 'nya', ['ニュ'] = 'nyu', ['ニョ'] = 'nyo', ['ヒャ'] = 'hya', ['ヒュ'] = 'hyu', ['ヒョ'] = 'hyo', ['ミャ'] = 'mya', ['ミュ'] = 'myu', ['ミョ'] = 'myo', ['リャ'] = 'rya', ['リュ'] = 'ryu', ['リョ'] = 'ryo', ['ヰャ'] = 'wya', ['ヰュ'] = 'wyu', ['ヰョ'] = 'wyo', ['ギャ'] = 'gya', ['ギュ'] = 'gyu', ['ギョ'] = 'gyo', ['ジャ'] = 'ja', ['ジュ'] = 'ju', ['ジョ'] = 'jo', ['ヂャ'] = 'ja', ['ヂュ'] = 'ju', ['ヂョ'] = 'jo', ['ビャ'] = 'bya', ['ビュ'] = 'byu', ['ビョ'] = 'byo', ['ピャ'] = 'pya', ['ピュ'] = 'pyu', ['ピョ'] = 'pyo', ['イェ'] = 'ye', ['ヴァ'] = 'va', ['ヴィ'] = 'vi', ['ヴ'] = 'vu', ['ヴェ'] = 've', ['ヴォ'] = 'vo', ['ヴャ'] = 'vya', ['ヴュ'] = 'vyu', ['ヴョ'] = 'vyo', ['シェ'] = 'she', ['ジェ'] = 'je', ['チェ'] = 'che', ['スィ'] = 'si', ['スャ'] = 'sya', ['スュ'] = 'syu', ['スョ'] = 'syo', ['ズィ'] = 'zi', ['ズャ'] = 'zya', ['ズュ'] = 'zyu', ['ズョ'] = 'zyo', ['ティ'] = 'ti', ['トゥ'] = 'tu', ['テャ'] = 'tya', ['テュ'] = 'tyu', ['テョ'] = 'tyo', ['ディ'] = 'di', ['ドゥ'] = 'du', ['デャ'] = 'dya', ['デュ'] = 'dyu', ['デョ'] = 'dyo', ['ツァ'] = 'tsa', ['ツィ'] = 'tsi', ['ツェ'] = 'tse', ['ツォ'] = 'tso', ['ファ'] = 'fa', ['フィ'] = 'fi', ['ホゥ'] = 'hu', ['フェ'] = 'fe', ['フォ'] = 'fo', ['フャ'] = 'fya', ['フュ'] = 'fyu', ['フョ'] = 'fyo', ['リェ'] = 'rye', ['ウァ'] = 'wa', ['ウィ'] = 'wi', ['ウェ'] = 'we', ['ウォ'] = 'wo', ['ウャ'] = 'wya', ['ウュ'] = 'wyu', ['ウョ'] = 'wyo', ['クァ'] = 'kwa', ['クィ'] = 'kwi', ['クゥ'] = 'kwu', ['クェ'] = 'kwe', ['クォ'] = 'kwo', ['グァ'] = 'gwa', ['グィ'] = 'gwi', ['グゥ'] = 'gwu', ['グェ'] = 'gwe', ['グォ'] = 'gwo', ['クヮ'] = 'kwa', ['グヮ'] = 'gwa', } local katakana = { ['ア'] = 'a', ['イ'] = 'i', ['ウ'] = 'u', ['エ'] = 'e', ['オ'] = 'o', ['カ'] = 'ka', ['キ'] = 'ki', ['ク'] = 'ku', ['ケ'] = 'ke', ['コ'] = 'ko', ['サ'] = 'sa', ['シ'] = 'shi', ['ス'] = 'su', ['セ'] = 'se', ['ソ'] = 'so', ['タ'] = 'ta', ['チ'] = 'chi', ['ツ'] = 'tsu', ['テ'] = 'te', ['ト'] = 'to', ['ナ'] = 'na', ['ニ'] = 'ni', ['ヌ'] = 'nu', ['ネ'] = 'ne', ['ノ'] = 'no', ['ハ'] = 'ha', ['ヒ'] = 'hi', ['フ'] = 'fu', ['ヘ'] = 'he', ['ホ'] = 'ho', ['マ'] = 'ma', ['ミ'] = 'mi', ['ム'] = 'mu', ['メ'] = 'me', ['モ'] = 'mo', ['ヤ'] = 'ya', ['ユ'] = 'yu', ['ヨ'] = 'yo', ['ラ'] = 'ra', ['リ'] = 'ri', ['ル'] = 'ru', ['レ'] = 're', ['ロ'] = 'ro', ['ワ'] = 'wa', ['ヰ'] = 'wi', ['⼲'] = 'wu', ['ヱ'] = 'we', ['ヲ'] = 'wo', ['ン'] = '\002n\002', ['ガ'] = 'ga', ['ギ'] = 'gi', ['グ'] = 'gu', ['ゲ'] = 'ge', ['ゴ'] = 'go', ['ザ'] = 'za', ['ジ'] = 'ji', ['ズ'] = 'zu', ['ゼ'] = 'ze', ['ゾ'] = 'zo', ['ダ'] = 'da', ['ヂ'] = 'ji', ['ヅ'] = 'dzu', ['デ'] = 'de', ['ド'] = 'do', ['バ'] = 'ba', ['ビ'] = 'bi', ['ブ'] = 'bu', ['ベ'] = 'be', ['ボ'] = 'bo', ['パ'] = 'pa', ['ピ'] = 'pi', ['プ'] = 'pu', ['ペ'] = 'pe', ['ポ'] = 'po', ['ヷ'] = 'va', ['ヸ'] = 'vi', ['ヹ'] = 've', ['ヺ'] = 'vo', [' 。'] = '.', ['、'] = ',', -- hmm... ['ァ'] = 'a', ['ィ'] = 'i', ['ゥ'] = 'u', ['ェ'] = 'e', ['ォ'] = 'o', ['ャ'] = 'ya', ['ュ'] = 'yu', ['ョ'] = 'yo', } local post = { ['(.)ー'] = '%1%1', ['ッ(.)'] = '%1%1', } return { ["^:(%S+) PRIVMSG (%S+) :!kr (.+)$"] = function(self, src, dest, msg) msg = chasen.sparse(msg:gsub('%s', '\n')) msg = utils.split(msg:gsub(" ", " "), '\n') -- chop of the last bit. table.remove(msg) for i=1,#msg do msg[i] = utils.split(msg[i], '\t') end local output = '' for k, data in next, msg do if(data[4] == '未知語') then output = output .. data[1] elseif(data[4] == '記号-アルファベット') then output = output..data[1] elseif(data[1] == 'EOS') then output = output .. ' ' else output = output..' '..data[2] end end for find, replace in next, pre do output = output:gsub(find, replace) end for find, replace in next, katakana do output = output:gsub(find, replace) end for find, replace in next, post do output = output:gsub(find, replace) end self:msg(dest, src, 'In romaji: %s', trim(output):gsub("[%s%s]+", " ")) end }
require'chasen' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local pre = { ['キャ'] = 'kya', ['キュ'] = 'kyu', ['キョ'] = 'kyo', ['シャ'] = 'sha', ['シュ'] = 'shu', ['ショ'] = 'sho', ['チャ'] = 'cha', ['チュ'] = 'chu', ['チョ'] = 'cho', ['ニャ'] = 'nya', ['ニュ'] = 'nyu', ['ニョ'] = 'nyo', ['ヒャ'] = 'hya', ['ヒュ'] = 'hyu', ['ヒョ'] = 'hyo', ['ミャ'] = 'mya', ['ミュ'] = 'myu', ['ミョ'] = 'myo', ['リャ'] = 'rya', ['リュ'] = 'ryu', ['リョ'] = 'ryo', ['ヰャ'] = 'wya', ['ヰュ'] = 'wyu', ['ヰョ'] = 'wyo', ['ギャ'] = 'gya', ['ギュ'] = 'gyu', ['ギョ'] = 'gyo', ['ジャ'] = 'ja', ['ジュ'] = 'ju', ['ジョ'] = 'jo', ['ヂャ'] = 'ja', ['ヂュ'] = 'ju', ['ヂョ'] = 'jo', ['ビャ'] = 'bya', ['ビュ'] = 'byu', ['ビョ'] = 'byo', ['ピャ'] = 'pya', ['ピュ'] = 'pyu', ['ピョ'] = 'pyo', ['イェ'] = 'ye', ['ヴァ'] = 'va', ['ヴィ'] = 'vi', ['ヴ'] = 'vu', ['ヴェ'] = 've', ['ヴォ'] = 'vo', ['ヴャ'] = 'vya', ['ヴュ'] = 'vyu', ['ヴョ'] = 'vyo', ['シェ'] = 'she', ['ジェ'] = 'je', ['チェ'] = 'che', ['スィ'] = 'si', ['スャ'] = 'sya', ['スュ'] = 'syu', ['スョ'] = 'syo', ['ズィ'] = 'zi', ['ズャ'] = 'zya', ['ズュ'] = 'zyu', ['ズョ'] = 'zyo', ['ティ'] = 'ti', ['トゥ'] = 'tu', ['テャ'] = 'tya', ['テュ'] = 'tyu', ['テョ'] = 'tyo', ['ディ'] = 'di', ['ドゥ'] = 'du', ['デャ'] = 'dya', ['デュ'] = 'dyu', ['デョ'] = 'dyo', ['ツァ'] = 'tsa', ['ツィ'] = 'tsi', ['ツェ'] = 'tse', ['ツォ'] = 'tso', ['ファ'] = 'fa', ['フィ'] = 'fi', ['ホゥ'] = 'hu', ['フェ'] = 'fe', ['フォ'] = 'fo', ['フャ'] = 'fya', ['フュ'] = 'fyu', ['フョ'] = 'fyo', ['リェ'] = 'rye', ['ウァ'] = 'wa', ['ウィ'] = 'wi', ['ウェ'] = 'we', ['ウォ'] = 'wo', ['ウャ'] = 'wya', ['ウュ'] = 'wyu', ['ウョ'] = 'wyo', ['クァ'] = 'kwa', ['クィ'] = 'kwi', ['クゥ'] = 'kwu', ['クェ'] = 'kwe', ['クォ'] = 'kwo', ['グァ'] = 'gwa', ['グィ'] = 'gwi', ['グゥ'] = 'gwu', ['グェ'] = 'gwe', ['グォ'] = 'gwo', ['クヮ'] = 'kwa', ['グヮ'] = 'gwa', } local katakana = { ['ア'] = 'a', ['イ'] = 'i', ['ウ'] = 'u', ['エ'] = 'e', ['オ'] = 'o', ['カ'] = 'ka', ['キ'] = 'ki', ['ク'] = 'ku', ['ケ'] = 'ke', ['コ'] = 'ko', ['サ'] = 'sa', ['シ'] = 'shi', ['ス'] = 'su', ['セ'] = 'se', ['ソ'] = 'so', ['タ'] = 'ta', ['チ'] = 'chi', ['ツ'] = 'tsu', ['テ'] = 'te', ['ト'] = 'to', ['ナ'] = 'na', ['ニ'] = 'ni', ['ヌ'] = 'nu', ['ネ'] = 'ne', ['ノ'] = 'no', ['ハ'] = 'ha', ['ヒ'] = 'hi', ['フ'] = 'fu', ['ヘ'] = 'he', ['ホ'] = 'ho', ['マ'] = 'ma', ['ミ'] = 'mi', ['ム'] = 'mu', ['メ'] = 'me', ['モ'] = 'mo', ['ヤ'] = 'ya', ['ユ'] = 'yu', ['ヨ'] = 'yo', ['ラ'] = 'ra', ['リ'] = 'ri', ['ル'] = 'ru', ['レ'] = 're', ['ロ'] = 'ro', ['ワ'] = 'wa', ['ヰ'] = 'wi', ['⼲'] = 'wu', ['ヱ'] = 'we', ['ヲ'] = 'wo', ['ン'] = '\002n\002', ['ガ'] = 'ga', ['ギ'] = 'gi', ['グ'] = 'gu', ['ゲ'] = 'ge', ['ゴ'] = 'go', ['ザ'] = 'za', ['ジ'] = 'ji', ['ズ'] = 'zu', ['ゼ'] = 'ze', ['ゾ'] = 'zo', ['ダ'] = 'da', ['ヂ'] = 'ji', ['ヅ'] = 'dzu', ['デ'] = 'de', ['ド'] = 'do', ['バ'] = 'ba', ['ビ'] = 'bi', ['ブ'] = 'bu', ['ベ'] = 'be', ['ボ'] = 'bo', ['パ'] = 'pa', ['ピ'] = 'pi', ['プ'] = 'pu', ['ペ'] = 'pe', ['ポ'] = 'po', ['ヷ'] = 'va', ['ヸ'] = 'vi', ['ヹ'] = 've', ['ヺ'] = 'vo', [' 。'] = '.', ['、'] = ',', ['(ッ) '] = '%1', -- hmm... ['ァ'] = 'a', ['ィ'] = 'i', ['ゥ'] = 'u', ['ェ'] = 'e', ['ォ'] = 'o', ['ャ'] = 'ya', ['ュ'] = 'yu', ['ョ'] = 'yo', } local post = { ['(.)ー'] = '%1%1', ['ッ(.)'] = '%1%1', } return { ["^:(%S+) PRIVMSG (%S+) :!kr (.+)$"] = function(self, src, dest, msg) msg = chasen.sparse(msg:gsub('%s', '\n')) msg = utils.split(msg:gsub(" ", " "), '\n') -- chop of the last bit. table.remove(msg) for k, data in ipairs(msg) do print(data) end for i=1,#msg do msg[i] = utils.split(msg[i], '\t') end local output = '' for k, data in next, msg do if(data[4] == '未知語') then output = output .. data[1] elseif(data[4] == '記号-アルファベット') then output = output..data[1] elseif(data[1] == 'EOS') then output = output .. ' ' else output = output..' '..data[2] end end print(output) for find, replace in next, pre do output = output:gsub(find, replace) end for find, replace in next, katakana do output = output:gsub(find, replace) end for find, replace in next, post do output = output:gsub(find, replace) end self:msg(dest, src, 'In romaji: %s', trim(output):gsub("[%s%s]+", " ")) end }
Hack to fix the romanization.
Hack to fix the romanization.
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
c3bf59a91d9e24ee09bd122e5e5a6fdaf5bc1702
libs/sgi-uhttpd/luasrc/sgi/uhttpd.lua
libs/sgi-uhttpd/luasrc/sgi/uhttpd.lua
--[[ LuCI - Server Gateway Interface for the uHTTPd server Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local function send(...) return uhttpd.send(...) end local function sendc(...) if env.HTTP_VERSION > 1.0 then return uhttpd.sendc(...) else return uhttpd.send(...) end end local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true if env.HTTP_VERSION > 1.0 then hcache["Transfer-Encoding"] = "chunked" end while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send(env.SERVER_PROTOCOL) send(" 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send(env.SERVER_PROTOCOL) send(" ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then sendc(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
--[[ LuCI - Server Gateway Interface for the uHTTPd server Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
libs/sgi-uhttpd: fix binding to properly work with current uhttpd2 implementation
libs/sgi-uhttpd: fix binding to properly work with current uhttpd2 implementation Signed-off-by: Jo-Philipp Wich <a9275913d515487ffaed469337a530ed202da558@openwrt.org>
Lua
apache-2.0
lbthomsen/openwrt-luci,NeoRaider/luci,wongsyrone/luci-1,chris5560/openwrt-luci,jlopenwrtluci/luci,tcatm/luci,palmettos/cnLuCI,oyido/luci,palmettos/test,zhaoxx063/luci,kuoruan/luci,marcel-sch/luci,obsy/luci,981213/luci-1,lcf258/openwrtcn,palmettos/test,Hostle/luci,nwf/openwrt-luci,MinFu/luci,taiha/luci,david-xiao/luci,florian-shellfire/luci,obsy/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,palmettos/test,forward619/luci,jchuang1977/luci-1,nmav/luci,hnyman/luci,Hostle/luci,nmav/luci,marcel-sch/luci,chris5560/openwrt-luci,fkooman/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,oyido/luci,florian-shellfire/luci,oneru/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,florian-shellfire/luci,teslamint/luci,daofeng2015/luci,palmettos/test,RedSnake64/openwrt-luci-packages,aa65535/luci,taiha/luci,jchuang1977/luci-1,artynet/luci,remakeelectric/luci,kuoruan/lede-luci,deepak78/new-luci,Noltari/luci,fkooman/luci,cappiewu/luci,slayerrensky/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,taiha/luci,RuiChen1113/luci,RuiChen1113/luci,openwrt-es/openwrt-luci,oneru/luci,thess/OpenWrt-luci,dismantl/luci-0.12,dwmw2/luci,kuoruan/lede-luci,obsy/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,oyido/luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,nmav/luci,deepak78/new-luci,kuoruan/luci,maxrio/luci981213,Noltari/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,david-xiao/luci,david-xiao/luci,joaofvieira/luci,Noltari/luci,981213/luci-1,rogerpueyo/luci,chris5560/openwrt-luci,lcf258/openwrtcn,fkooman/luci,urueedi/luci,daofeng2015/luci,schidler/ionic-luci,thesabbir/luci,chris5560/openwrt-luci,nwf/openwrt-luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,david-xiao/luci,urueedi/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,aa65535/luci,teslamint/luci,artynet/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,fkooman/luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,cshore/luci,palmettos/cnLuCI,cappiewu/luci,male-puppies/luci,fkooman/luci,oneru/luci,mumuqz/luci,zhaoxx063/luci,LuttyYang/luci,jorgifumi/luci,MinFu/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,keyidadi/luci,male-puppies/luci,nmav/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,NeoRaider/luci,obsy/luci,marcel-sch/luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,Hostle/luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,slayerrensky/luci,male-puppies/luci,dwmw2/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,RuiChen1113/luci,david-xiao/luci,maxrio/luci981213,thess/OpenWrt-luci,thesabbir/luci,aa65535/luci,NeoRaider/luci,rogerpueyo/luci,981213/luci-1,fkooman/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,thesabbir/luci,marcel-sch/luci,Hostle/luci,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,forward619/luci,nmav/luci,deepak78/new-luci,daofeng2015/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,thess/OpenWrt-luci,bright-things/ionic-luci,bright-things/ionic-luci,artynet/luci,kuoruan/luci,openwrt-es/openwrt-luci,keyidadi/luci,ollie27/openwrt_luci,kuoruan/luci,urueedi/luci,mumuqz/luci,tcatm/luci,cappiewu/luci,harveyhu2012/luci,slayerrensky/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,lcf258/openwrtcn,aa65535/luci,chris5560/openwrt-luci,Noltari/luci,jlopenwrtluci/luci,981213/luci-1,jlopenwrtluci/luci,tobiaswaldvogel/luci,jorgifumi/luci,thesabbir/luci,marcel-sch/luci,rogerpueyo/luci,dwmw2/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,oneru/luci,oneru/luci,thesabbir/luci,RuiChen1113/luci,rogerpueyo/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,sujeet14108/luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,palmettos/test,thess/OpenWrt-luci,tobiaswaldvogel/luci,daofeng2015/luci,daofeng2015/luci,jchuang1977/luci-1,openwrt/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,forward619/luci,jorgifumi/luci,ollie27/openwrt_luci,kuoruan/luci,Wedmer/luci,urueedi/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,maxrio/luci981213,dwmw2/luci,Kyklas/luci-proto-hso,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,oyido/luci,opentechinstitute/luci,MinFu/luci,nwf/openwrt-luci,nmav/luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,obsy/luci,RedSnake64/openwrt-luci-packages,jorgifumi/luci,hnyman/luci,zhaoxx063/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,opentechinstitute/luci,slayerrensky/luci,deepak78/new-luci,sujeet14108/luci,dismantl/luci-0.12,joaofvieira/luci,maxrio/luci981213,thesabbir/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,mumuqz/luci,schidler/ionic-luci,nmav/luci,joaofvieira/luci,kuoruan/luci,urueedi/luci,david-xiao/luci,taiha/luci,artynet/luci,openwrt/luci,cshore/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,ff94315/luci-1,slayerrensky/luci,jchuang1977/luci-1,openwrt/luci,tobiaswaldvogel/luci,deepak78/new-luci,jchuang1977/luci-1,tcatm/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,kuoruan/lede-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,male-puppies/luci,taiha/luci,taiha/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,marcel-sch/luci,harveyhu2012/luci,teslamint/luci,aa65535/luci,schidler/ionic-luci,bright-things/ionic-luci,forward619/luci,ollie27/openwrt_luci,jorgifumi/luci,shangjiyu/luci-with-extra,hnyman/luci,Noltari/luci,urueedi/luci,dismantl/luci-0.12,forward619/luci,zhaoxx063/luci,openwrt/luci,keyidadi/luci,thess/OpenWrt-luci,rogerpueyo/luci,artynet/luci,obsy/luci,harveyhu2012/luci,openwrt-es/openwrt-luci,forward619/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,bittorf/luci,tobiaswaldvogel/luci,fkooman/luci,lcf258/openwrtcn,sujeet14108/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,zhaoxx063/luci,cappiewu/luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,jorgifumi/luci,cshore/luci,Wedmer/luci,bittorf/luci,cshore/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,Hostle/luci,Sakura-Winkey/LuCI,LuttyYang/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,tcatm/luci,dismantl/luci-0.12,cappiewu/luci,ff94315/luci-1,deepak78/new-luci,shangjiyu/luci-with-extra,openwrt/luci,Kyklas/luci-proto-hso,mumuqz/luci,RedSnake64/openwrt-luci-packages,oyido/luci,openwrt/luci,deepak78/new-luci,kuoruan/lede-luci,rogerpueyo/luci,Kyklas/luci-proto-hso,artynet/luci,lcf258/openwrtcn,marcel-sch/luci,bittorf/luci,oneru/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,LuttyYang/luci,nwf/openwrt-luci,MinFu/luci,MinFu/luci,NeoRaider/luci,joaofvieira/luci,keyidadi/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,ff94315/luci-1,dwmw2/luci,remakeelectric/luci,marcel-sch/luci,tcatm/luci,bright-things/ionic-luci,cshore/luci,oyido/luci,florian-shellfire/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,taiha/luci,RuiChen1113/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,teslamint/luci,chris5560/openwrt-luci,Wedmer/luci,bright-things/ionic-luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,zhaoxx063/luci,Noltari/luci,nwf/openwrt-luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,palmettos/cnLuCI,kuoruan/lede-luci,teslamint/luci,ff94315/luci-1,joaofvieira/luci,artynet/luci,slayerrensky/luci,remakeelectric/luci,harveyhu2012/luci,cshore-firmware/openwrt-luci,male-puppies/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,openwrt-es/openwrt-luci,zhaoxx063/luci,joaofvieira/luci,keyidadi/luci,rogerpueyo/luci,remakeelectric/luci,Hostle/luci,981213/luci-1,mumuqz/luci,david-xiao/luci,chris5560/openwrt-luci,dwmw2/luci,tcatm/luci,dismantl/luci-0.12,artynet/luci,lcf258/openwrtcn,schidler/ionic-luci,LuttyYang/luci,maxrio/luci981213,MinFu/luci,cappiewu/luci,teslamint/luci,male-puppies/luci,harveyhu2012/luci,ollie27/openwrt_luci,maxrio/luci981213,florian-shellfire/luci,Hostle/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,florian-shellfire/luci,MinFu/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,Noltari/luci,lcf258/openwrtcn,bright-things/ionic-luci,thess/OpenWrt-luci,LuttyYang/luci,deepak78/new-luci,artynet/luci,schidler/ionic-luci,schidler/ionic-luci,forward619/luci,remakeelectric/luci,palmettos/cnLuCI,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,981213/luci-1,obsy/luci,florian-shellfire/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,opentechinstitute/luci,jlopenwrtluci/luci,taiha/luci,Sakura-Winkey/LuCI,NeoRaider/luci,cshore-firmware/openwrt-luci,tcatm/luci,maxrio/luci981213,cshore/luci,ff94315/luci-1,palmettos/test,david-xiao/luci,sujeet14108/luci,aa65535/luci,mumuqz/luci,lbthomsen/openwrt-luci,keyidadi/luci,daofeng2015/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,aa65535/luci,mumuqz/luci,bittorf/luci,sujeet14108/luci,sujeet14108/luci,lbthomsen/openwrt-luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,kuoruan/luci,daofeng2015/luci,wongsyrone/luci-1,NeoRaider/luci,nwf/openwrt-luci,opentechinstitute/luci,wongsyrone/luci-1,palmettos/cnLuCI,fkooman/luci,cshore/luci,jchuang1977/luci-1,bittorf/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,cappiewu/luci,981213/luci-1,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,openwrt/luci,RuiChen1113/luci,bittorf/luci,remakeelectric/luci,oneru/luci,maxrio/luci981213,hnyman/luci,dismantl/luci-0.12,opentechinstitute/luci,tcatm/luci,shangjiyu/luci-with-extra,ff94315/luci-1,joaofvieira/luci,jorgifumi/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,kuoruan/luci,jlopenwrtluci/luci,obsy/luci,hnyman/luci,oneru/luci,bittorf/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,openwrt/luci,joaofvieira/luci,male-puppies/luci,male-puppies/luci,teslamint/luci,bright-things/ionic-luci,wongsyrone/luci-1,cshore/luci,Noltari/luci,LuttyYang/luci,NeoRaider/luci,Wedmer/luci,oyido/luci
13888fd242b5f1219113ee60ad1c3a97b9827fb9
premake.lua
premake.lua
-- TODO: Because there is plenty ... -- 1. x86/x64 switching -- 2. actually test linux build configuration -- 3. clean this file up because I'm sure it could be organized better -- 4. consider maybe switching to CMake because of the ugly hack below -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end -- avert your eyes children! if string.find(_ACTION, "xcode") then -- TODO: i'm sure we could do some string search+replace trickery to make -- this more general-purpose -- take care of the most common case where the FBX SDK is installed to the -- default location and part of the path contains a space -- god help you if you install the FBX SDK using a totally different path -- that contains a space AND you want to use Xcode -- Premake + Xcode combined fuck this up so badly making it nigh-impossible -- to do any kind of _proper_ path escaping here (I wasted an hour on this) -- (maybe I should have used CMake ....) FBX_SDK_ROOT = string.gsub(FBX_SDK_ROOT, "FBX SDK", "'FBX SDK'") end -- ok, you can look again BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX ---------------------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x86"), "./libs/libpng/lib/linux/x86", "./libs/zlib/lib/linux/x86", } links { "png", "z", } configuration { "linux", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013.3-static", } --- MAC ------------------------------------------------------------ configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", } configuration { "macosx", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013.3-static", }
-- TODO: Because there is plenty ... -- 1. x86/x64 switching -- 2. actually test linux build configuration -- 3. clean this file up because I'm sure it could be organized better -- 4. consider maybe switching to CMake because of the ugly hack below -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end -- avert your eyes children! if string.find(_ACTION, "xcode") then -- TODO: i'm sure we could do some string search+replace trickery to make -- this more general-purpose -- take care of the most common case where the FBX SDK is installed to the -- default location and part of the path contains a space -- god help you if you install the FBX SDK using a totally different path -- that contains a space AND you want to use Xcode -- Premake + Xcode combined fuck this up so badly making it nigh-impossible -- to do any kind of _proper_ path escaping here (I wasted an hour on this) -- (maybe I should have used CMake ....) FBX_SDK_ROOT = string.gsub(FBX_SDK_ROOT, "FBX SDK", "'FBX SDK'") end -- ok, you can look again BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX ---------------------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } -- TODO: while using x64 will likely be fine for most people nowadays, -- we still need to make this configurable libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x64"), "./libs/libpng/lib/linux/x64", "./libs/zlib/lib/linux/x64", } links { "png", "z", "pthread", "dl", } configuration { "linux", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013.3-static", } --- MAC ------------------------------------------------------------ configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", } configuration { "macosx", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013.3-static", }
quick fixes for building on Linux
quick fixes for building on Linux eventually will have to revisit and do proper x86/x64 configuration switching for that one random person who will want to do a 32 bit binary on linux
Lua
apache-2.0
super626/fbx-conv,arisecbf/fbx-conv,lvlonggame/fbx-conv,andyvand/fbx-conv,cocos2d-x/fbx-conv,xoppa/fbx-conv,cocos2d-x/fbx-conv,andyvand/fbx-conv,iichenbf/fbx-conv,arisecbf/fbx-conv,reduz/fbx-conv,lvlonggame/fbx-conv,super626/fbx-conv,super626/fbx-conv,arisecbf/fbx-conv,Maxwolf/Multimap.FBXConv,reduz/fbx-conv,Maxwolf/Multimap.FBXConv,davidedmonds/fbx-conv,iichenbf/fbx-conv,davidedmonds/fbx-conv,xoppa/fbx-conv,cocos2d-x/fbx-conv,reduz/fbx-conv,xoppa/fbx-conv,andyvand/fbx-conv,iichenbf/fbx-conv,davidedmonds/fbx-conv,lvlonggame/fbx-conv
7c48e155b89d92f9e2e3c543b8c77218ac2bdee6
hammerspoon/init.lua
hammerspoon/init.lua
-- API Doc : http://www.hammerspoon.org/docs/ -- KeyCodes : http://www.hammerspoon.org/docs/hs.keycodes.html#map hs.hotkey.bind({"ctrl"}, "t", function() hs.application.launchOrFocus("iTerm") end) hs.hotkey.bind({"ctrl"}, "g", function() hs.application.launchOrFocus("Google Chrome") end) hs.hotkey.bind({"ctrl"}, "s", function() hs.application.launchOrFocus("Sublime Text") end) hs.hotkey.bind({"ctrl"}, "e", function() hs.application.launchOrFocus("Finder") end) hs.hotkey.bind({"ctrl"}, "v", function() hs.application.launchOrFocus("Filezilla") end) hs.hotkey.bind({"ctrl"}, "q", function() hs.application.launchOrFocus("Calendar") end) hs.hotkey.bind({"ctrl"}, "a", function() hs.application.launchOrFocus("Slack") end) hs.hotkey.bind({"ctrl"}, "m", function() hs.application.launchOrFocus("Mail") end) hs.hotkey.bind({"ctrl"}, "l", function() hs.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend") end) -- Toggle Fullscreen hs.hotkey.bind({"ctrl"}, "f", function() local win = hs.window.focusedWindow() win:toggleFullScreen() end) -- Close active window hs.hotkey.bind({"ctrl"}, "x", function() local win = hs.window.focusedWindow() win:application():kill() end) -- Chrome reload hs.hotkey.bind({"ctrl"}, "i", function() local chrome = hs.appfinder.appFromName("Google Chrome") local item = {"Afficher", "Actualiser cette page"} chrome:selectMenuItem(item) end) -- Autoconfig reload function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config reloaded !"}):send() end end local configWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
-- API Doc : http://www.hammerspoon.org/docs/ -- KeyCodes : http://www.hammerspoon.org/docs/hs.keycodes.html#map hs.hotkey.bind({"ctrl"}, "t", function() hs.application.launchOrFocus("iTerm") end) hs.hotkey.bind({"ctrl"}, "g", function() hs.application.launchOrFocus("Google Chrome") end) hs.hotkey.bind({"ctrl"}, "s", function() hs.application.launchOrFocus("Sublime Text") end) hs.hotkey.bind({"ctrl"}, "e", function() hs.application.launchOrFocus("Finder") end) hs.hotkey.bind({"ctrl"}, "v", function() hs.application.launchOrFocus("Filezilla") end) hs.hotkey.bind({"ctrl"}, "q", function() hs.application.launchOrFocus("Calendar") end) hs.hotkey.bind({"ctrl"}, "a", function() hs.application.launchOrFocus("Slack") end) hs.hotkey.bind({"ctrl"}, "m", function() hs.application.launchOrFocus("Mail") end) hs.hotkey.bind({"ctrl"}, "l", function() hs.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend") end) -- Toggle Fullscreen hs.hotkey.bind({"ctrl"}, "f", function() local win = hs.window.focusedWindow() win:toggleFullScreen() end) -- Close active window hs.hotkey.bind({"ctrl"}, "x", function() local win = hs.window.focusedWindow() win:application():kill() end) -- Chrome reload hs.hotkey.bind({"ctrl"}, "i", function() local script = [[tell application "Chrome" to tell the active tab of its first window reload end tell]] hs.osascript.applescript(script) end) -- Autoconfig reload function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config reloaded !"}):send() end end local configWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
Fix hammerspoon chrome reload
Fix hammerspoon chrome reload
Lua
mit
Benoth/dotfiles,Benoth/dotfiles
78879ae8932f67023efcf0b6d5f76a6222a2630b
modulefiles/Core/lmod/SitePackage.lua
modulefiles/Core/lmod/SitePackage.lua
require("strict") local TIMEOUT = 5 local hook = require("Hook") local http = require("socket.http") 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 -- 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("USER") local site = os.getenv("OSG_SITE_NAME") local fhandle = io.popen('/bin/hostname -f', 'r') local host = fhandle:read() fhandle:close() 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://login.osgconnect.net:8080/?' uri = uri .. 'user=' .. url_quote(username) 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 TIMEOUT = 5 local hook = require("Hook") local http = require("socket.http") 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 -- 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("USER") if username == nil then username = '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 fhandle = io.open('/tmp/mod.log', 'a') fhandle:write("Module invocation load\n") fhandle:write(username) fhandle:write("\n") fhandle:write(site) fhandle:write("\n") fhandle:write(host) fhandle:write("\n") fhandle:write(t.modFullName) fhandle:write("\n") fhandle:close() 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://login.osgconnect.net:8080/?' uri = uri .. 'user=' .. url_quote(username) uri = uri .. '&module=' .. url_quote(t.modFullName) uri = uri .. '&site=' .. url_quote(site) uri = uri .. '&host=' .. url_quote(host) fhandle = io.open("/tmp/mod.log", 'a') fhandle:write(uri) fhandle:close() http.request(uri) end end hook.register("load",load_hook)
Fix up module tracking and add better handling of possibly missing values
Fix up module tracking and add better handling of possibly missing values
Lua
apache-2.0
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
ad30f7a43f07150b617118eab8b4831f2e1e26ee
wow/30-FontString-Text.lua
wow/30-FontString-Text.lua
require "wow/Frame"; require "rainback/AnchoredBound"; require "rainback/Graphics"; local Delegate = OOP.Class(); function Delegate:Constructor(frame) self.frame = frame; self.text = ""; self.font = Rainback.Font(); self.color = {0, 0, 0, 1}; frame:OnDelegateSet(function(category, delegate) if category ~= "layout" then return; end; self:AttachLayout(delegate); end); local delegate = frame:GetDelegate("layout"); if delegate then frame:AttachLayout(delegate); end; end; function Delegate:AttachLayout(delegate) if not delegate.GetBounds then return; end; local bounds = delegate:GetBounds(); if type(bounds) ~= "table" then return; end; if not bounds.GetNaturalHeight or not bounds.GetNaturalWidth then return; end; bounds.GetNaturalHeight = Override(self, "GetNaturalHeight"); bounds.GetNaturalWidth = Override(self, "GetNaturalWidth"); end; function Delegate:GetText() return self.text; end; function Delegate:SetText(text) self.text = tostring(text); Rainback.Update(); end; function Delegate:GetNaturalWidth(height) return self.font:width(self.text); end; function Delegate:GetNaturalHeight(width) return self.font:height(self.text, width); end; function Delegate:GetWrappedWidth() return self:GetNaturalWidth(); end; function Delegate:GetStringWidth() return self:GetNaturalWidth(); end; function Delegate:GetStringHeight() return self:GetNaturalHeight(); end; function Delegate:SetFont(family, size) self.font.family = family; self.font.pointSize = size; Rainback.Update(); end; function Delegate:GetFont() return self.font.family, self.folnt.pointSize; end; function Delegate:SetTextColor(r, g, b, a) self.color = {r, g, b, a}; Rainback.Update(); end; function Delegate:GetTextColor() return unpack(self.color); end; function Delegate:GetInternalFont() return self.font; end; function Delegate:ToString() return "[Rainback Text Delegate]"; end; WoW.SetFrameDelegate("FontString", "text", Delegate, "New");
require "wow/Frame"; require "rainback/AnchoredBound"; require "rainback/Graphics"; local Delegate = OOP.Class(); function Delegate:Constructor(frame) self.frame = frame; self.text = ""; self.font = Rainback.Font(); self.color = {0, 0, 0, 1}; frame:OnDelegateSet(function(category, delegate) if category ~= "layout" then return; end; self:AttachLayout(delegate); end); local delegate = frame:GetDelegate("layout"); if delegate then frame:AttachLayout(delegate); end; end; function Delegate:AttachLayout(delegate) if not delegate.GetBounds then return; end; local bounds = delegate:GetBounds(); if type(bounds) ~= "table" then return; end; if not bounds.GetNaturalHeight or not bounds.GetNaturalWidth then return; end; bounds.GetNaturalHeight = Override(self, "GetNaturalHeight"); bounds.GetNaturalWidth = Override(self, "GetNaturalWidth"); end; function Delegate:GetText() return self.text; end; function Delegate:SetText(text) self.text = tostring(text); Rainback.Update(); end; function Delegate:GetNaturalWidth(height) return self.font:width(self.text); end; function Delegate:GetNaturalHeight(width) return self.font:height(self.text, width); end; function Delegate:GetWrappedWidth() return self:GetNaturalWidth(); end; function Delegate:GetStringWidth() return self:GetNaturalWidth(); end; function Delegate:GetStringHeight() return self:GetNaturalHeight(); end; function Delegate:SetFont(family, size) self.font.family = family; if size then self.font.pointSize = size; end; Rainback.Update(); end; function Delegate:GetFont() return self.font.family, self.folnt.pointSize; end; function Delegate:SetTextColor(r, g, b, a) self.color = {r, g, b, a}; Rainback.Update(); end; function Delegate:GetTextColor() return unpack(self.color); end; function Delegate:GetInternalFont() return self.font; end; function Delegate:ToString() return "[Rainback Text Delegate]"; end; WoW.SetFrameDelegate("FontString", "text", Delegate, "New");
Fix a warning from Qt when the size is not given
Fix a warning from Qt when the size is not given
Lua
mit
Thonik/rainback
606ef840d04a81bdbc411b43dc6ada9472337abc
tocmenu.lua
tocmenu.lua
require "rendertext" require "keys" require "graphics" TOCMenu = { -- font for displaying file/dir names face = freetype.newBuiltinFace("cjk", 22), fhash = "s22", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 25), tfhash = "hbo25", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 40, -- spacing between lines spacing = 36, -- foot height foot_H = 27, -- state buffer toc = {}, items = 14, page = 1, current = 1, oldcurrent = 0, } function TOCMenu:new(toc) --@TODO set font here in the future 21.02 2012 --clearglyphcache() instance = self instance.toc = toc instance.items = #toc return instance end function TOCMenu:dump() for k,v in pairs(self.toc) do print("TOC item: "..k) for key,value in pairs(v) do print(" "..key..": "..value) end end end function TOCMenu:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), self.title_H + 10, 0) fb.bb:paintRect(30, ypos + 10, fb.bb:getWidth() - 60, self.title_H, 5) x = fb.bb:getWidth() - 260 -- move text to the right y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, self.tface, self.tfhash, "Table of Contents", true) -- draw font items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 30, y, self.face, self.fhash, (" "):rep(self.toc[i]["depth"]-1)..self.toc[i]["title"], true) end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then ev.code = adjustFWKey(ev.code) if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then return self.toc[perpage*(self.page-1)+self.current]["page"] elseif ev.code == KEY_BACK then return nil end end end end
require "rendertext" require "keys" require "graphics" TOCMenu = { -- font for displaying file/dir names face = freetype.newBuiltinFace("cjk", 22), fhash = "s22", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 25), tfhash = "hbo25", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 40, -- spacing between lines spacing = 36, -- foot height foot_H = 27, -- state buffer toc = {}, items = 14, page = 1, current = 1, oldcurrent = 0, } function TOCMenu:new(toc) --@TODO set font here in the future 21.02 2012 --clearglyphcache() instance = self instance.toc = toc instance.items = #toc return instance end function TOCMenu:dump() for k,v in pairs(self.toc) do print("TOC item: "..k) for key,value in pairs(v) do print(" "..key..": "..value) end end end function TOCMenu:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then markerdirty = true -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), self.title_H + 10, 0) fb.bb:paintRect(30, ypos + 10, fb.bb:getWidth() - 60, self.title_H, 5) x = fb.bb:getWidth() - 260 -- move text to the right y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, self.tface, self.tfhash, "Table of Contents", true) -- draw toc items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) if self.items == 0 then y = ypos + self.title_H + (self.spacing * 2) renderUtf8Text(fb.bb, 30, y, self.face, self.fhash, "Oops... Bad news for you:", true) y = y + self.spacing renderUtf8Text(fb.bb, 30, y, self.face, self.fhash, "This document does not have a Table of Conent.", true) markerdirty = false else local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 30, y, self.face, self.fhash, (" "):rep(self.toc[i]["depth"]-1)..self.toc[i]["title"], true) end end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H + 5 x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 8 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 8 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then ev.code = adjustFWKey(ev.code) if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then return self.toc[perpage*(self.page-1)+self.current]["page"] elseif ev.code == KEY_BACK then return nil end end end end
fix: two fixes for TOC menu
fix: two fixes for TOC menu * adjusted font spacing, looks better * handle pdf with no table of content
Lua
agpl-3.0
koreader/koreader-base,frankyifei/koreader,mihailim/koreader,frankyifei/koreader-base,houqp/koreader-base,houqp/koreader,frankyifei/koreader-base,chihyang/koreader,NiLuJe/koreader,ashang/koreader,chrox/koreader,Markismus/koreader,koreader/koreader,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader-base,Frenzie/koreader,koreader/koreader-base,apletnev/koreader-base,poire-z/koreader,noname007/koreader,koreader/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,pazos/koreader,poire-z/koreader,robert00s/koreader,NiLuJe/koreader-base,Frenzie/koreader-base,ashhher3/koreader,Frenzie/koreader,apletnev/koreader,apletnev/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,frankyifei/koreader-base,NiLuJe/koreader,mwoz123/koreader,apletnev/koreader-base,Hzj-jie/koreader-base,koreader/koreader,Frenzie/koreader-base,apletnev/koreader-base,Hzj-jie/koreader,Hzj-jie/koreader-base,NickSavage/koreader,lgeek/koreader,NiLuJe/koreader-base
fea1424cb20a3904eff1bbd9d0f6d0694a7283a9
lua/models.lua
lua/models.lua
--[ -- NN package model helpers. -- -- (c) 2014 Brandon L. Reiss --] require "nn" require "math" require "torch" require "RluMax" require "SgdMomentum" models = {} ---Append dataset information to a model. function models.append_ds_info(ds, mlp) mlp.time_sig = ds.time_sig mlp.dims = ds.logical_dims return mlp end ---Create a simple 2-layer NN. --Each output channel is taken in isolation using this architecture. The --filters in layer 2 are applied to each note channel and accumulated into the --hidden features with num_hidden per note track. The output layer is a linear --combination of these hidden features where each feature is still isolated to --a single note. function models.simple_2lnn_iso(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) mlp:add(nn.Linear(mlp.dims.input[2], num_hidden)) mlp:add(nn.RluMax()) mlp:add(nn.Linear(num_hidden, mlp.dims.output[2])) return mlp end ---Create a simple 2-layer NN. --Each output channel is a linear combination over all hidden features for all --note tracks. Therefore, the activation of note 1 is influenced by the --activation of all other notes. This requires more weights than the isolated --architecture. function models.simple_2lnn_cmb(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) local num_notes = mlp.dims.input[1] -- By transposing, we extract features over the notes for each time slice. mlp:add(nn.Transpose({1, 2})) mlp:add(nn.Linear(num_notes, num_hidden)) mlp:add(nn.RluMax()) -- Flatten the network. local flattened_len = mlp.dims.input[2] * num_hidden mlp:add(nn.Reshape(flattened_len)) -- Allow output channels to take features across notes. mlp:add(nn.Linear(flattened_len, num_notes * mlp.dims.output[2])) mlp:add(nn.Reshape(num_notes, mlp.dims.output[2])) return mlp end ---Create a simple 2-layer NN. --Each output channel is a linear combination over all hidden features for all --note tracks. Therefore, the activation of note 1 is influenced by the --activation of all other notes. This requires more weights than the isolated --architecture. function models.simple_2lnn_iso_cmb(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) local num_notes = mlp.dims.input[1] mlp:add(nn.Linear(mlp.input.dims[2], num_hidden)) mlp:add(nn.RluMax()) -- Flatten the network. local flattened_len = num_notes * num_hidden mlp:add(nn.Reshape(flattened_len)) -- Allow output channels to take features across notes. mlp:add(nn.Linear(flattened_len, num_notes * mlp.output.dims[2])) mlp:add(nn.Reshape(num_notes, mlp.output.dims[2])) return mlp end --- Train model using the given dataset. function models.train_model(ds, model, criterion, train_args) local train = ds.data_train() local trainer = nn.SgdMomentum(model, criterion, train_args) trainer:train(train) local train_loss = 0 for i = 1, train:size() do local X = train[i][1] local Y = train[i][2] local loss = criterion:forward(model:forward(X), Y) train_loss = train_loss + loss end local avg_train_loss = train_loss / train:size() local test_loss = 0 local test = ds.data_test() for i = 1, test:size() do local X = test[i][1] local Y = test[i][2] local loss = criterion:forward(model:forward(X), Y) test_loss = test_loss + loss end local avg_test_loss = test_loss / test:size() return avg_train_loss, avg_test_loss end --- Predict a song by seeding with input window x0. -- :param number length: the length of the song in output windows function models.predict(model, x0, length) if x0:size(1) ~= model.dims.input[1] or x0:size(2) ~= model.dims.input[2] then error(string.format("Seed point has incorrect dims (%d, %d) != (%d, %d)", x0:size(1), x0:size(2), model.dims.input[1], model.dims.input[2])) end local input_wnd = model.dims.input[2] local output_wnd = model.dims.output[2] local total_size = output_wnd * length local channel_dims = model.dims.input[1] local total_length = input_wnd + total_size local x0_song = torch.Tensor(channel_dims, total_length) local song = x0_song:narrow(2, input_wnd + 1, total_size) -- Copy first input to output buffer. x0_song:narrow(2, 1, input_wnd):copy(x0) for offset = 1, total_size, output_wnd do -- Predict next output_wnd and copy to the song. local X = x0_song:narrow(2, offset, input_wnd) local Y = model:forward(X) song:narrow(2, offset, output_wnd):copy(Y) print(string.format("predict() : t=%d/%d, max_ouput=% .4f", offset, total_size, Y:max())) end return song end return models
--[ -- NN package model helpers. -- -- (c) 2014 Brandon L. Reiss --] require "nn" require "math" require "torch" require "RluMax" require "SgdMomentum" models = {} ---Append dataset information to a model. function models.append_ds_info(ds, mlp) mlp.time_sig = ds.time_sig mlp.dims = ds.logical_dims return mlp end ---Create a simple 2-layer NN. --Each output channel is taken in isolation using this architecture. The --filters in layer 2 are applied to each note channel and accumulated into the --hidden features with num_hidden per note track. The output layer is a linear --combination of these hidden features where each feature is still isolated to --a single note. function models.simple_2lnn_iso(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) mlp:add(nn.Linear(mlp.dims.input[2], num_hidden)) mlp:add(nn.RluMax()) mlp:add(nn.Linear(num_hidden, mlp.dims.output[2])) return mlp end ---Create a simple 2-layer NN. --Each output channel is a linear combination over all hidden features for all --note tracks. Therefore, the activation of note 1 is influenced by the --activation of all other notes. This requires more weights than the isolated --architecture. function models.simple_2lnn_cmb(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) local num_notes = mlp.dims.input[1] -- By transposing, we extract features over the notes for each time slice. mlp:add(nn.Transpose({1, 2})) mlp:add(nn.Linear(num_notes, num_hidden)) mlp:add(nn.RluMax()) -- Flatten the network. local flattened_len = mlp.dims.input[2] * num_hidden mlp:add(nn.Reshape(flattened_len)) -- Allow output channels to take features across notes. mlp:add(nn.Linear(flattened_len, num_notes * mlp.dims.output[2])) mlp:add(nn.Reshape(num_notes, mlp.dims.output[2])) return mlp end ---Create a simple 2-layer NN. --Each output channel is a linear combination over all hidden features for all --note tracks. Therefore, the activation of note 1 is influenced by the --activation of all other notes. This requires more weights than the isolated --architecture. function models.simple_2lnn_iso_cmb(ds, num_hidden) local mlp = models.append_ds_info(ds, nn.Sequential()) local num_notes = mlp.dims.input[1] mlp:add(nn.Linear(mlp.dims.input[2], num_hidden)) mlp:add(nn.RluMax()) -- Flatten the network. local flattened_len = num_notes * num_hidden mlp:add(nn.Reshape(flattened_len)) -- Allow output channels to take features across notes. mlp:add(nn.Linear(flattened_len, num_notes * mlp.dims.output[2])) mlp:add(nn.Reshape(num_notes, mlp.dims.output[2])) return mlp end --- Train model using the given dataset. function models.train_model(ds, model, criterion, train_args) local train = ds.data_train() local trainer = nn.SgdMomentum(model, criterion, train_args) trainer:train(train) local train_loss = 0 for i = 1, train:size() do local X = train[i][1] local Y = train[i][2] local loss = criterion:forward(model:forward(X), Y) train_loss = train_loss + loss end local avg_train_loss = train_loss / train:size() local test_loss = 0 local test = ds.data_test() for i = 1, test:size() do local X = test[i][1] local Y = test[i][2] local loss = criterion:forward(model:forward(X), Y) test_loss = test_loss + loss end local avg_test_loss = test_loss / test:size() return avg_train_loss, avg_test_loss end --- Predict a song by seeding with input window x0. -- :param number length: the length of the song in output windows function models.predict(model, x0, length) if x0:size(1) ~= model.dims.input[1] or x0:size(2) ~= model.dims.input[2] then error(string.format("Seed point has incorrect dims (%d, %d) != (%d, %d)", x0:size(1), x0:size(2), model.dims.input[1], model.dims.input[2])) end local input_wnd = model.dims.input[2] local output_wnd = model.dims.output[2] local total_size = output_wnd * length local channel_dims = model.dims.input[1] local total_length = input_wnd + total_size local x0_song = torch.Tensor(channel_dims, total_length) local song = x0_song:narrow(2, input_wnd + 1, total_size) -- Copy first input to output buffer. x0_song:narrow(2, 1, input_wnd):copy(x0) for offset = 1, total_size, output_wnd do -- Predict next output_wnd and copy to the song. local X = x0_song:narrow(2, offset, input_wnd) local Y = model:forward(X) song:narrow(2, offset, output_wnd):copy(Y) print(string.format("predict() : t=%d/%d, max_ouput=% .4f", offset, total_size, Y:max())) end return song end return models
Fix dims usage in models.
Fix dims usage in models.
Lua
bsd-3-clause
blr246/midi-machine
5cb6744f364bbdafefcb5b0e75bd4485ea888bb4
extensions/hints/init.lua
extensions/hints/init.lua
--- === hs.hints === --- --- Switch focus with a transient per-application hotkey local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z, the numbers 0-9, and the punctuation characters: -=[];'\\,./\` hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "1","2","3","4","5","6","7","8","9","0", "-","=","[","]",";","'","\\",",",".","/","`"} local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.createHandler(char) return function() local win = hintDict[char] if win then win:focus() end hints.closeHints() modalKey:exit() end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for i,c in ipairs(hints.hintChars) do k:bind({}, c, hints.createHandler(c)) end return k end --- hs.hints.windowHints() --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, not all windows will receive a hint, and an error will be logged to the Hammerspoon Console function hints.windowHints() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() local numHints = 0 for i,_ in ipairs(hints.hintChars) do numHints = numHints + 1 end for i,win in ipairs(window.allWindows()) do local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:title() ~= "" and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} c = hints.bumpPos(c.x, c.y) if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else --print(win:title().." x:"..c.x.." y:"..c.y) -- debugging -- Check there are actually hint keys available local numOpenHints = 0 for x,_ in ipairs(openHints) do numOpenHints = numOpenHints + 1 end if numOpenHints < numHints then local hint = hints.new(c.x,c.y,hints.hintChars[numOpenHints+1],app:bundleID(),win:screen()) hintDict[hints.hintChars[numOpenHints+1]] = win table.insert(takenPositions, c) table.insert(openHints, hint) else print("hs.hints: Error: more windows than we have hint keys defined. See docs for hs.hints.hintChars") end end end end modalKey:enter() end function hints.closeHints() for i, hint in ipairs(openHints) do hint:close() end openHints = {} hintDict = {} takenPositions = {} end return hints
--- === hs.hints === --- --- Switch focus with a transient per-application hotkey local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z, the numbers 0-9, and the punctuation characters: -=[];'\\,./\` hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} --- hs.hints.style --- Variable --- If this is set to "vimperator", every window hint starts with the first character --- of the parent application's title hints.style = "vimperator" local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.addWindow(dict, win) local n = dict['count'] if n == nil then dict['count'] = 0 n = 0 end local m = (n % #hints.hintChars) + 1 local char = hints.hintChars[m] if n < #hints.hintChars then dict[char] = win else if type(dict[char]) == "userdata" then -- dict[m] is already occupied by another window -- which me must convert into a new dictionary local otherWindow = dict[char] dict[char] = {} hints.addWindow(dict, otherWindow) end hints.addWindow(dict[char], win) end dict['count'] = dict['count'] + 1 end function hints.displayHintsForDict(dict, prefixstring) for key, val in pairs(dict) do if type(val) == "userdata" then -- this is a window local win = val local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:title() ~= "" and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} c = hints.bumpPos(c.x, c.y) if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else -- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen()) table.insert(takenPositions, c) table.insert(openHints, hint) end end elseif type(val) == "table" then -- this is another window dict hints.displayHintsForDict(val, prefixstring .. key) end end end function hints.processChar(char) if hintDict[char] ~= nil then hints.closeHints() if type(hintDict[char]) == "userdata" then if hintDict[char] then hintDict[char]:focus() end modalKey:exit() elseif type(hintDict[char]) == "table" then hintDict = hintDict[char] takenPositions = {} hints.displayHintsForDict(hintDict, "") end end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for _, c in ipairs(hints.hintChars) do k:bind({}, c, function() hints.processChar(c) end) end return k end --- hs.hints.windowHints() --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, --- we resort to multi-character hints --- * If hints.style is set to "vimperator", every window hint is prefixed with the first --- character of the parent application's name function hints.windowHints() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() hintDict = {} for i, win in ipairs(window.allWindows()) do local app = win:application() if hints.style == "vimperator" then if app and win:title() ~= "" and win:isStandard() then local appchar = string.upper(string.sub(app:title(), 1, 1)) modalKey:bind({}, appchar, function() hints.processChar(appchar) end) if hintDict[appchar] == nil then hintDict[appchar] = {} end hints.addWindow(hintDict[appchar], win) end else hints.addWindow(hintDict, win) end end takenPositions = {} hints.displayHintsForDict(hintDict, "") modalKey:enter() end function hints.closeHints() for _, hint in ipairs(openHints) do hint:close() end openHints = {} takenPositions = {} end return hints
Implement vimperator-style hints
Implement vimperator-style hints Add hs.hints.style variable to control hinting style: hs.hints.style = "vimperator" creates multi-character hints, with the first character of each hint corresponding to the first character of the parent application's title hs.hints.style = "default" (or anything else) creates the usual single-character hints, unless the available hintChars are exhausted. In that case, Hammerspoon switches to multi-char hints (but without application title prefixes)
Lua
mit
asmagill/hammerspoon,hypebeast/hammerspoon,CommandPost/CommandPost-App,junkblocker/hammerspoon,bradparks/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,heptal/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,lowne/hammerspoon,cmsj/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,peterhajas/hammerspoon,Hammerspoon/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,knl/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,knu/hammerspoon,Stimim/hammerspoon,knl/hammerspoon,knu/hammerspoon,tmandry/hammerspoon,hypebeast/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,CommandPost/CommandPost-App,ocurr/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,dopcn/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,Hammerspoon/hammerspoon,wvierber/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,emoses/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,lowne/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,Stimim/hammerspoon,junkblocker/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,trishume/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,wsmith323/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,tmandry/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,joehanchoi/hammerspoon
6dc9f2aadc398f4d1a53fef4925d54fc9f32e299
src/lounge/lua/mplayer.lua
src/lounge/lua/mplayer.lua
#!/lounge/bin/janosh -f local util = require("util") Janosh:set("/player/active", "false") Janosh:setenv("http_proxy","http://localhost:1234/") Janosh:system("killall mplayer") local PID, STDIN, STDOUT, STDERR = Janosh:popen("bash", "-c", "exec mplayer -idle -input file=/dev/stdin 2>&1") Janosh:pclose(STDERR) --terminate mplayer and close loffile on exit --Janosh:exitHandler(function(sig) -- print("caught signal:", sig) -- Janosh:kill(PID) -- os.exit(1) --end) -- unset causes wierd errors Janosh:setenv("http_proxy","") local MplayerClass = {} -- the table representing the class, which will double as the metatable for the instances MplayerClass.__index = MplayerClass -- failed table lookups on the instances should fallback to the class table, to get methods function MplayerClass.new() return setmetatable({}, MplayerClass) end function MplayerClass.jump(self, idx) print("jump:", idx) obj = Janosh:get("/playlist/items/.") if tonumber(idx) > #obj then idx = #obj end file = obj[tonumber(idx)].url title = obj[tonumber(idx)].title self:cmd("pause") Janosh:trigger("/player/active", "true") util:notify("Loading: " .. title) self:cmd("loadfile " .. file) Janosh:trigger("/playlist/index", tostring(idx)) end function MplayerClass.previous(self) util:notify("previous") self:jump(tonumber(Janosh:get("/playlist/index").index) - 1) end function MplayerClass.next(self) util:notify("next") self:jump(tonumber(Janosh:get("/playlist/index").index) + 1) end function MplayerClass.enqueue(self, videoUrl, title, srcUrl) util:notify("Queued: " .. title) if title == "" then title = "(no title)" end size = Janosh:size("/playlist/items/.") Janosh:mkobj("/playlist/items/#" .. size .. "/.") Janosh:set("/playlist/items/#" .. size .. "/url", videoUrl) Janosh:set("/playlist/items/#" .. size .. "/title", title) Janosh:set("/playlist/items/#" .. size .. "/source", srcUrl) print("enqueuend") end function MplayerClass.add(self, videoUrl, title, srcUrl) self:enqueue(videoUrl, title, srcUrl) if Janosh:get("/player/active").active == "false" then self:jump(10000000) -- jump to the ned of the playlist end end function MplayerClass.run(self) print("run") SOTRACK="DEMUXER: ==> Found" EOTRACK="GLOBAL: EOF code: 1" PATH_CHANGED="GLOBAL: ANS_path=" CACHEEMPTY="Cache empty" while true do line="" while true do line = Janosh:preadLine(STDOUT) if line == nil then break end print(line) if string.find(line, EOTRACK) then self:eotrack() elseif string.find(line, SOTRACK) then self:sotrack() elseif string.find(line, CACHEEMPTY) then self:cache_empty() end end Janosh:sleep(1000) end end function MplayerClass.cmd(self, cmdstring) Janosh:lock("MplayerClass.cmd") print("cmd:", cmdstring) Janosh:pwrite(STDIN, cmdstring .. "\n") Janosh:unlock("MplayerClass.cmd") end function MplayerClass.forward(self) util:notify("Forward") self:cmd("seek +10") end function MplayerClass.forwardMore(self) util:notify("Forward more") self:cmd("seek +300") end function MplayerClass.rewind(self) util:notify("Rewind") self:cmd("seek -10") end function MplayerClass.rewindMore(self) util:notify("Rewind more") self:cmd("seek -300") end function MplayerClass.pause(self) util:notify("Pause") self:cmd("pause") end function MplayerClass.stop(self) util:notify("Stop") self:cmd("pause") self:cmd("stop") Janosh:transaction(function() if Janosh:get("/player/active").active == "true" then Janosh:trigger("/player/active","false") Janosh:publish("backgroundRefresh", "W", "") end end) end function MplayerClass.osd(self) self:cmd("osd") end function MplayerClass.subtitle(self) self:cmd("sub_visibility") end function MplayerClass.sotrack(self) end function MplayerClass.cache_empty(self) Janosh:trigger("/notify/message", "Network Problem!") end function MplayerClass.eotrack(self) print("eotrack") obj = Janosh:get("/playlist/.") idx = tonumber(obj.index) len = #obj.items print("idx: ", idx) print("len: ", len) if idx < len - 1 then self:jump(tostring(idx + 1)) else self:stop() end end function MplayerClass.loadFile(self,path) Janosh:trigger("/player/active", "true") self:cmd("loadfile " .. path) end return MplayerClass:new()
#!/lounge/bin/janosh -f local util = require("util") Janosh:set("/player/active", "false") Janosh:setenv("http_proxy","http://localhost:1234/") Janosh:system("killall mplayer") local PID, STDIN, STDOUT, STDERR = Janosh:popen("bash", "-c", "exec mplayer -idle -input file=/dev/stdin 2>&1") Janosh:pclose(STDERR) --terminate mplayer and close loffile on exit --Janosh:exitHandler(function(sig) -- print("caught signal:", sig) -- Janosh:kill(PID) -- os.exit(1) --end) -- unset causes wierd errors Janosh:setenv("http_proxy","") local MplayerClass = {} -- the table representing the class, which will double as the metatable for the instances MplayerClass.__index = MplayerClass -- failed table lookups on the instances should fallback to the class table, to get methods function MplayerClass.new() return setmetatable({}, MplayerClass) end function MplayerClass.jump(self, idx) print("jump:", idx) obj = Janosh:get("/playlist/items/.") if tonumber(idx) > #obj then idx = #obj end file = obj[tonumber(idx)].url title = obj[tonumber(idx)].title self:cmd("pause") Janosh:set_t("/player/active", "true") util:notify("Loading: " .. title) self:cmd("loadfile " .. file) Janosh:set_t("/playlist/index", tostring(idx)) end function MplayerClass.previous(self) util:notify("previous") self:jump(tonumber(Janosh:get("/playlist/index").index) - 1) end function MplayerClass.next(self) util:notify("next") self:jump(tonumber(Janosh:get("/playlist/index").index) + 1) end function MplayerClass.enqueue(self, videoUrl, title, srcUrl) util:notify("Queued: " .. title) if title == "" then title = "(no title)" end print("msize") size = Janosh:size("/playlist/items/.") Janosh:mkobj("/playlist/items/#" .. size .. "/.") Janosh:set("/playlist/items/#" .. size .. "/url", videoUrl) Janosh:set("/playlist/items/#" .. size .. "/title", title) Janosh:set("/playlist/items/#" .. size .. "/source", srcUrl) print("msizend") print("enqueuend") end function MplayerClass.add(self, videoUrl, title, srcUrl) self:enqueue(videoUrl, title, srcUrl) if Janosh:get("/player/active").active == "false" then self:jump(10000000) -- jump to the ned of the playlist end end function MplayerClass.run(self) print("run") SOTRACK="DEMUXER: ==> Found" EOTRACK="GLOBAL: EOF code: 1" PATH_CHANGED="GLOBAL: ANS_path=" CACHEEMPTY="Cache empty" while true do line="" while true do line = Janosh:preadLine(STDOUT) if line == nil then break end print(line) if string.find(line, EOTRACK) then self:eotrack() elseif string.find(line, SOTRACK) then self:sotrack() elseif string.find(line, CACHEEMPTY) then self:cache_empty() end end Janosh:sleep(1000) end end function MplayerClass.cmd(self, cmdstring) Janosh:lock("MplayerClass.cmd") print("cmd:", cmdstring) Janosh:pwrite(STDIN, cmdstring .. "\n") Janosh:unlock("MplayerClass.cmd") end function MplayerClass.forward(self) util:notify("Forward") self:cmd("seek +10") end function MplayerClass.forwardMore(self) util:notify("Forward more") self:cmd("seek +300") end function MplayerClass.rewind(self) util:notify("Rewind") self:cmd("seek -10") end function MplayerClass.rewindMore(self) util:notify("Rewind more") self:cmd("seek -300") end function MplayerClass.pause(self) util:notify("Pause") self:cmd("pause") end function MplayerClass.stop(self) util:notify("Stop") self:cmd("pause") self:cmd("stop") Janosh:transaction(function() if Janosh:get("/player/active").active == "true" then Janosh:set_t("/player/active","false") Janosh:publish("backgroundRefresh", "W", "") end end) end function MplayerClass.osd(self) self:cmd("osd") end function MplayerClass.subtitle(self) self:cmd("sub_visibility") end function MplayerClass.sotrack(self) end function MplayerClass.cache_empty(self) Janosh:publish("notifySend", "Network Problem!") end function MplayerClass.eotrack(self) print("eotrack") obj = Janosh:get("/playlist/.") idx = tonumber(obj.index) len = #obj.items print("idx: ", idx) print("len: ", len) if idx < len then self:jump(tostring(idx + 1)) else self:stop() end end function MplayerClass.loadFile(self,path) Janosh:set_t("/player/active", "true") self:cmd("loadfile " .. path) end return MplayerClass:new()
fixed old triggering
fixed old triggering
Lua
agpl-3.0
screeninvader/ScreenInvader,screeninvader/ScreenInvader
468dd4ac24f8ff2175f49c406e624992e9273dd7
test/ocmocks/robot.lua
test/ocmocks/robot.lua
local mockInv = require("test/ocmocks/mock_inventory") local robot = {} function robot.detect() return false, "air" end function robot.detectUp() return false, "air" end function robot.forward() print("robot: forward") return true end function robot.back() print("robot: back") return true end function robot.turnLeft() print("robot: turnLeft") return true end function robot.turnRight() print("robot: turnRight") return true end function robot.turnAround() print("robot: turnAround") return true end function robot.up() print("robot: up") --return false return true end function robot.down() print("robot: down") return true end function robot.inventorySize() return 32 end function robot.select(slot) print("robot: select " .. slot) mockInv.selected = slot end function robot.place() local stack = mockInv.get() if not stack or stack.count <= 0 then print("robot: place (fail)") return false, "empty slot" end stack.count = stack.count - 1 if stack.count <= 0 then mockInv.slots[mockInv.selected] = nil end print("robot: place " .. stack.name .. "(" .. stack.count .. ")") return true end function robot.placeUp() local stack = mockInv.get() if not stack or stack.count <= 0 then print("robot: placeUp (fail)") return false, "empty slot" end stack.count = stack.count - 1 if stack.count <= 0 then mockInv.slots[mockInv.selected] = nil end print("robot: placeUp " .. stack.name .. "(" .. stack.count .. ")") return true end package.preload.robot = function() return robot end
local mockInv = require("test/ocmocks/mock_inventory") local robot = {} function robot.detect() return false, "air" end function robot.detectUp() return false, "air" end function robot.forward() print("robot: forward") return true end function robot.back() print("robot: back") return true end function robot.turnLeft() print("robot: turnLeft") return true end function robot.turnRight() print("robot: turnRight") return true end function robot.turnAround() print("robot: turnAround") return true end function robot.up() print("robot: up") --return false return true end function robot.down() print("robot: down") return true end function robot.inventorySize() return 32 end function robot.select(slot) print("robot: select " .. slot) mockInv.selected = slot end function robot.place() local stack = mockInv.get() if not stack or stack.size <= 0 then print("robot: place (fail)") return false, "empty slot" end stack.size = stack.size - 1 if stack.size <= 0 then mockInv.slots[mockInv.selected] = nil end print("robot: place " .. stack.name .. "(" .. stack.size .. ")") return true end function robot.placeUp() local stack = mockInv.get() if not stack or stack.size <= 0 then print("robot: placeUp (fail)") return false, "empty slot" end stack.size = stack.size - 1 if stack.size <= 0 then mockInv.slots[mockInv.selected] = nil end print("robot: placeUp " .. stack.name .. "(" .. stack.size .. ")") return true end package.preload.robot = function() return robot end
fixes stack size usage
fixes stack size usage
Lua
apache-2.0
InfinitiesLoop/oclib
d2a583abd24a954b63949893813473b679b6ab76
lib/luvit/module.lua
lib/luvit/module.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 fs = require('fs') local path = require('path') local table = require('table') local module = {} -- This is the built-in require from lua. module.oldRequire = require local global_meta = {__index=_G} local function partialRealpath(filepath) -- Do some minimal realpathing local link link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) while link do filepath = path.resolve(path.dirname(filepath), link) link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) end return path.normalize(filepath) end local function myloadfile(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local code = fs.readFileSync(filepath) -- TODO: find out why inlining assert here breaks the require test local fn, err = loadstring(code, '@' .. filepath) assert(fn, err) local dirname = path.dirname(filepath) local realRequire = require setfenv(fn, setmetatable({ __filename = filepath, __dirname = dirname, require = function (filepath) return realRequire(filepath, dirname) end, }, global_meta)) local module = fn() package.loaded[filepath] = module return function() return module end end module.myloadfile = myloadfile local function myloadlib(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local name = path.basename(filepath) if name == "init.luvit" then name = path.basename(path.dirname(filepath)) end local base_name = name:sub(1, #name - 6) package.loaded[filepath] = base_name -- Hook to allow C modules to find their path local fn, error_message = package.loadlib(filepath, "luaopen_" .. base_name) if fn then local module = fn() package.loaded[filepath] = module return function() return module end end error(error_message) end -- tries to load a module at a specified absolute path local function loadModule(filepath, verbose) -- First, look for exact file match if the extension is given local extension = path.extname(filepath) if extension == ".lua" then return myloadfile(filepath) end if extension == ".luvit" then return myloadlib(filepath) end -- Then, look for module/package.lua config file if fs.existsSync(filepath .. "/package.lua") then local metadata = loadModule(filepath .. "/package.lua")() if metadata.main then return loadModule(path.join(filepath, metadata.main)) end end -- Try to load as either lua script or binary extension local fn = myloadfile(filepath .. ".lua") or myloadfile(filepath .. "/init.lua") or myloadlib(filepath .. ".luvit") or myloadlib(filepath .. "/init.luvit") if fn then return fn end return "\n\tCannot find module " .. filepath end -- Remove the cwd based loaders, we don't want them local builtinLoader = package.loaders[1] local base_path = process.cwd() local libpath = process.execPath:match('^(.*)' .. path.sep .. '[^' ..path.sep.. ']+' ..path.sep.. '[^' ..path.sep.. ']+$') ..path.sep.. 'lib' ..path.sep.. 'luvit' ..path.sep function module.require(filepath, dirname) if not dirname then dirname = base_path end -- Absolute and relative required modules local absolute_path if filepath:sub(1, path.root:len()) == path.root then absolute_path = path.normalize(filepath) elseif filepath:sub(1, 1) == "." then absolute_path = path.join(dirname, filepath) end if absolute_path then local loader = loadModule(absolute_path) if type(loader) == "function" then return loader() else error("Failed to find module '" .. filepath .."'") end end local errors = {} -- Builtin modules local module = package.loaded[filepath] if module then return module end if filepath:find("^[a-z_]+$") then local loader = builtinLoader(filepath) if type(loader) == "function" then module = loader() package.loaded[filepath] = module return module else errors[#errors + 1] = loader end end -- Library modules local loader = loadModule(libpath .. filepath) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end -- Bundled path modules local dir = dirname .. path.sep repeat dir = path.dirname(dir) local full_path = path.join(dir, "modules", filepath) local loader = loadModule(full_path) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end until dir == "." error("Failed to find module '" .. filepath .."'" .. table.concat(errors, "")) end package.loaders = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil return module
--[[ 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 fs = require('fs') local path = require('path') local table = require('table') local module = {} -- This is the built-in require from lua. module.oldRequire = require local global_meta = {__index=_G} local function partialRealpath(filepath) -- Do some minimal realpathing local link link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) while link do filepath = path.resolve(path.dirname(filepath), link) link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) end return path.normalize(filepath) end local function myloadfile(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local code = fs.readFileSync(filepath) -- TODO: find out why inlining assert here breaks the require test local fn, err = loadstring(code, '@' .. filepath) assert(fn, err) local dirname = path.dirname(filepath) local realRequire = require setfenv(fn, setmetatable({ __filename = filepath, __dirname = dirname, require = function (filepath) return realRequire(filepath, dirname) end, }, global_meta)) local module = fn() package.loaded[filepath] = module return function() return module end end module.myloadfile = myloadfile local function myloadlib(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local name = path.basename(filepath) if name == "init.luvit" then name = path.basename(path.dirname(filepath)) end local base_name = name:sub(1, #name - 6) package.loaded[filepath] = base_name -- Hook to allow C modules to find their path local fn, error_message = package.loadlib(filepath, "luaopen_" .. base_name) if fn then local module = fn() package.loaded[filepath] = module return function() return module end end error(error_message) end -- tries to load a module at a specified absolute path local function loadModule(filepath, verbose) -- First, look for exact file match if the extension is given local extension = path.extname(filepath) if extension == ".lua" then return myloadfile(filepath) end if extension == ".luvit" then return myloadlib(filepath) end -- Then, look for module/package.lua config file if fs.existsSync(filepath .. "/package.lua") then local metadata = loadModule(filepath .. "/package.lua")() if metadata.main then return loadModule(path.join(filepath, metadata.main)) end end -- Try to load as either lua script or binary extension local fn = myloadfile(filepath .. ".lua") or myloadfile(filepath .. "/init.lua") or myloadlib(filepath .. ".luvit") or myloadlib(filepath .. "/init.luvit") if fn then return fn end return "\n\tCannot find module " .. filepath end local builtinLoader = package.loaders[1] local base_path = process.cwd() local libpath = process.execPath:match('^(.*)' .. path.sep .. '[^' ..path.sep.. ']+' ..path.sep.. '[^' ..path.sep.. ']+$') ..path.sep.. 'lib' ..path.sep.. 'luvit' ..path.sep function module.require(filepath, dirname) if not dirname then dirname = base_path end -- Absolute and relative required modules local absolute_path if filepath:sub(1, path.root:len()) == path.root then absolute_path = path.normalize(filepath) elseif filepath:sub(1, 1) == "." then absolute_path = path.join(dirname, filepath) end if absolute_path then local loader = loadModule(absolute_path) if type(loader) == "function" then return loader() else error("Failed to find module '" .. filepath .."'") end end local errors = {} -- Builtin modules local module = package.loaded[filepath] if module then return module end if filepath:find("^[a-z_]+$") then local loader = builtinLoader(filepath) if type(loader) == "function" then module = loader() package.loaded[filepath] = module return module else errors[#errors + 1] = loader end end -- Library modules local loader = loadModule(libpath .. filepath) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end -- Bundled path modules local dir = dirname .. path.sep repeat local full_path = path.join(dir, "modules", filepath) local loader = loadModule(full_path) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end dir = path.dirname(dir) until dir == "." error("Failed to find module '" .. filepath .."'" .. table.concat(errors, "")) end -- Remove the cwd based loaders, we don't want them package.loaders = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil return module
Fix bundled search paths
Fix bundled search paths
Lua
apache-2.0
AndrewTsao/luvit,sousoux/luvit,sousoux/luvit,luvit/luvit,zhaozg/luvit,rjeli/luvit,DBarney/luvit,rjeli/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,AndrewTsao/luvit,boundary/luvit,AndrewTsao/luvit,rjeli/luvit,sousoux/luvit,sousoux/luvit,DBarney/luvit,sousoux/luvit,rjeli/luvit,kaustavha/luvit,boundary/luvit,boundary/luvit,zhaozg/luvit,bsn069/luvit,DBarney/luvit,boundary/luvit,boundary/luvit,connectFree/lev,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,luvit/luvit,sousoux/luvit,kaustavha/luvit,DBarney/luvit,connectFree/lev
6a069c2a1c99ca34f53af747a969d5f5c4044e84
src/promise/src/Shared/Utility/promiseChild.lua
src/promise/src/Shared/Utility/promiseChild.lua
--- Warps the WaitForChild API with a promise -- @module promiseChild local require = require(script.Parent.loader).load(script) local Promise = require("Promise") --- Wraps the :WaitForChild API with a promise return function(parent, name, timeOut) local result = parent:FindFirstChild(name) if result then return Promise.resolved(result) end return Promise.new(function(resolve, reject) -- Cheaper to do spawn() here than deferred, and we aren't going to get the -- resource for another tick anyway spawn(function() local child = parent:WaitForChild(name, timeOut) if child then resolve(child) else reject("Timed out") end end) end) end
--- Warps the WaitForChild API with a promise -- @module promiseChild local require = require(script.Parent.loader).load(script) local Promise = require("Promise") --- Wraps the :WaitForChild API with a promise return function(parent, name, timeOut) local result = parent:FindFirstChild(name) if result then return Promise.resolved(result) end return Promise.spawn(function(resolve, reject) local child = parent:WaitForChild(name, timeOut) if child then resolve(child) else reject("Timed out") end end) end
fix: Use Promies.spawn() since task.spawn() is probably cheaper now
fix: Use Promies.spawn() since task.spawn() is probably cheaper now
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
44dc61108886efd0eac5fcd29e1c73234d3b161c
mods/farming/api.lua
mods/farming/api.lua
-- Wear out hoes, place soil -- TODO Ignore group:flower farming.hoe_on_use = function(itemstack, user, pointed_thing, uses) local pt = pointed_thing -- check if pointing at a node if not pt then return end if pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local p = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z} local above = minetest.get_node(p) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] then return end if not minetest.registered_nodes[above.name] then return end -- check if the node above the pointed thing is air if above.name ~= "air" then return end -- check if pointing at soil if minetest.get_item_group(under.name, "soil") ~= 1 then return end -- check if (wet) soil defined local regN = minetest.registered_nodes if regN[under.name].soil == nil or regN[under.name].soil.wet == nil or regN[under.name].soil.dry == nil then return end -- turn the node into soil, wear out item and play sound minetest.set_node(pt.under, {name = regN[under.name].soil.dry}) minetest.sound_play("default_dig_crumbly", { pos = pt.under, gain = 0.5, }) if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/(uses-1)) end return itemstack end -- Register new hoes farming.register_hoe = function(name, def) -- Check for : prefix (register new hoes in your mod's namespace) if name:sub(1,1) ~= ":" then name = ":" .. name end -- Check def table if def.description == nil then def.description = "Hoe" end if def.inventory_image == nil then def.inventory_image = "unknown_item.png" end if def.recipe == nil then def.recipe = { {"air","air",""}, {"","group:stick",""}, {"","group:stick",""} } end if def.max_uses == nil then def.max_uses = 30 end -- Register the tool minetest.register_tool(name, { description = def.description, inventory_image = def.inventory_image, on_use = function(itemstack, user, pointed_thing) return farming.hoe_on_use(itemstack, user, pointed_thing, def.max_uses) end }) -- Register its recipe minetest.register_craft({ output = name:gsub(":", "", 1), recipe = def.recipe }) end -- Seed placement farming.place_seed = function(itemstack, placer, pointed_thing, plantname) local pt = pointed_thing -- check if pointing at a node if not pt then return end if pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local above = minetest.get_node(pt.above) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] then return end if not minetest.registered_nodes[above.name] then return end -- check if pointing at the top of the node if pt.above.y ~= pt.under.y+1 then return end -- check if you can replace the node above the pointed node if not minetest.registered_nodes[above.name].buildable_to then return end -- check if pointing at soil if minetest.get_item_group(under.name, "soil") < 2 then return end -- add the node and remove 1 item from the itemstack minetest.add_node(pt.above, {name = plantname, param2 = 1}) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end -- Register plants farming.register_plant = function(name, def) local mname = name:split(":")[1] local pname = name:split(":")[2] -- Check def table if not def.description then def.description = "Seed" end if not def.inventory_image then def.inventory_image = "unknown_item.png" end if not def.steps then return nil end if not def.minlight then def.minlight = 1 end if not def.maxlight then def.maxlight = 14 end if not def.fertility then def.fertility = {} end -- Register seed local g = {seed = 1, snappy = 3, attached_node = 1} for k, v in pairs(def.fertility) do g[v] = 1 end minetest.register_node(":" .. mname .. ":seed_" .. pname, { description = def.description, tiles = {def.inventory_image}, inventory_image = def.inventory_image, wield_image = def.inventory_image, drawtype = "signlike", groups = g, paramtype = "light", paramtype2 = "wallmounted", walkable = false, sunlight_propagates = true, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, fertility = def.fertility, on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, mname .. ":seed_" .. pname) end }) -- Register harvest minetest.register_craftitem(":" .. mname .. ":" .. pname, { description = pname:gsub("^%l", string.upper), inventory_image = mname .. "_" .. pname .. ".png", }) -- Register growing steps for i=1,def.steps do local drop = { items = { {items = {mname .. ":" .. pname}, rarity = 9 - i}, {items = {mname .. ":" .. pname}, rarity= 18 - i * 2}, {items = {mname .. ":seed_" .. pname}, rarity = 9 - i}, {items = {mname .. ":seed_" .. pname}, rarity = 18 - i * 2}, } } local nodegroups = {snappy = 3, flammable = 2, plant = 1, not_in_creative_inventory = 1, attached_node = 1} nodegroups[pname] = i minetest.register_node(mname .. ":" .. pname .. "_" .. i, { drawtype = "plantlike", waving = 1, tiles = {mname .. "_" .. pname .. "_" .. i .. ".png"}, paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = drop, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, groups = nodegroups, sounds = default.node_sound_leaves_defaults(), }) end -- Growing ABM minetest.register_abm({ nodenames = {"group:" .. pname, "group:seed"}, neighbors = {"group:soil"}, interval = 90, chance = 2, action = function(pos, node) local plant_height = minetest.get_item_group(node.name, pname) -- return if already full grown if plant_height == def.steps then return end local node_def = minetest.registered_items[node.name] or nil -- grow seed if minetest.get_item_group(node.name, "seed") and node_def.fertility then local can_grow = false local soil_node = minetest.get_node_or_nil({x = pos.x, y = pos.y - 1, z = pos.z}) for _, v in pairs(node_def.fertility) do if minetest.get_item_group(soil_node.name, v) ~= 0 then can_grow = true end end if can_grow then minetest.set_node(pos, {name = node.name:gsub("seed_", "") .. "_1"}) end return end -- check if on wet soil pos.y = pos.y - 1 local n = minetest.get_node(pos) if minetest.get_item_group(n.name, "soil") < 3 then return end pos.y = pos.y + 1 -- check light local ll = minetest.get_node_light(pos) if not ll or ll < def.minlight or ll > def.maxlight then return end -- grow minetest.set_node(pos, {name = mname .. ":" .. pname .. "_" .. plant_height + 1}) end }) -- Return local r = { seed = mname .. ":seed_" .. pname, harvest = mname .. ":" .. pname } return r end
-- Wear out hoes, place soil -- TODO Ignore group:flower farming.hoe_on_use = function(itemstack, user, pointed_thing, uses) local pt = pointed_thing -- check if pointing at a node if not pt then return end if pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local p = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z} local above = minetest.get_node(p) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] then return end if not minetest.registered_nodes[above.name] then return end -- check if the node above the pointed thing is air if above.name ~= "air" then return end -- check if pointing at soil if minetest.get_item_group(under.name, "soil") ~= 1 then return end -- check if (wet) soil defined local regN = minetest.registered_nodes if regN[under.name].soil == nil or regN[under.name].soil.wet == nil or regN[under.name].soil.dry == nil then return end -- turn the node into soil, wear out item and play sound minetest.set_node(pt.under, {name = regN[under.name].soil.dry}) minetest.sound_play("default_dig_crumbly", { pos = pt.under, gain = 0.5, }) if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/(uses-1)) end return itemstack end -- Register new hoes farming.register_hoe = function(name, def) -- Check for : prefix (register new hoes in your mod's namespace) if name:sub(1,1) ~= ":" then name = ":" .. name end -- Check def table if def.description == nil then def.description = "Hoe" end if def.inventory_image == nil then def.inventory_image = "unknown_item.png" end if def.recipe == nil then def.recipe = { {"air","air",""}, {"","group:stick",""}, {"","group:stick",""} } end if def.max_uses == nil then def.max_uses = 30 end -- Register the tool minetest.register_tool(name, { description = def.description, inventory_image = def.inventory_image, on_use = function(itemstack, user, pointed_thing) return farming.hoe_on_use(itemstack, user, pointed_thing, def.max_uses) end }) -- Register its recipe minetest.register_craft({ output = name:gsub(":", "", 1), recipe = def.recipe }) end -- Seed placement farming.place_seed = function(itemstack, placer, pointed_thing, plantname) local pt = pointed_thing -- check if pointing at a node if not pt then return end if pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local above = minetest.get_node(pt.above) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] then return end if not minetest.registered_nodes[above.name] then return end -- check if pointing at the top of the node if pt.above.y ~= pt.under.y+1 then return end -- check if you can replace the node above the pointed node if not minetest.registered_nodes[above.name].buildable_to then return end -- check if pointing at soil if minetest.get_item_group(under.name, "soil") < 2 then return end -- add the node and remove 1 item from the itemstack minetest.add_node(pt.above, {name = plantname, param2 = 1}) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end -- Register plants farming.register_plant = function(name, def) local mname = name:split(":")[1] local pname = name:split(":")[2] -- Check def table if not def.description then def.description = "Seed" end if not def.inventory_image then def.inventory_image = "unknown_item.png" end if not def.steps then return nil end if not def.minlight then def.minlight = 1 end if not def.maxlight then def.maxlight = 14 end if not def.fertility then def.fertility = {} end -- Register seed local g = {seed = 1, snappy = 3, attached_node = 1} for k, v in pairs(def.fertility) do g[v] = 1 end minetest.register_node(":" .. mname .. ":seed_" .. pname, { description = def.description, tiles = {def.inventory_image}, inventory_image = def.inventory_image, wield_image = def.inventory_image, drawtype = "signlike", groups = g, paramtype = "light", paramtype2 = "wallmounted", walkable = false, sunlight_propagates = true, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, fertility = def.fertility, on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, mname .. ":seed_" .. pname) end }) -- Register harvest minetest.register_craftitem(":" .. mname .. ":" .. pname, { description = pname:gsub("^%l", string.upper), inventory_image = mname .. "_" .. pname .. ".png", }) -- Register growing steps for i=1,def.steps do local drop = { items = { {items = {mname .. ":" .. pname}, rarity = 9 - i}, {items = {mname .. ":" .. pname}, rarity= 18 - i * 2}, {items = {mname .. ":seed_" .. pname}, rarity = 9 - i}, {items = {mname .. ":seed_" .. pname}, rarity = 18 - i * 2}, } } local nodegroups = {snappy = 3, flammable = 2, plant = 1, not_in_creative_inventory = 1, attached_node = 1} nodegroups[pname] = i minetest.register_node(mname .. ":" .. pname .. "_" .. i, { drawtype = "plantlike", waving = 1, tiles = {mname .. "_" .. pname .. "_" .. i .. ".png"}, paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = drop, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, groups = nodegroups, sounds = default.node_sound_leaves_defaults(), }) end -- Growing ABM minetest.register_abm({ nodenames = {"group:" .. pname, "group:seed"}, neighbors = {"group:soil"}, interval = 90, chance = 2, action = function(pos, node) local plant_height = minetest.get_item_group(node.name, pname) -- return if already full grown if plant_height == def.steps then return end local node_def = minetest.registered_items[node.name] or nil -- grow seed if minetest.get_item_group(node.name, "seed") and node_def.fertility then local can_grow = false local soil_node = minetest.get_node_or_nil({x = pos.x, y = pos.y - 1, z = pos.z}) if not soil_node then return end for _, v in pairs(node_def.fertility) do if minetest.get_item_group(soil_node.name, v) ~= 0 then can_grow = true end end if can_grow then minetest.set_node(pos, {name = node.name:gsub("seed_", "") .. "_1"}) end return end -- check if on wet soil pos.y = pos.y - 1 local n = minetest.get_node(pos) if minetest.get_item_group(n.name, "soil") < 3 then return end pos.y = pos.y + 1 -- check light local ll = minetest.get_node_light(pos) if not ll or ll < def.minlight or ll > def.maxlight then return end -- grow minetest.set_node(pos, {name = mname .. ":" .. pname .. "_" .. plant_height + 1}) end }) -- Return local r = { seed = mname .. ":seed_" .. pname, harvest = mname .. ":" .. pname } return r end
Fix farming unloaded node crash
Fix farming unloaded node crash
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
3b4b30ff3c38f8bba6bf880915104da2af53b9e9
lib/luchador/storage.lua
lib/luchador/storage.lua
local sha1 = require "luchador.sha1" local serializer = require "luchador.serializer" local zlib = require "zlib" local namespace = 'LC_' local Storage = {} local mt = {__index = Storage} function Storage.new(datastore, page_key_filter) local storage = {datastore = datastore, page_key_filter = page_key_filter} setmetatable(storage, mt) return storage end function Storage:page_key() local key = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.request_uri if self.page_key_filter then key = self.page_key_filter(key, self.datastore) end return sha1.digest_base64(key) end function Storage:get_metadata(req_h) local metadata = self:get(self:page_key()) if metadata == nil then return nil else ngx.log(ngx.INFO, "HIT") for _, metadata in pairs(metadata) do local cached_vary_key = metadata[1] local cached_req_h = metadata[2] local cached_resp_h = metadata[3] if cached_resp_h['Vary'] then if cached_vary_key == self.vary_key(cached_resp_h['Vary'], req_h) then return cached_resp_h end else return cached_resp_h end end end end function Storage:store_metadata(req_h, resp_h, digest_key, ttl) if resp_h["Date"] == nil then resp_h["Date"] = ngx.http_time(ngx.time()) end resp_h['X-Content-Digest'] = digest_key resp_h['Set-Cookie'] = nil local k = self:page_key() local h = (self:get(k) or {}) local vk = self.vary_key(resp_h['Vary'], req_h) local vary_position = 1 for i,v in ipairs(h) do if v[1] == vk then vary_position = i else vary_position = i + 1 end end local cached_vary_val = {vk, req_h, resp_h} h[vary_position] = cached_vary_val self:set(k, h, ttl) end function Storage.vary_key(vary, req_h) local vk = {} if vary then for h in vary:gmatch("[^ ,]+") do h = h:lower() table.insert(vk, req_h[h] or '') end end return table.concat(vk) end function Storage:get_page(metadata) if not (metadata == nil) then local digest = metadata["X-Content-Digest"] if not (digest == nil) then return self:get(digest, false) end end end function Storage:store_page(resp, req_h) if not (resp.status == 200) then -- TODO cache all response codes rack cache does return false end local ttl = resp:ttl() if ttl == nil or ttl == '0' then return false end ngx.log(ngx.INFO, "MISS" .. ngx.var.request_uri) local digest_key = ngx.md5(resp.body) local h = resp.header['Content-Type'] if h:match('text') or h:match('application') then resp.body = zlib.compress(resp.body, zlib.BEST_COMPRESSION, nil, 15+16) resp.header["Content-Encoding"] = "gzip" else resp.header['Content-Encoding'] = nil end self:store_metadata(req_h, resp.header, digest_key, ttl) self:set(digest_key, resp.body, ttl) return true end function Storage:get_lock() local r, err = ngx.shared.cache:add(self:page_key() .. 'lock', true, 15) return r end function Storage:release_lock() return ngx.shared.cache:delete(self:page_key() .. 'lock') end function Storage:set(key, val, ttl) key = namespace .. key val = {val = val, ttl = ttl, created = ngx.time()} val = serializer.serialize(val) ngx.shared.cache:set(key, self.datastore:set(key, val, ttl), ttl) ngx.shared.cache:flush_expired(5) end function Storage:get(key) local locally_cached = false local entry = ngx.shared.cache:get(key) key = namespace .. key if entry then locally_cached = true else entry = self.datastore:get(key) end local thawed if entry then thawed = serializer.deserialize(entry) end if thawed then if not locally_cached then local age = (ngx.time() - thawed.created) ngx.shared.cache:set(key, entry, thawed.ttl - age) end return thawed.val end end function Storage:keepalive() self.datastore:keepalive() end return Storage
local sha1 = require "luchador.sha1" local serializer = require "luchador.serializer" local zlib = require "zlib" local namespace = 'LC_' local Storage = {} local mt = {__index = Storage} function Storage.new(datastore, page_key_filter) local storage = {datastore = datastore, page_key_filter = page_key_filter} setmetatable(storage, mt) return storage end function Storage:page_key() local key = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.request_uri if self.page_key_filter then key = self.page_key_filter(key, self.datastore) end return sha1.digest_base64(key) end function Storage:get_metadata(req_h) local metadata = self:get(self:page_key()) if metadata == nil then return nil else ngx.log(ngx.INFO, "HIT") for _, metadata in pairs(metadata) do local cached_vary_key = metadata[1] local cached_req_h = metadata[2] local cached_resp_h = metadata[3] if cached_resp_h['Vary'] then if cached_vary_key == self.vary_key(cached_resp_h['Vary'], req_h) then return cached_resp_h end else return cached_resp_h end end end end function Storage:store_metadata(req_h, resp_h, digest_key, ttl) if resp_h["Date"] == nil then resp_h["Date"] = ngx.http_time(ngx.time()) end resp_h['X-Content-Digest'] = digest_key resp_h['Set-Cookie'] = nil local k = self:page_key() local h = (self:get(k) or {}) local vk = self.vary_key(resp_h['Vary'], req_h) local vary_position = 1 for i,v in ipairs(h) do if v[1] == vk then vary_position = i else vary_position = i + 1 end end local cached_vary_val = {vk, req_h, resp_h} h[vary_position] = cached_vary_val self:set(k, h, ttl) end function Storage.vary_key(vary, req_h) local vk = {} if vary then for h in vary:gmatch("[^ ,]+") do h = h:lower() table.insert(vk, req_h[h] or '') end end return table.concat(vk) end function Storage:get_page(metadata) if not (metadata == nil) then local digest = metadata["X-Content-Digest"] if not (digest == nil) then return self:get(digest, false) end end end function Storage:store_page(resp, req_h) if not (resp.status == 200) then -- TODO cache all response codes rack cache does return false end local ttl = resp:ttl() if ttl == nil or ttl == '0' then return false end ngx.log(ngx.INFO, "MISS" .. ngx.var.request_uri) local digest_key = ngx.md5(resp.body) local h = resp.header['Content-Type'] if h:match('text') or h:match('application') then resp.body = zlib.compress(resp.body, zlib.BEST_COMPRESSION, nil, 15+16) resp.header["Content-Encoding"] = "gzip" else resp.header['Content-Encoding'] = nil end self:store_metadata(req_h, resp.header, digest_key, ttl) self:set(digest_key, resp.body, ttl) return true end function Storage:get_lock() local r, err = ngx.shared.cache:add(self:page_key() .. 'lock', true, 15) return r end function Storage:release_lock() return ngx.shared.cache:delete(self:page_key() .. 'lock') end function Storage:set(key, val, ttl) key = namespace .. key val = {val = val, ttl = ttl, created = ngx.time()} val = serializer.serialize(val) ngx.shared.cache:set(key, self.datastore:set(key, val, ttl), ttl) ngx.shared.cache:flush_expired(5) end function Storage:get(key) key = namespace .. key local locally_cached = false local entry = ngx.shared.cache:get(key) if entry then locally_cached = true else entry = self.datastore:get(key) end local thawed if entry then thawed = serializer.deserialize(entry) end if thawed then if not locally_cached then local age = (ngx.time() - thawed.created) ngx.shared.cache:set(key, entry, thawed.ttl - age) end return thawed.val end end function Storage:keepalive() self.datastore:keepalive() end return Storage
Fix local cache get bug
Fix local cache get bug
Lua
mit
maxjustus/luchador
f20ca2d43ad91599f6b16f1ecb7b9508f7f60ba2
core/ext/find.lua
core/ext/find.lua
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then if next then buffer:goto_pos(buffer.current_pos + increment) buffer:search_anchor() result = buffer:search_next(flags, text) else buffer:goto_pos(buffer.anchor - increment) buffer:search_anchor() result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain Lua escape -- sequences to use text captured by a Lua pattern. (%n where 1 <= n <= 9.) function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('[^%%]?[^%%]?%%'..i, v) -- not entirely correct end end buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then if next then buffer:goto_pos(buffer.current_pos + increment) buffer:search_anchor() result = buffer:search_next(flags, text) else buffer:goto_pos(buffer.anchor - increment) buffer:search_anchor() result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain both Lua -- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %() -- sequences for embedding Lua code for any search. function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() rtext = rtext:gsub('%%%%', '\\037') -- escape '%%' if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('%%'..i, v) end end local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())', function(code) local ret, val = pcall( loadstring('return '..code) ) if not ret then os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"') error() end return val end ) if ret then rtext = rtext:gsub('\\037', '%%') -- unescape '%' buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement else -- Since find is called after replace returns, have it 'find' the current -- text again, rather than the next occurance so the user can fix the error. buffer:goto_pos(buffer.current_pos) end end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
Fixed escapes in replace, added %() sequence; core/ext/find.lua '%%' is now properly escaped. %() sequence executes Lua code, showing an error dialog if one occured.
Fixed escapes in replace, added %() sequence; core/ext/find.lua '%%' is now properly escaped. %() sequence executes Lua code, showing an error dialog if one occured.
Lua
mit
rgieseke/textadept,rgieseke/textadept
27c2fcf2e9d369d0b7b7619bb6d4167336e12e0a
config/sipi.init-knora.lua
config/sipi.init-knora.lua
-- -- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, -- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. -- This file is part of Sipi. -- Sipi is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- Sipi is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- Additional permission under GNU AGPL version 3 section 7: -- If you modify this Program, or any covered work, by linking or combining -- it with Kakadu (or a modified version of that library), containing parts -- covered by the terms of the Kakadu Software Licence, the licensors of this -- Program grant you additional permission to convey the resulting work. -- See the GNU Affero General Public License for more details. -- You should have received a copy of the GNU Affero General Public -- License along with Sipi. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- This function is being called from sipi before the file is served -- Knora is called to ask for the user's permissions on the file -- Parameters: -- prefix: This is the prefix that is given on the IIIF url -- identifier: the identifier for the image -- cookie: The cookie that may be present -- -- Returns: -- permission: -- 'allow' : the view is allowed with the given IIIF parameters -- 'restrict:watermark=<path-to-watermark>' : Add a watermark -- 'restrict:size=<iiif-size-string>' : reduce size/resolution -- 'deny' : no access! -- filepath: server-path where the master file is located ------------------------------------------------------------------------------- function pre_flight(prefix, identifier, cookie) if config.prefix_as_path then filepath = config.imgroot .. '/' .. prefix .. '/' .. identifier else filepath = config.imgroot .. '/' .. identifier end if prefix == "thumbs" then -- always allow thumbnails return 'allow', filepath end if prefix == "tmp" then -- always deny access to tmp folder return 'deny' end -- comment this in if you do not want to do a preflight request -- print("ignoring permissions") -- do return 'allow', filepath end knora_cookie_header = nil if cookie ~='' then key = string.sub(cookie, 0, 4) if (key ~= "sid=") then -- cookie key is not valid print("cookie key is invalid") else session_id = string.sub(cookie, 5) knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id } end end knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier print("knora_url: " .. knora_url) result = server.http("GET", knora_url, knora_cookie_header, 5000) -- check HTTP request was successful if not result.success then print("Request to Knora failed: " .. result.errmsg) -- deny request return 'deny' end if result.status_code ~= 200 then print("Knora returned HTTP status code " .. ret.status) print(result.body) return 'deny' end response_json = server.json_to_table(result.body) print("status: " .. response_json.status) print("permission code: " .. response_json.permissionCode) if response_json.status ~= 0 then -- something went wrong with the request, Knora returned a non zero status return 'deny' end if response_json.permissionCode == 0 then -- no view permission on file return 'deny' elseif response_json.permissionCode == 1 then -- restricted view permission on file -- either watermark or size (depends on project, should be returned with permission code by Sipi responder) return 'restrict:size=' .. config.thumb_size, filepath elseif response_json.permissionCode >= 2 then -- full view permissions on file return 'allow', filepath else -- invalid permission code return 'deny' end end -------------------------------------------------------------------------------
-- -- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, -- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. -- This file is part of Sipi. -- Sipi is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- Sipi is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- Additional permission under GNU AGPL version 3 section 7: -- If you modify this Program, or any covered work, by linking or combining -- it with Kakadu (or a modified version of that library), containing parts -- covered by the terms of the Kakadu Software Licence, the licensors of this -- Program grant you additional permission to convey the resulting work. -- See the GNU Affero General Public License for more details. -- You should have received a copy of the GNU Affero General Public -- License along with Sipi. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- This function is being called from sipi before the file is served -- Knora is called to ask for the user's permissions on the file -- Parameters: -- prefix: This is the prefix that is given on the IIIF url -- identifier: the identifier for the image -- cookie: The cookie that may be present -- -- Returns: -- permission: -- 'allow' : the view is allowed with the given IIIF parameters -- 'restrict:watermark=<path-to-watermark>' : Add a watermark -- 'restrict:size=<iiif-size-string>' : reduce size/resolution -- 'deny' : no access! -- filepath: server-path where the master file is located ------------------------------------------------------------------------------- function pre_flight(prefix, identifier, cookie) if config.prefix_as_path then filepath = config.imgroot .. '/' .. prefix .. '/' .. identifier else filepath = config.imgroot .. '/' .. identifier end if prefix == "thumbs" then -- always allow thumbnails return 'allow', filepath end if prefix == "tmp" then -- always deny access to tmp folder return 'deny' end -- comment this in if you do not want to do a preflight request -- print("ignoring permissions") -- do return 'allow', filepath end knora_cookie_header = nil if cookie ~='' then -- tries to extract the Knora session id from the cookie: -- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs) -- returns nil if it cannot find it session_id = string.match(cookie, "sid=(%d+);?") if session_id == nil then -- no session_id could be extracted print("cookie key is invalid") else knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id } end end knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier print("knora_url: " .. knora_url) result = server.http("GET", knora_url, knora_cookie_header, 5000) -- check HTTP request was successful if not result.success then print("Request to Knora failed: " .. result.errmsg) -- deny request return 'deny' end if result.status_code ~= 200 then print("Knora returned HTTP status code " .. ret.status) print(result.body) return 'deny' end response_json = server.json_to_table(result.body) print("status: " .. response_json.status) print("permission code: " .. response_json.permissionCode) if response_json.status ~= 0 then -- something went wrong with the request, Knora returned a non zero status return 'deny' end if response_json.permissionCode == 0 then -- no view permission on file return 'deny' elseif response_json.permissionCode == 1 then -- restricted view permission on file -- either watermark or size (depends on project, should be returned with permission code by Sipi responder) return 'restrict:size=' .. config.thumb_size, filepath elseif response_json.permissionCode >= 2 then -- full view permissions on file return 'allow', filepath else -- invalid permission code return 'deny' end end -------------------------------------------------------------------------------
refactor (session cookie): use a regex to get session id from cookie
refactor (session cookie): use a regex to get session id from cookie - fixes the problem that sometimes the cookie contains only other information that sid
Lua
agpl-3.0
dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi
2b224122928f5aa7602870415f47f8f3e06e0d71
premake/premake4.lua
premake/premake4.lua
-- -- Copyright 2010-2013 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- solution "bx" configurations { "Debug", "Release", } platforms { "x32", "x64", "Native", -- for targets where bitness is not specified } language "C++" BX_DIR = (path.getabsolute("..") .. "/") local BX_BUILD_DIR = (BX_DIR .. ".build/") local BX_THIRD_PARTY_DIR = (BX_DIR .. "3rdparty/") defines { "BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1" } dofile (BX_DIR .. "premake/toolchain.lua") toolchain(BX_BUILD_DIR, BX_THIRD_PARTY_DIR) function copyLib() end dofile "bx.lua" dofile "unittest++.lua" project "bx.test" uuid "8a653da8-23d6-11e3-acb4-887628d43830" kind "ConsoleApp" debugdir (BX_DIR .. "tests") includedirs { BX_DIR .. "include", BX_THIRD_PARTY_DIR .. "UnitTest++/src/", } links { "UnitTest++", } files { BX_DIR .. "tests/**.cpp", BX_DIR .. "tests/**.H", } configuration { "vs*" } configuration { "android*" } kind "ConsoleApp" targetextension ".so" linkoptions { "-shared", } configuration { "nacl or nacl-arm" } kind "ConsoleApp" targetextension ".nexe" links { "ppapi", "pthread", } configuration { "pnacl" } kind "ConsoleApp" targetextension ".pexe" links { "ppapi", "pthread", } configuration { "linux-*" } links { "pthread", } configuration {}
-- -- Copyright 2010-2013 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- solution "bx" configurations { "Debug", "Release", } platforms { "x32", "x64", "Native", -- for targets where bitness is not specified } language "C++" BX_DIR = (path.getabsolute("..") .. "/") local BX_BUILD_DIR = (BX_DIR .. ".build/") local BX_THIRD_PARTY_DIR = (BX_DIR .. "3rdparty/") defines { "BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1" } dofile (BX_DIR .. "premake/toolchain.lua") toolchain(BX_BUILD_DIR, BX_THIRD_PARTY_DIR) function copyLib() end dofile "bx.lua" dofile "unittest++.lua" project "bx.test" uuid "8a653da8-23d6-11e3-acb4-887628d43830" kind "ConsoleApp" debugdir (BX_DIR .. "tests") includedirs { BX_DIR .. "include", BX_THIRD_PARTY_DIR .. "UnitTest++/src/", } links { "UnitTest++", } files { BX_DIR .. "tests/**.cpp", BX_DIR .. "tests/**.H", } configuration { "vs*" } configuration { "android*" } kind "ConsoleApp" targetextension ".so" linkoptions { "-shared", } configuration { "nacl or nacl-arm" } kind "ConsoleApp" targetextension ".nexe" links { "ppapi", "pthread", } configuration { "pnacl" } kind "ConsoleApp" targetextension ".pexe" links { "ppapi", "pthread", } configuration { "linux-*" } links { "pthread", } configuration { "osx" } links { "Cocoa.framework", } configuration {}
Fixed OSX linking.
Fixed OSX linking.
Lua
bsd-2-clause
septag/termite,pigpigyyy/bx,mmicko/bx,attilaz/bx,coconutxin/bx,dariomanesku/bx,MikePopoloski/bx,ShuangxueBai/bx,bkaradzic/bx,fluffyfreak/bx,septag/termite,OlegOAndreev/bx,dariomanesku/bx,septag/termite,BlueCrystalLabs/bx,0-wiz-0/bx,septag/bx,u-engine/bx,BlueCrystalLabs/bx,ShuangxueBai/bx,mmicko/bx,septag/termite,septag/termite,OlegOAndreev/bx,attilaz/bx,septag/termite,septag/bx,bkaradzic/bx,u-engine/bx,MikePopoloski/bx,pigpigyyy/bx,0-wiz-0/bx,fluffyfreak/bx,coconutxin/bx
d5e004be67447b5b20185c3428e8930cea025fc6
worldedit_commands/cuboid.lua
worldedit_commands/cuboid.lua
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "<amount> [h|v]", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "<amount> [h|v]", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "[x|y|z|?|up|down|left|right|front|back] [+|-]<amount>", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, direction, amount = param:find("([%?%l]+)%s*([+-]?%d+)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction ~= "?" then axis, dir = worldedit.translate_direction(name, direction) else axis, dir = worldedit.player_axis(name) end if axis == nil or dir == nil then return false, "Invalid" end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, reverse_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -reverse_amount) worldedit.marker_update(name) end, } )
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "[h|v] <amount>", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("([hv]?)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "[h|v] <amount>", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("([hv]?)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "[x|y|z|?|up|down|left|right|front|back] [+|-]<amount>", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, direction, amount = param:find("([%?%l]+)%s*([+-]?%d+)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction ~= "?" then axis, dir = worldedit.translate_direction(name, direction) else axis, dir = worldedit.player_axis(name) end if axis == nil or dir == nil then return false, "Invalid" end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, reverse_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -reverse_amount) worldedit.marker_update(name) end, } )
Fix /outset and /inset to conform to WE standards
Fix /outset and /inset to conform to WE standards
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
4f11b8df5ad91f4622cfb7ddd0ed34ab569b089f
dbmodule.lua
dbmodule.lua
-- db module local dbmodule = {} local config = require "config" local sqlite3 = require "lsqlite3" scriptdb = config.scriptdb -- see if the file exists function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then print "El archivo no existe" os.exit() end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end function connectDB(method) if method then db = sqlite3.open( scriptdb, method) else db = sqlite3.open(scriptdb) end return db end function findAll(table) local db = connectDB() for row in db:nrows("Select name from "..table.." ") do print(">>> "..row.name) end end function dbmodule.InitSetup(method) local db = connectDB(scriptdb,method) print("Creating Database :"..scriptdb) local sm = db:prepare [[ create table scripts( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, author TEXT NULL); ]] sm:step() print("Creating Table For Script ....") sm:finalize() local cat = db:prepare [[ create table categories( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL); ]] cat:step() print("Creating Table for Categories .... ") cat:finalize() local sc = db:prepare [[ create table script_category( id_category INTEGER NOT NULL, id_script INETGER NOT NULL); ]] sc:step() print("Creating Table for Scripts per Category ....") sc:finalize() local categoryList = config.categories print("Upload Categories to Categories Table ...") for k,v in ipairs(categoryList) do sql=[[insert into categories (name) Values (]].."'".. v .. "'"..[[);]] db:exec(sql) end db:close() end function dbmodule.InsertScript(value,table) local db = connectDB(scriptdb,"wc") for i,v in ipairs(value) do sql=[[insert into ]]..table..[[ (name) Values (]].."'".. v .. "'"..[[);]] db:exec(sql) last_rowid = db:last_insert_rowid(sql) end db:close() return last_rowid end function dbmodule.InsertCategory(id_script,id_category) local db = connectDB(scriptdb,"wc") sql=[[insert into script_category (id_category,id_script) Values (]].. id_category ..",".. id_script ..[[);]] db:exec(sql) db:close() end function dbmodule.SearchByCat(catName) scripts = {} local db = connectDB("wc") for row in db:nrows("select scripts.name from scripts, categories, script_category where categories.name='"..catName.."' and scripts.id=script_category.id_script and categories.id=script_category.id_category") do table.insert(scripts,row.name) end if #scripts > 0 then print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n") for k,v in ipairs(scripts) do print(k.." "..v) end else print("Not Results Found\n") print("=== These are the enabled Categories ===\n") findAll("categories") end db:close() end function dbmodule.findScript(scriptName) local nse = {} local db= connectDB() for row in db:nrows("select name from scripts where name like '%"..scriptName.."%'") do table.insert(nse,row.name) end if #nse > 0 then print("\nTotal Scripts Found "..#nse.."\n") for k,v in ipairs(nse) do print(k.." "..v) end io.write('Do yo want more info about any script, choose the script using id [1-'..#nse..'] ') local option = io.read("*n") print(nse[option]) if nse[option] then -- tests the functions above local file = config.scriptsPath..nse[option] local lines = lines_from(file) for k,v in pairs(lines) do local i = string.find(v, "license") if not i then print(v) else break end end end else print("Not Results Found\n") io.write("Do you want search again? [y/n] ") local action = io.read() if action == 'y' then print("Sorry action disable, try later") end end end return dbmodule
-- db module local dbmodule = {} local config = require "config" local sqlite3 = require "lsqlite3" scriptdb = config.scriptdb local helper = require "helper" -- see if the file exists function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then print "El archivo no existe" os.exit() end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end function connectDB(method) if method then db = sqlite3.open( scriptdb, method) else db = sqlite3.open(scriptdb) end return db end function findAll(table) local db = connectDB() for row in db:nrows("Select name from "..table.." ") do print(">>> "..row.name) end end function dbmodule.InitSetup(method) local db = connectDB(scriptdb,method) print("Creating Database :"..scriptdb) local sm = db:prepare [[ create table scripts( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, author TEXT NULL); ]] sm:step() print("Creating Table For Script ....") sm:finalize() local cat = db:prepare [[ create table categories( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL); ]] cat:step() print("Creating Table for Categories .... ") cat:finalize() local sc = db:prepare [[ create table script_category( id_category INTEGER NOT NULL, id_script INETGER NOT NULL); ]] sc:step() print("Creating Table for Scripts per Category ....") sc:finalize() local categoryList = config.categories print("Upload Categories to Categories Table ...") for k,v in ipairs(categoryList) do sql=[[insert into categories (name) Values (]].."'".. v .. "'"..[[);]] db:exec(sql) end db:close() end function dbmodule.InsertScript(value,table) local db = connectDB(scriptdb,"wc") for i,v in ipairs(value) do sql=[[insert into ]]..table..[[ (name) Values (]].."'".. v .. "'"..[[);]] db:exec(sql) last_rowid = db:last_insert_rowid(sql) end db:close() return last_rowid end function dbmodule.InsertCategory(id_script,id_category) local db = connectDB(scriptdb,"wc") sql=[[insert into script_category (id_category,id_script) Values (]].. id_category ..",".. id_script ..[[);]] db:exec(sql) db:close() end function dbmodule.SearchByCat(catName) scripts = {} local db = connectDB("wc") for row in db:nrows("select scripts.name from scripts, categories, script_category where categories.name='"..catName.."' and scripts.id=script_category.id_script and categories.id=script_category.id_category") do table.insert(scripts,row.name) end if #scripts > 0 then print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n") for k,v in ipairs(scripts) do print(k.." "..v) end else print("Not Results Found\n") print("=== These are the enabled Categories ===\n") findAll("categories") end db:close() end function dbmodule.findScript(scriptName) local nse = {} local db= connectDB() for row in db:nrows("select name from scripts where name like '%"..scriptName.."%'") do table.insert(nse,row.name) end if #nse > 0 then print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nTotal Scripts Found "..#nse.."\n") for k,v in ipairs(nse) do print(k.." "..v) end io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] ') local option = io.read("*n") if nse[option] then print("\n") -- tests the functions above local file = config.scriptsPath..nse[option] local lines = lines_from(file) for k,v in pairs(lines) do local i = string.find(v, "license") if not i then print(v) else break end end end else print("Not Results Found\n") io.write("Do you want search again? [y/n] ") local action = io.read() if action == 'y' then print("Sorry action disable, try later") end end end return dbmodule
Fixing Read Script Menu Help
Fixing Read Script Menu Help
Lua
apache-2.0
JKO/nsearch,JKO/nsearch
431c158a65017a1e8aa2a611b454534f2aa383f1
tests/actions/vstudio/vc2010/test_debug_settings.lua
tests/actions/vstudio/vc2010/test_debug_settings.lua
-- -- tests/actions/vstudio/vc2010/test_debug_settings.lua -- Validate handling of the working directory for debugging. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs2010_debug_settings") local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc2010.debugSettings(cfg) end -- -- If no debug directory is set, nothing should be output. -- function suite.noOutput_onNoDebugDir() prepare() test.isemptycapture() end -- -- The debug command should specified relative to the project location. -- function suite.debugCommand_isProjectRelative() debugcommand "bin/emulator.exe" prepare() test.capture [[ <LocalDebuggerCommand>bin\emulator.exe</LocalDebuggerCommand> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> ]] end -- -- The debug directory should specified relative to the project location. -- function suite.debugDirectory_isProjectRelative() debugdir "bin/debug" prepare() test.capture [[ <LocalDebuggerWorkingDirectory>bin\debug</LocalDebuggerWorkingDirectory> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> ]] end -- -- Verify handling of debug arguments. -- function suite.debuggerCommandArgs_onDebugArgs() debugargs { "arg1", "arg2" } prepare() test.capture [[ <LocalDebuggerCommandArguments>arg1 arg2</LocalDebuggerCommandArguments> ]] end -- -- Check the handling of debug environment variables. -- function suite.localDebuggerEnv_onDebugEnv() debugenvs { "key=value" } prepare() test.capture [[ <LocalDebuggerEnvironment>key=value</LocalDebuggerEnvironment> ]] end -- -- Multiple environment variables should be separated by a "\n" sequence. -- function suite.localDebuggerEnv_onDebugEnv() debugenvs { "key=value", "foo=bar" } prepare() test.capture [[ <LocalDebuggerEnvironment>key=value foo=bar</LocalDebuggerEnvironment> ]] end
-- -- tests/actions/vstudio/vc2010/test_debug_settings.lua -- Validate handling of the working directory for debugging. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs2010_debug_settings") local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc2010.debugSettings(cfg) end -- -- If no debug directory is set, nothing should be output. -- function suite.noOutput_onNoDebugDir() prepare() test.isemptycapture() end -- -- The debug command should specified relative to the project location. -- function suite.debugCommand_isProjectRelative() debugcommand "bin/emulator.exe" prepare() expectedPath = path.translate(path.getabsolute(os.getcwd())) .. "\\bin\\emulator.exe" expected = "<LocalDebuggerCommand>" .. expectedPath .. "</LocalDebuggerCommand>" expected = expected .. "\n<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>" test.capture (expected) end -- -- The debug directory should specified relative to the project location. -- function suite.debugDirectory_isProjectRelative() debugdir "bin/debug" prepare() test.capture [[ <LocalDebuggerWorkingDirectory>bin\debug</LocalDebuggerWorkingDirectory> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> ]] end -- -- Verify handling of debug arguments. -- function suite.debuggerCommandArgs_onDebugArgs() debugargs { "arg1", "arg2" } prepare() test.capture [[ <LocalDebuggerCommandArguments>arg1 arg2</LocalDebuggerCommandArguments> ]] end -- -- Check the handling of debug environment variables. -- function suite.localDebuggerEnv_onDebugEnv() debugenvs { "key=value" } prepare() test.capture [[ <LocalDebuggerEnvironment>key=value</LocalDebuggerEnvironment> ]] end -- -- Multiple environment variables should be separated by a "\n" sequence. -- function suite.localDebuggerEnv_onDebugEnv() debugenvs { "key=value", "foo=bar" } prepare() test.capture [[ <LocalDebuggerEnvironment>key=value foo=bar</LocalDebuggerEnvironment> ]] end
Fixed test for debugcommand for vc2010 action
Fixed test for debugcommand for vc2010 action
Lua
bsd-3-clause
mendsley/premake-core,mandersan/premake-core,Tiger66639/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,premake/premake-core,prapin/premake-core,jsfdez/premake-core,Blizzard/premake-core,lizh06/premake-core,LORgames/premake-core,resetnow/premake-core,tritao/premake-core,saberhawk/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,Blizzard/premake-core,soundsrc/premake-core,saberhawk/premake-core,tritao/premake-core,lizh06/premake-core,starkos/premake-core,resetnow/premake-core,dcourtois/premake-core,Blizzard/premake-core,Tiger66639/premake-core,LORgames/premake-core,Tiger66639/premake-core,PlexChat/premake-core,Meoo/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,sleepingwit/premake-core,noresources/premake-core,dcourtois/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,akaStiX/premake-core,Meoo/premake-core,martin-traverse/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,premake/premake-core,soundsrc/premake-core,Yhgenomics/premake-core,Blizzard/premake-core,tvandijck/premake-core,tvandijck/premake-core,starkos/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,soundsrc/premake-core,lizh06/premake-core,TurkeyMan/premake-core,xriss/premake-core,premake/premake-core,xriss/premake-core,kankaristo/premake-core,soundsrc/premake-core,noresources/premake-core,prapin/premake-core,noresources/premake-core,LORgames/premake-core,noresources/premake-core,mandersan/premake-core,alarouche/premake-core,mandersan/premake-core,prapin/premake-core,martin-traverse/premake-core,TurkeyMan/premake-core,Meoo/premake-core,martin-traverse/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,jstewart-amd/premake-core,soundsrc/premake-core,mendsley/premake-core,mendsley/premake-core,LORgames/premake-core,jsfdez/premake-core,resetnow/premake-core,saberhawk/premake-core,mendsley/premake-core,TurkeyMan/premake-core,noresources/premake-core,Blizzard/premake-core,xriss/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,premake/premake-core,Yhgenomics/premake-core,felipeprov/premake-core,aleksijuvani/premake-core,akaStiX/premake-core,TurkeyMan/premake-core,xriss/premake-core,martin-traverse/premake-core,premake/premake-core,Zefiros-Software/premake-core,kankaristo/premake-core,CodeAnxiety/premake-core,jsfdez/premake-core,PlexChat/premake-core,premake/premake-core,mendsley/premake-core,prapin/premake-core,aleksijuvani/premake-core,kankaristo/premake-core,Zefiros-Software/premake-core,starkos/premake-core,sleepingwit/premake-core,saberhawk/premake-core,felipeprov/premake-core,mandersan/premake-core,Tiger66639/premake-core,noresources/premake-core,starkos/premake-core,tritao/premake-core,felipeprov/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,PlexChat/premake-core,Zefiros-Software/premake-core,felipeprov/premake-core,noresources/premake-core,starkos/premake-core,sleepingwit/premake-core,Meoo/premake-core,akaStiX/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,starkos/premake-core,jsfdez/premake-core,akaStiX/premake-core,CodeAnxiety/premake-core,Blizzard/premake-core,dcourtois/premake-core,alarouche/premake-core,bravnsgaard/premake-core,lizh06/premake-core,LORgames/premake-core,dcourtois/premake-core,alarouche/premake-core,starkos/premake-core,tritao/premake-core,premake/premake-core,resetnow/premake-core,mandersan/premake-core,tvandijck/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,resetnow/premake-core,xriss/premake-core,kankaristo/premake-core
6aabc62f7353c2eb7ae515550bd2f18703fb7ffd
frontend/apps/reader/modules/readerconfig.lua
frontend/apps/reader/modules/readerconfig.lua
local ConfigDialog = require("ui/widget/configdialog") local InputContainer = require("ui/widget/container/inputcontainer") local Device = require("ui/device") local GestureRange = require("ui/gesturerange") local Geom = require("ui/geometry") local Screen = require("ui/screen") local Event = require("ui/event") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end end function ReaderConfig:initGesListener() self.ges_events = { TapShowConfigMenu = { GestureRange:new{ ges = "tap", range = Geom:new{ x = Screen:getWidth()*DTAP_ZONE_CONFIG.x, y = Screen:getHeight()*DTAP_ZONE_CONFIG.y, w = Screen:getWidth()*DTAP_ZONE_CONFIG.w, h = Screen:getHeight()*DTAP_ZONE_CONFIG.h, } } } } end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() self:onShowConfigMenu() return true end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() self.config_dialog:closeDialog() end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") self.last_panel_index = config:readSetting("config_panel_index") or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
local ConfigDialog = require("ui/widget/configdialog") local InputContainer = require("ui/widget/container/inputcontainer") local Device = require("ui/device") local GestureRange = require("ui/gesturerange") local Geom = require("ui/geometry") local Screen = require("ui/screen") local Event = require("ui/event") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end end function ReaderConfig:initGesListener() self.ges_events = { TapShowConfigMenu = { GestureRange:new{ ges = "tap", range = Geom:new{ x = Screen:getWidth()*DTAP_ZONE_CONFIG.x, y = Screen:getHeight()*DTAP_ZONE_CONFIG.y, w = Screen:getWidth()*DTAP_ZONE_CONFIG.w, h = Screen:getHeight()*DTAP_ZONE_CONFIG.h, } } } } end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() self:onShowConfigMenu() return true end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") self.last_panel_index = config:readSetting("config_panel_index") or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
fix(reader): crash on closing reader menu
fix(reader): crash on closing reader menu
Lua
agpl-3.0
koreader/koreader,pazos/koreader,poire-z/koreader,Hzj-jie/koreader,Frenzie/koreader,Markismus/koreader,frankyifei/koreader,ashang/koreader,ashhher3/koreader,NickSavage/koreader,chihyang/koreader,robert00s/koreader,houqp/koreader,NiLuJe/koreader,koreader/koreader,chrox/koreader,mwoz123/koreader,noname007/koreader,lgeek/koreader,poire-z/koreader,NiLuJe/koreader,apletnev/koreader,Frenzie/koreader,mihailim/koreader
eb39186e8b762cfe51761b56e1f7b8ac5df1ddae
backends/sky-rts/lua/city_attack.lua
backends/sky-rts/lua/city_attack.lua
function gen_tower(rng, x, y, faction, out) types = {"Small Tower", "Big Tower", "Small City", "Big City"} tower_type = rng:rand_int(1,#types+1) -- Only select cities ~40% of the time if tower_type > 2 and rng:rand_double(0,1) < 0.6 then tower_type = tower_type - 2 end tower = { pos = {x=x, y=y}, faction = faction, unit_type = types[tower_type], } if tower_type == 1 then tower.hp = rng:rand_double(15, 50) elseif tower_type == 2 then tower.hp = rng:rand_double(15, 70) else -- Only friendly cities for now tower.faction = 0 tower.hp = rng:rand_double(50, 70) end table.insert(out, tower) end function roll_ship(rng, units, agent) cities = {} for i,tower in pairs(units) do if tower.unit_type ~= "Ship" and tower.faction == 0 and (tower.unit_type == "Small City" or tower.unit_type == "Big City") then table.insert(cities, i) end end if #cities == 0 then return false end roll = rng:rand_double(0,1) if roll < 0.6 then return false end which = rng:rand_int(1, #cities+1) idx = cities[which] tower = units[idx] -- Find how far we need to spawn the ship from the tower -- to be outside it (at least mostly) -- -- Code for towers is left in for legacy reasons (i.e. in case we want to go back to it) if tower.unit_type == "Big Tower" then scale = 5 * math.sqrt(2) / 2 elseif tower.unit_type == "Small Tower" then scale = 3 * math.sqrt(2) / 2 elseif tower.unit_type == "Small City" then scale = 1.5 elseif tower.unit_type == "Big City" then scale = 3 end -- Find unit vector from tower to agent -- and scale to needed value x = tower.pos.x - agent.pos.x y = tower.pos.y - agent.pos.y norm = math.sqrt(x*x + y*y) x = x / norm y = y / norm x = x * scale y = y * scale enemy_ship = { pos = {x = tower.pos.x - x, y = tower.pos.y - y}, unit_type = "Ship", faction = 1, hp = rng:rand_double(5.0, 25.0) } -- The python code just attacks the index corresponding to the -- given entity, so this hack lets us select the ship as if it -- were the tower in that quadrant automagically units[idx] = enemy_ship table.insert(units, tower) end function _reset(rng, data) local agent = { pos = {x=20.0, y=20.0}, unit_type="Ship", faction=0, } out = {} table.insert(out, agent) for i = 4,1,-1 do x_max = (( (i-1) // 2) + 1) * 20.0 - 5.5 y_max = (( (i-1) % 2) + 1) * 20.0 - 5.5 x = rng:rand_double(x_max - 2.5, x_max) y = rng:rand_double(y_max - 2.5, y_max) faction_weight = rng:rand_double(0.0, 1.0) -- About a 70% chance of a tower being an enemy. -- May tweak if faction_weight < 0.7 then faction = 1 else faction = 0 end gen_tower(rng, x, y, faction, out) end roll_ship(rng, out, agent) return out end function sky_reset(rng) return _reset(rng, nil) end function on_spawn(world, unit) world:override_skip(true) end function sky_init() local factions = 2 local unit_types= {} unit_types[1] = { tag = "Ship", max_hp = 80, shape = { body="triangle", base_len=2.0, }, kill_reward=0, kill_type="Enemy Destroyed", dmg_deal_type="Enemy Damaged", death_penalty=0, damage_recv_penalty=0, damage_deal_reward=0, speed=40.0, attack_range=0.3, attack_dmg=10, attack_delay=0.2, } unit_types[2] = { tag="Small Tower", max_hp = 50, shape = { body="rect", width=3.0, height=3.0, }, can_move=false, kill_reward=50, kill_type="Enemy Destroyed", death_type="Friend Destroyed", dmg_recv_type="Friend Damaged", dmg_deal_type="Enemy Damaged", attack_range=0.3, attack_dmg=5, attack_delay=0.2, } unit_types[3] = { tag="Big Tower", max_hp=70, shape = { body="rect", width=5.0, height=5.0, }, can_move=false, kill_reward=70, kill_type="Enemy Destroyed", death_type="Friend Destroyed", dmg_recv_type="Friend Damaged", dmg_deal_type="Enemy Damaged", attack_range=0.3, attack_dmg=10, attack_delay=0.2, } unit_types[4] = { tag="Big City", max_hp=70, shape = { body="circle", radius=3, }, can_move=false, kill_reward=-115, death_penalty=-115, kill_type="City Destroyed", death_type="City Destroyed", dmg_recv_type="City Damaged", dmg_deal_type="City Damaged", damage_deal_reward=-10, damage_recv_penalty=-10, attack_range=0, attack_dmg=0, attack_delay=999, } unit_types[5] = { tag="Small City", max_hp=70, shape = { body="circle", radius=1.5, }, can_move=false, kill_reward=-100, death_penalty=-100, kill_type="City Destroyed", death_type="City Destroyed", dmg_recv_type="City Damaged", dmg_deal_type="City Damaged", damage_deal_reward=-10, damage_recv_penalty=-10, attack_range=0, attack_dmg=0, attack_delay=999, } return { unit_types = unit_types, factions=factions, victory_reward=0, failure_penalty=0, reward_types={"Enemy Destroyed", "Friend Destroyed", "City Destroyed", "City Damaged", "Friend Damaged", "Enemy Damaged", "Living"}, } end function on_death(world, dead, cause) -- Filter out the enemy ship killing a tower/being killed by a tower if (cause:unit_type() == "Ship" and cause:faction() == 1 and dead:unit_type() ~= "Ship") -- (dead:unit_type() == "Ship" and dead:faction() == 1 and cause:unit_type() ~= "Ship") -- Note: we need to actually filter this out because otherwise games can stall indefinitely then return end world:emit_reward(1, "Living") if dead:unit_type() == "Ship" and dead:faction() == 0 then world:victory(0) return end world:delete_all() -- We'll just use our reset function to generate -- the next board and tweak it to our liking new_board = _reset(world:rng(), world) for _k,entity in pairs(new_board) do -- Carry over agent HP to next iteration if entity.unit_type == "Ship" and entity.faction == 0 then entity.hp = cause:hp() -- Due to the nature of the scenario, if the agent didn't die they caused the death end world:spawn(entity) end end
function gen_tower(rng, x, y, faction, out) types = {"Small Tower", "Big Tower", "Small City", "Big City"} tower_type = rng:rand_int(1,#types+1) -- Only select cities ~40% of the time if tower_type > 2 and rng:rand_double(0,1) < 0.6 then tower_type = tower_type - 2 end tower = { pos = {x=x, y=y}, faction = faction, unit_type = types[tower_type], } if tower_type == 1 then tower.hp = rng:rand_double(15, 50) elseif tower_type == 2 then tower.hp = rng:rand_double(15, 70) else -- Only friendly cities for now tower.faction = 0 tower.hp = rng:rand_double(50, 70) end table.insert(out, tower) end function roll_ship(rng, units, agent) cities = {} for i,tower in pairs(units) do if tower.unit_type ~= "Ship" and tower.faction == 0 and (tower.unit_type == "Small City" or tower.unit_type == "Big City") then table.insert(cities, i) end end if #cities == 0 then return false end roll = rng:rand_double(0,1) if roll < 0.6 then return false end which = rng:rand_int(1, #cities+1) idx = cities[which] tower = units[idx] -- Find how far we need to spawn the ship from the tower -- to be outside it (at least mostly) -- -- Code for towers is left in for legacy reasons (i.e. in case we want to go back to it) if tower.unit_type == "Big Tower" then scale = 5 * math.sqrt(2) / 2 elseif tower.unit_type == "Small Tower" then scale = 3 * math.sqrt(2) / 2 elseif tower.unit_type == "Small City" then scale = 1.5 elseif tower.unit_type == "Big City" then scale = 3 end -- Find unit vector from tower to agent -- and scale to needed value x = tower.pos.x - agent.pos.x y = tower.pos.y - agent.pos.y norm = math.sqrt(x*x + y*y) x = x / norm y = y / norm x = x * scale y = y * scale enemy_ship = { pos = {x = tower.pos.x - x, y = tower.pos.y - y}, unit_type = "Ship", faction = 1, hp = rng:rand_double(5.0, 25.0) } -- The python code just attacks the index corresponding to the -- given entity, so this hack lets us select the ship as if it -- were the tower in that quadrant automagically units[idx] = enemy_ship table.insert(units, tower) end function _reset(rng, data) local agent = { pos = {x=20.0, y=20.0}, unit_type="Ship", faction=0, } out = {} table.insert(out, agent) for i = 4,1,-1 do x_max = (( (i-1) // 2) + 1) * 20.0 - 5.5 y_max = (( (i-1) % 2) + 1) * 20.0 - 5.5 x = rng:rand_double(x_max - 2.5, x_max) y = rng:rand_double(y_max - 2.5, y_max) faction_weight = rng:rand_double(0.0, 1.0) -- About a 70% chance of a tower being an enemy. -- May tweak if faction_weight < 0.7 then faction = 1 else faction = 0 end gen_tower(rng, x, y, faction, out) end roll_ship(rng, out, agent) return out end function sky_reset(rng) return _reset(rng, nil) end function on_spawn(world, unit) world:override_skip(true) end function sky_init() local factions = 2 local unit_types= {} unit_types[1] = { tag = "Ship", max_hp = 80, shape = { body="triangle", base_len=2.0, }, kill_reward=0, kill_type="Enemy Destroyed", dmg_deal_type="Enemy Damaged", death_penalty=0, damage_recv_penalty=0, -- damage_deal_reward=0, speed=40.0, attack_range=0.3, attack_dmg=10, attack_delay=0.2, } unit_types[2] = { tag="Small Tower", max_hp = 50, shape = { body="rect", width=3.0, height=3.0, }, can_move=false, kill_reward=50, kill_type="Enemy Destroyed", death_type="Friend Destroyed", dmg_recv_type="Friend Damaged", dmg_deal_type="Enemy Damaged", damage_recv_penalty=-10, attack_range=0.3, attack_dmg=5, attack_delay=0.2, } unit_types[3] = { tag="Big Tower", max_hp=70, shape = { body="rect", width=5.0, height=5.0, }, can_move=false, kill_reward=70, kill_type="Enemy Destroyed", death_type="Friend Destroyed", dmg_recv_type="Friend Damaged", dmg_deal_type="Enemy Damaged", damage_recv_penalty=-10, attack_range=0.3, attack_dmg=10, attack_delay=0.2, } unit_types[4] = { tag="Big City", max_hp=70, shape = { body="circle", radius=3, }, can_move=false, kill_reward=-115, death_penalty=-115, kill_type="City Destroyed", death_type="City Destroyed", dmg_recv_type="City Damaged", dmg_deal_type="City Damaged", damage_deal_reward=-10, damage_recv_penalty=-10, attack_range=0, attack_dmg=0, attack_delay=999, } unit_types[5] = { tag="Small City", max_hp=70, shape = { body="circle", radius=1.5, }, can_move=false, kill_reward=-100, death_penalty=-100, kill_type="City Destroyed", death_type="City Destroyed", dmg_recv_type="City Damaged", dmg_deal_type="City Damaged", damage_deal_reward=-10, damage_recv_penalty=-10, attack_range=0, attack_dmg=0, attack_delay=999, } return { unit_types = unit_types, factions=factions, victory_reward=0, failure_penalty=0, reward_types={"Enemy Destroyed", "Friend Destroyed", "City Destroyed", "City Damaged", "Friend Damaged", "Enemy Damaged", "Living"}, } end function on_death(world, dead, cause) -- Filter out the enemy ship killing a tower/being killed by a tower if (cause:unit_type() == "Ship" and cause:faction() == 1 and dead:unit_type() ~= "Ship") -- (dead:unit_type() == "Ship" and dead:faction() == 1 and cause:unit_type() ~= "Ship") -- Note: we need to actually filter this out because otherwise games can stall indefinitely then return end world:emit_reward(1, "Living") if dead:unit_type() == "Ship" and dead:faction() == 0 then world:victory(0) return end world:delete_all() -- We'll just use our reset function to generate -- the next board and tweak it to our liking new_board = _reset(world:rng(), world) for _k,entity in pairs(new_board) do -- Carry over agent HP to next iteration if entity.unit_type == "Ship" and entity.faction == 0 then entity.hp = cause:hp() -- Due to the nature of the scenario, if the agent didn't die they caused the death end world:spawn(entity) end end
Apparently there's a bug where damage_deal_reward means two things
Apparently there's a bug where damage_deal_reward means two things
Lua
bsd-3-clause
SCAII/SCAII,SCAII/SCAII,SCAII/SCAII,SCAII/SCAII,SCAII/SCAII
32d7cc5b710f11905d953151e11bb498d9008fb4
xmake/plugins/lua/main.lua
xmake/plugins/lua/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.sandbox.module") import("core.sandbox.sandbox") -- get all lua scripts function scripts() local names = {} local files = os.files(path.join(os.scriptdir(), "scripts/*.lua")) for _, file in ipairs(files) do table.insert(names, path.basename(file)) end return names end -- list all lua scripts function _list() print("scripts:") for _, file in ipairs(scripts()) do print(" " .. file) end end -- print verbose log function _print_vlog(script_type, script_name, args) if not option.get("verbose") then return end cprintf("running %s ${underline}%s${reset}", script_type, script_name) if args.n > 0 then print(" with args:") if not option.get("diagnosis") then for i = 1, args.n do print(" - " .. todisplay(args[i])) end else utils.dump(table.unpack(args, 1, args.n)) end else print(".") end end function _run_commanad(command, args) local tmpfile = os.tmpfile() .. ".lua" io.writefile(tmpfile, "function main(...)\n" .. command .. "\nend") return _run_script(tmpfile, args) end function _run_script(script, args) local func local printresult = false local script_type, script_name -- import and run script if path.extension(script) == ".lua" and os.isfile(script) then -- run the given lua script file (xmake lua /tmp/script.lua) script_type, script_name = "given lua script file", path.relative(script) func = import(path.basename(script), {rootdir = path.directory(script), anonymous = true}) elseif os.isfile(path.join(os.scriptdir(), "scripts", script .. ".lua")) then -- run builtin lua script (xmake lua echo "hello xmake") script_type, script_name = "builtin lua script", script func = import("scripts." .. script, {anonymous = true}) else -- attempt to find the builtin module local object = nil for _, name in ipairs(script:split("%.")) do object = object and object[name] or module.get(name) if not object then break end end if object then -- run builtin modules (xmake lua core.xxx.xxx) script_type, script_name = "builtin module", script func = object else -- run imported modules (xmake lua core.xxx.xxx) script_type, script_name = "imported module", script func = import(script, {anonymous = true}) end printresult = true end -- print verbose log _print_vlog(script_type or "script", script_name or "", args) -- dump result if type(func) == "function" then local result = table.pack(func(table.unpack(args, 1, args.n))) if printresult and result and result.n ~= 0 then utils.dump(unpack(result, 1, result.n)) end else -- dump variables directly utils.dump(func) end end function _get_args() -- get arguments local args = option.get("arguments") or {} args.n = #args -- get deserialize tag local deserialize = option.get("deserialize") if not deserialize then return args end deserialize = tostring(deserialize) -- deserialize prefixed arguments for i, value in ipairs(args) do if value:startswith(deserialize) then local v, err = string.deserialize(value:sub(#deserialize + 1)) if err then raise(err) else args[i] = v end end end return args end function main() -- list builtin scripts if option.get("list") then return _list() end -- run command? local script = option.get("script") if option.get("command") and script then return _run_commanad(script, _get_args()) end -- get script if script then return _run_script(script, _get_args()) end -- enter interactive mode sandbox.interactive() end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.sandbox.module") import("core.sandbox.sandbox") -- get all lua scripts function scripts() local names = {} local files = os.files(path.join(os.scriptdir(), "scripts/*.lua")) for _, file in ipairs(files) do table.insert(names, path.basename(file)) end return names end -- list all lua scripts function _list() print("scripts:") for _, file in ipairs(scripts()) do print(" " .. file) end end -- print verbose log function _print_vlog(script_type, script_name, args) if not option.get("verbose") then return end cprintf("running %s ${underline}%s${reset}", script_type, script_name) if args.n > 0 then print(" with args:") if not option.get("diagnosis") then for i = 1, args.n do print(" - " .. todisplay(args[i])) end else utils.dump(table.unpack(args, 1, args.n)) end else print(".") end end function _run_commanad(command, args) local tmpfile = os.tmpfile() .. ".lua" io.writefile(tmpfile, "function main(...)\n" .. command .. "\nend") return _run_script(tmpfile, args) end function _run_script(script, args) local func local printresult = false local script_type, script_name -- import and run script if path.extension(script) == ".lua" and os.isfile(script) then -- run the given lua script file (xmake lua /tmp/script.lua) script_type, script_name = "given lua script file", path.relative(script) func = import(path.basename(script), {rootdir = path.directory(script), anonymous = true}) elseif os.isfile(path.join(os.scriptdir(), "scripts", script .. ".lua")) then -- run builtin lua script (xmake lua echo "hello xmake") script_type, script_name = "builtin lua script", script func = import("scripts." .. script, {anonymous = true}) else -- attempt to find the builtin module local object = nil for _, name in ipairs(script:split("%.")) do object = object and object[name] or module.get(name) if not object then break end end if object then -- run builtin modules (xmake lua core.xxx.xxx) script_type, script_name = "builtin module", script func = object else -- run imported modules (xmake lua core.xxx.xxx) script_type, script_name = "imported module", script func = import(script, {anonymous = true}) end printresult = true end -- print verbose log _print_vlog(script_type or "script", script_name or "", args) -- dump func() result if type(func) == "function" or (type(func) == "table" and func.main and type(func.main) == "function") then local result = table.pack(func(table.unpack(args, 1, args.n))) if printresult and result and result.n ~= 0 then utils.dump(unpack(result, 1, result.n)) end else -- dump variables directly utils.dump(func) end end function _get_args() -- get arguments local args = option.get("arguments") or {} args.n = #args -- get deserialize tag local deserialize = option.get("deserialize") if not deserialize then return args end deserialize = tostring(deserialize) -- deserialize prefixed arguments for i, value in ipairs(args) do if value:startswith(deserialize) then local v, err = string.deserialize(value:sub(#deserialize + 1)) if err then raise(err) else args[i] = v end end end return args end function main() -- list builtin scripts if option.get("list") then return _list() end -- run command? local script = option.get("script") if option.get("command") and script then return _run_commanad(script, _get_args()) end -- get script if script then return _run_script(script, _get_args()) end -- enter interactive mode sandbox.interactive() end
fix xmake lua
fix xmake lua
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
74d5847559a28dfda18c1d4479be4b14afc73a3b
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) back = s:taboption("general", DummyValue, "_overview", translate("Overview")) back.value = "" back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect") name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", ListValue, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) back = s:taboption("general", DummyValue, "_overview", translate("Overview")) back.value = "" back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect") name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
applications/luci-firewall: some fixes on redirection page
applications/luci-firewall: some fixes on redirection page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6514 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,gwlim/luci,projectbismark/luci-bismark,gwlim/luci,Canaan-Creative/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,zwhfly/openwrt-luci,ch3n2k/luci,saraedum/luci-packages-old,stephank/luci,projectbismark/luci-bismark,freifunk-gluon/luci,stephank/luci,Flexibity/luci,projectbismark/luci-bismark,ch3n2k/luci,projectbismark/luci-bismark,Canaan-Creative/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,yeewang/openwrt-luci,Flexibity/luci,stephank/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,projectbismark/luci-bismark,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,ch3n2k/luci,jschmidlapp/luci,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,phi-psi/luci,Canaan-Creative/luci,vhpham80/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,jschmidlapp/luci,vhpham80/luci,jschmidlapp/luci,8devices/carambola2-luci,gwlim/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,vhpham80/luci,jschmidlapp/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,ch3n2k/luci,saraedum/luci-packages-old,stephank/luci,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,8devices/carambola2-luci,ch3n2k/luci,8devices/carambola2-luci,8devices/carambola2-luci,vhpham80/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,Canaan-Creative/luci,Flexibity/luci,eugenesan/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,Flexibity/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,stephank/luci,stephank/luci,projectbismark/luci-bismark,Canaan-Creative/luci,jschmidlapp/luci,phi-psi/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci
a0c60edcad88cc65ba88a87757126b3ae0bc3e8d
init.lua
init.lua
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) readwhat = readwhat or '*all' local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s= file:read(readwhat) file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local os = execute('uname -a') if os:find('Linux') then return 'linux' elseif os:find('Darwin') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- sys.prefix = execute('which lua'):gsub('//','/'):gsub('/bin/lua\n','') -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) readwhat = readwhat or '*all' local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s= file:read(readwhat) file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local ffi = require 'ffi' local os = ffi.os if os:find('Linux') then return 'linux' elseif os:find('OSX') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- sys.prefix = execute('which lua'):gsub('//','/'):gsub('/bin/lua\n','') -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
fixing sys to not fork for figuring out sys.OS
fixing sys to not fork for figuring out sys.OS
Lua
bsd-3-clause
torch/sys
c39ad9bee70358ceeee59d02b54a4aef68bc4006
sample/stats/tblutils.lua
sample/stats/tblutils.lua
local function group_by(tab, field) local ret = {} for _, entry in ipairs(tab) do local value = entry[field] assert(value, string.format("stats are not available on field %s", field)) if not ret[value] then ret[value] = {} end table.insert(ret[value], entry) end return ret end local function order_by(tab, order) local ret = {} for k, v in pairs(tab) do table.insert(ret, {k, v}) end table.sort(ret, order) return ret end local function max_length_field(tab, nb) local max = {} if nb > #tab then nb = #tab end for iter = 1, nb do for k, v in sorted_pairs(tab[iter]) do local size = #v if size > 99 then -- Lua formating limits width to 99 size = 99 end if not max[k] then max[k] = #k end if size > max[k] then max[k] = size end end end return max end local function print_columns(tab, nb) local max = max_length_field(tab, nb) if #tab > 0 then local columns = {} for k, _ in sorted_pairs(tab[1]) do table.insert(columns, string.format("%-" .. tostring(max[k]) .. "s", k)) end print("| " .. table.concat(columns, " | ") .. " |") end return max end -- Metatable for storing 'sql-like' table and methods. Intended to be used to -- store 'stats' data and to provide methods to request them local table_mt = {} table_mt.__index = table_mt function table_mt:select_table(elements, where) local ret = {} for _, entry in ipairs(self) do local selected_entry = {} if not where or where(entry) then for _, field in ipairs(elements) do selected_entry[field] = entry[field] end table.insert(ret, selected_entry) end end setmetatable(ret, table_mt) return ret end function table_mt:top(field, nb) nb = nb or 10 assert(field, "missing field parameter") local grouped = group_by(self, field) local sorted = order_by(grouped, function(p, q) return #p[2] > #q[2] end) for _, entry in ipairs(sorted) do if nb <= 0 then break end print(entry[1], ":", #entry[2]) nb = nb - 1 end end function table_mt:dump(nb) nb = nb or #self assert(nb > 0, "illegal negative value") local max = print_columns(self, nb) local iter = nb for _, entry in ipairs(self) do if iter <= 0 then break end local content = {} for k, v in sorted_pairs(entry) do table.insert(content, string.format("%-" .. tostring(max[k]) .. "s", v)) end print("| " .. table.concat(content, " | ") .. " |") iter = iter -1 end if #self > nb then print("... " .. tostring(#self - nb) .. " remaining entries") end end function table_mt:list() if #stats > 1 then for k, _ in sorted_pairs(self[1]) do print(k) end end end return { new = function () local ret = {} setmetatable(ret, table_mt) return ret end }
local function group_by(tab, field) local ret = {} for _, entry in ipairs(tab) do local value = entry[field] assert(value, string.format("stats are not available on field %s", field)) if not ret[value] then ret[value] = {} end table.insert(ret[value], entry) end return ret end local function order_by(tab, order) local ret = {} for k, v in pairs(tab) do table.insert(ret, {k, v}) end table.sort(ret, order) return ret end local function max_length_field(tab, nb) local max = {} if nb > #tab then nb = #tab end for iter = 1, nb do for k, v in sorted_pairs(tab[iter]) do local size = #v if size > 99 then -- Lua formating limits width to 99 size = 99 end if not max[k] then max[k] = #k end if size > max[k] then max[k] = size end end end return max end local function print_columns(tab, nb) local max = max_length_field(tab, nb) if #tab > 0 then local columns = {} for k, _ in sorted_pairs(tab[1]) do table.insert(columns, string.format("%-" .. tostring(max[k]) .. "s", k)) end print("| " .. table.concat(columns, " | ") .. " |") end return max end -- Metatable for storing 'sql-like' table and methods. Intended to be used to -- store 'stats' data and to provide methods to request them local table_mt = {} table_mt.__index = table_mt function table_mt:select_table(elements, where) local ret = {} for _, entry in ipairs(self) do local selected_entry = {} if not where or where(entry) then for _, field in ipairs(elements) do selected_entry[field] = entry[field] end table.insert(ret, selected_entry) end end setmetatable(ret, table_mt) return ret end function table_mt:top(field, nb) nb = nb or 10 assert(field, "missing field parameter") local grouped = group_by(self, field) local sorted = order_by(grouped, function(p, q) return #p[2] > #q[2] or (#p[2] == #q[2] and p[1] > q[1]) end) for _, entry in ipairs(sorted) do if nb <= 0 then break end print(entry[1], ":", #entry[2]) nb = nb - 1 end end function table_mt:dump(nb) nb = nb or #self assert(nb > 0, "illegal negative value") local max = print_columns(self, nb) local iter = nb for _, entry in ipairs(self) do if iter <= 0 then break end local content = {} for k, v in sorted_pairs(entry) do table.insert(content, string.format("%-" .. tostring(max[k]) .. "s", v)) end print("| " .. table.concat(content, " | ") .. " |") iter = iter -1 end if #self > nb then print("... " .. tostring(#self - nb) .. " remaining entries") end end function table_mt:list() if #stats > 1 then for k, _ in sorted_pairs(self[1]) do print(k) end end end return { new = function () local ret = {} setmetatable(ret, table_mt) return ret end }
Fix top line order
Fix top line order Make sure than even with Lua 5.2, the order of the output of top() is always the same.
Lua
mpl-2.0
lcheylus/haka,lcheylus/haka,Wingless-Archangel/haka,lcheylus/haka,Wingless-Archangel/haka,nabilbendafi/haka,LubyRuffy/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,LubyRuffy/haka,haka-security/haka,nabilbendafi/haka
befa3aa63c7570b88c422c2cc6cfdc42d42155d7
frontend/ui/otamanager.lua
frontend/ui/otamanager.lua
local InfoMessage = require("ui/widget/infomessage") local ConfirmBox = require("ui/widget/confirmbox") local NetworkMgr = require("ui/networkmgr") local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("device") local DEBUG = require("dbg") local _ = require("gettext") local OTAManager = { ota_servers = { "http://vislab.bjmu.edu.cn:80/apps/koreader/ota/", "http://koreader.ak-team.com:80/", "http://hal9k.ifsc.usp.br:80/koreader/", }, ota_channels = { "nightly", }, zsync_template = "koreader-%s-latest-%s.zsync", installed_package = "ota/koreader.installed.tar", package_indexfile = "ota/package.index", updated_package = "ota/koreader.updated.tar", } function OTAManager:getOTAModel() if Device:isKindle() then return "kindle" elseif Device:isKobo() then return "kobo" else return "" end end function OTAManager:getOTAServer() return G_reader_settings:readSetting("ota_server") or self.ota_servers[1] end function OTAManager:setOTAServer(server) DEBUG("Set OTA server:", server) G_reader_settings:saveSetting("ota_server", server) end function OTAManager:getOTAChannel() return G_reader_settings:readSetting("ota_channel") or self.ota_channels[1] end function OTAManager:setOTAChannel(channel) DEBUG("Set OTA channel:", channel) G_reader_settings:saveSetting("ota_channel", channel) end function OTAManager:getZsyncFilename() return self.zsync_template:format(self:getOTAModel(), self:getOTAChannel()) end function OTAManager:checkUpdate() local http = require("socket.http") local ltn12 = require("ltn12") local zsync_file = self:getZsyncFilename() local ota_zsync_file = self:getOTAServer() .. zsync_file local local_zsync_file = "ota/" .. zsync_file -- download zsync file from OTA server local r, c, h = http.request{ url = ota_zsync_file, sink = ltn12.sink.file(io.open(local_zsync_file, "w"))} -- prompt users to turn on Wifi if network is unreachable if c ~= 200 then return end -- parse OTA package version local ota_package = nil local zsync = io.open(local_zsync_file, "r") if zsync then for line in zsync:lines() do ota_package = line:match("^Filename:%s*(.-)%s*$") if ota_package then break end end zsync:close() end local local_version = io.open("git-rev", "r"):read() local ota_version = nil if ota_package then ota_version = ota_package:match(".-(v%d.-)%.tar") end -- return ota package version if package on OTA server has version -- larger than the local package version if ota_version and ota_version > local_version then return ota_version elseif ota_version and ota_version == local_version then return 0 end end function OTAManager:fetchAndProcessUpdate() local ota_version = OTAManager:checkUpdate() if ota_version == 0 then UIManager:show(InfoMessage:new{ text = _("Your koreader is updated."), }) elseif ota_version == nil then UIManager:show(InfoMessage:new{ text = _("OTA server is not available."), }) elseif ota_version then UIManager:show(ConfirmBox:new{ text = _("Do you want to update to version ")..ota_version.."?", ok_callback = function() UIManager:show(InfoMessage:new{ text = _("Downloading may take several minutes..."), timeout = 3, }) UIManager:scheduleIn(1, function() if OTAManager:zsync() == 0 then UIManager:show(InfoMessage:new{ text = _("Koreader will be updated on next restart."), }) else UIManager:show(ConfirmBox:new{ text = _("Error updating Koreader. Would you like to delete temporary files?"), ok_callback = function() os.execute("rm ota/ko*") end, }) end end) end }) end end function OTAManager:_buildLocalPackage() -- TODO: validate the installed package? local installed_package = lfs.currentdir() .. "/" .. self.installed_package if lfs.attributes(installed_package, "mode") == "file" then return 0 end return os.execute(string.format( "./tar cvf %s -C .. -T %s --no-recursion", self.installed_package, self.package_indexfile)) end function OTAManager:zsync() if self:_buildLocalPackage() == 0 then return os.execute(string.format( "./zsync -i %s -o %s -u %s %s", self.installed_package, self.updated_package, self:getOTAServer(), "ota/" .. self:getZsyncFilename() )) end end function OTAManager:genServerList() local servers = {} for _, server in ipairs(self.ota_servers) do local server_item = { text = server, checked_func = function() return self:getOTAServer() == server end, callback = function() self:setOTAServer(server) end } table.insert(servers, server_item) end return servers end function OTAManager:genChannelList() local channels = {} for _, channel in ipairs(self.ota_channels) do local channel_item = { text = channel, checked_func = function() return self:getOTAChannel() == channel end, callback = function() self:setOTAChannel(channel) end } table.insert(channels, channel_item) end return channels end function OTAManager:getOTAMenuTable() return { text = _("OTA update"), sub_item_table = { { text = _("Check update"), callback = function() if NetworkMgr:getWifiStatus() == false then NetworkMgr:promptWifiOn() else OTAManager.fetchAndProcessUpdate() end end }, { text = _("Settings"), sub_item_table = { { text = _("OTA server"), sub_item_table = self:genServerList() }, { text = _("OTA channel"), sub_item_table = self:genChannelList() }, } }, } } end return OTAManager
local InfoMessage = require("ui/widget/infomessage") local ConfirmBox = require("ui/widget/confirmbox") local NetworkMgr = require("ui/networkmgr") local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("device") local DEBUG = require("dbg") local _ = require("gettext") local OTAManager = { ota_servers = { "http://vislab.bjmu.edu.cn:80/apps/koreader/ota/", "http://koreader.ak-team.com:80/", "http://hal9k.ifsc.usp.br:80/koreader/", }, ota_channels = { "nightly", }, zsync_template = "koreader-%s-latest-%s.zsync", installed_package = "ota/koreader.installed.tar", package_indexfile = "ota/package.index", updated_package = "ota/koreader.updated.tar", } function OTAManager:getOTAModel() if Device:isKindle() then return "kindle" elseif Device:isKobo() then return "kobo" else return "" end end function OTAManager:getOTAServer() return G_reader_settings:readSetting("ota_server") or self.ota_servers[1] end function OTAManager:setOTAServer(server) DEBUG("Set OTA server:", server) G_reader_settings:saveSetting("ota_server", server) end function OTAManager:getOTAChannel() return G_reader_settings:readSetting("ota_channel") or self.ota_channels[1] end function OTAManager:setOTAChannel(channel) DEBUG("Set OTA channel:", channel) G_reader_settings:saveSetting("ota_channel", channel) end function OTAManager:getZsyncFilename() return self.zsync_template:format(self:getOTAModel(), self:getOTAChannel()) end function OTAManager:checkUpdate() local http = require("socket.http") local ltn12 = require("ltn12") local zsync_file = self:getZsyncFilename() local ota_zsync_file = self:getOTAServer() .. zsync_file local local_zsync_file = "ota/" .. zsync_file -- download zsync file from OTA server local r, c, h = http.request{ url = ota_zsync_file, sink = ltn12.sink.file(io.open(local_zsync_file, "w"))} -- prompt users to turn on Wifi if network is unreachable if c ~= 200 then return end -- parse OTA package version local ota_package = nil local zsync = io.open(local_zsync_file, "r") if zsync then for line in zsync:lines() do ota_package = line:match("^Filename:%s*(.-)%s*$") if ota_package then break end end zsync:close() end local normalized_version = function(rev) local version = rev:match("(v%d.-)-g"):gsub("[^%d]", "") return tonumber(version) end local local_ok, local_version = pcall(function() local rev_file = io.open("git-rev", "r") if rev_file then local rev = rev_file:read() rev_file:close() return normalized_version(rev) end end) local ota_ok, ota_version = pcall(function() return normalized_version(ota_package) end) -- return ota package version if package on OTA server has version -- larger than the local package version if local_ok and ota_ok and ota_version and local_version and ota_version > local_version then return ota_version elseif ota_version and ota_version == local_version then return 0 end end function OTAManager:fetchAndProcessUpdate() local ota_version = OTAManager:checkUpdate() if ota_version == 0 then UIManager:show(InfoMessage:new{ text = _("Your koreader is updated."), }) elseif ota_version == nil then UIManager:show(InfoMessage:new{ text = _("OTA server is not available."), }) elseif ota_version then UIManager:show(ConfirmBox:new{ text = _("Do you want to update to version ")..ota_version.."?", ok_callback = function() UIManager:show(InfoMessage:new{ text = _("Downloading may take several minutes..."), timeout = 3, }) UIManager:scheduleIn(1, function() if OTAManager:zsync() == 0 then UIManager:show(InfoMessage:new{ text = _("Koreader will be updated on next restart."), }) else UIManager:show(ConfirmBox:new{ text = _("Error updating Koreader. Would you like to delete temporary files?"), ok_callback = function() os.execute("rm ota/ko*") end, }) end end) end }) end end function OTAManager:_buildLocalPackage() -- TODO: validate the installed package? local installed_package = lfs.currentdir() .. "/" .. self.installed_package if lfs.attributes(installed_package, "mode") == "file" then return 0 end return os.execute(string.format( "./tar cvf %s -C .. -T %s --no-recursion", self.installed_package, self.package_indexfile)) end function OTAManager:zsync() if self:_buildLocalPackage() == 0 then return os.execute(string.format( "./zsync -i %s -o %s -u %s %s", self.installed_package, self.updated_package, self:getOTAServer(), "ota/" .. self:getZsyncFilename() )) end end function OTAManager:genServerList() local servers = {} for _, server in ipairs(self.ota_servers) do local server_item = { text = server, checked_func = function() return self:getOTAServer() == server end, callback = function() self:setOTAServer(server) end } table.insert(servers, server_item) end return servers end function OTAManager:genChannelList() local channels = {} for _, channel in ipairs(self.ota_channels) do local channel_item = { text = channel, checked_func = function() return self:getOTAChannel() == channel end, callback = function() self:setOTAChannel(channel) end } table.insert(channels, channel_item) end return channels end function OTAManager:getOTAMenuTable() return { text = _("OTA update"), sub_item_table = { { text = _("Check update"), callback = function() if NetworkMgr:getWifiStatus() == false then NetworkMgr:promptWifiOn() else OTAManager.fetchAndProcessUpdate() end end }, { text = _("Settings"), sub_item_table = { { text = _("OTA server"), sub_item_table = self:genServerList() }, { text = _("OTA channel"), sub_item_table = self:genChannelList() }, } }, } } end return OTAManager
normalize version when checking packages in OTA manager This fixes a bug that version 987 was treated newer than version 1010.
normalize version when checking packages in OTA manager This fixes a bug that version 987 was treated newer than version 1010.
Lua
agpl-3.0
ashhher3/koreader,Frenzie/koreader,pazos/koreader,chihyang/koreader,NiLuJe/koreader,poire-z/koreader,noname007/koreader,koreader/koreader,chrox/koreader,lgeek/koreader,frankyifei/koreader,robert00s/koreader,mwoz123/koreader,houqp/koreader,apletnev/koreader,NickSavage/koreader,Markismus/koreader,ashang/koreader,Hzj-jie/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,poire-z/koreader,mihailim/koreader
45ff0545d34a0738a18ca9f07b1f07ab8754c22a
lua/entities/gmod_wire_expression2/core/glon.lua
lua/entities/gmod_wire_expression2/core/glon.lua
if not glon then require("glon") end local last_glon_error = "" __e2setcost(10) --- Encodes <data> into a string, using [[GLON]]. e2function string glonEncode(array data) local ok, ret = pcall(glon.encode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.encode error: "..ret) return "" end if ret then self.prf = self.prf + string.len(ret) / 2 end return ret or "" end --- Decodes <data> into an array, using [[GLON]]. e2function array glonDecode(string data) self.prf = self.prf + string.len(data) / 2 local ok, ret = pcall(glon.decode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.decode error: "..ret) return {} end if (type(ret) != "table") then -- Exploit detected --MsgN( "[E2] WARNING! " .. self.player:Nick() .. " (" .. self.player:SteamID() .. ") tried to read a non-table type as a table. This is a known and serious exploit that has been prevented." ) --error( "Tried to read a non-table type as a table." ) return {} end return ret or {} end e2function string glonError() return last_glon_error end hook.Add("InitPostEntity", "wire_expression2_glonfix", function() -- Fixing other people's bugs... for i = 1,20 do local name, encode_types = debug.getupvalue(glon.Write, i) if name == "encode_types" then for _,tp in ipairs({"NPC","Vehicle","Weapon"}) do if not encode_types[tp] then encode_types[tp] = encode_types.Entity end end break end end end) --------------------------------------------------------------------------- -- table glon --------------------------------------------------------------------------- __e2setcost(15) --- Encodes <data> into a string, using [[GLON]]. e2function string glonEncode(table data) = e2function string glonEncode(array data) __e2setcost(25) local function ExploitFix( self, tbl, checked ) if (!self or !tbl) then return true end if (!tbl.istable) then return false end local ret = true for k,v in pairs( tbl.n ) do self.prf = self.prf + 1 if (!checked[v]) then checked[v] = true if (exploitables[type(v)] and tbl.ntypes[k] != "e") then ret = false elseif (tbl.ntypes[k] == "t") then local temp = ExploitFix( self, v, checked ) if (temp == false) then ret = false end end end end for k,v in pairs( tbl.s ) do self.prf = self.prf + 1 if (!checked[v]) then checked[v] = true if (exploitables[type(v)] and tbl.stypes[k] != "e") then ret = false elseif (tbl.stypes[k] == "t") then local temp = ExploitFix( self, v, checked ) if (temp == false) then ret = false end end end end return ret end local DEFAULT = {n={},ntypes={},s={},stypes={},size=0,istable=true,depth=0} -- decodes a glon string and returns an table e2function table glonDecodeTable(string data) if (!data or data == "") then return table.Copy(DEFAULT) end self.prf = self.prf + string.len(data) / 2 data = string.Replace(data, "\7xwl", "\7xxx") local ok, ret = pcall(glon.decode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.decode error: "..ret) return table.Copy(DEFAULT) end if (!ret or !ret.istable) then return table.Copy(DEFAULT) end if (type(ret) != "table" or ExploitFix( self, ret, { [ret] = true } ) == false) then -- Exploit check --MsgN( "[E2] WARNING! " .. self.player:Nick() .. " (" .. self.player:SteamID() .. ") tried to read a non-table type as a table. This is a known and serious exploit that has been prevented." ) --error( "Tried to read a non-table type as a table." ) return table.Copy(DEFAULT) end return ret or table.Copy(DEFAULT) end __e2setcost(nil)
if not glon then require("glon") end local last_glon_error = "" __e2setcost(10) --- Encodes <data> into a string, using [[GLON]]. e2function string glonEncode(array data) local ok, ret = pcall(glon.encode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.encode error: "..ret) return "" end if ret then self.prf = self.prf + string.len(ret) / 2 end return ret or "" end --- Decodes <data> into an array, using [[GLON]]. e2function array glonDecode(string data) self.prf = self.prf + string.len(data) / 2 local ok, ret = pcall(glon.decode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.decode error: "..ret) return {} end if (type(ret) != "table") then -- Exploit detected --MsgN( "[E2] WARNING! " .. self.player:Nick() .. " (" .. self.player:SteamID() .. ") tried to read a non-table type as a table. This is a known and serious exploit that has been prevented." ) --error( "Tried to read a non-table type as a table." ) return {} end return ret or {} end e2function string glonError() return last_glon_error end hook.Add("InitPostEntity", "wire_expression2_glonfix", function() -- Fixing other people's bugs... for i = 1,20 do local name, encode_types = debug.getupvalue(glon.Write, i) if name == "encode_types" then for _,tp in ipairs({"NPC","Vehicle","Weapon"}) do if not encode_types[tp] then encode_types[tp] = encode_types.Entity end end break end end end) --------------------------------------------------------------------------- -- table glon --------------------------------------------------------------------------- __e2setcost(15) --- Encodes <data> into a string, using [[GLON]]. e2function string glonEncode(table data) = e2function string glonEncode(array data) __e2setcost(25) local exploitables = {} local function ExploitFix( self, tbl, checked ) if (!self or !tbl) then return true end if (!tbl.istable) then return false end local ret = true for k,v in pairs( tbl.n ) do self.prf = self.prf + 1 if (!checked[v]) then checked[v] = true if (exploitables[type(v)] or tbl.ntypes[k] == "e") then ret = false elseif (tbl.ntypes[k] == "t") then local temp = ExploitFix( self, v, checked ) if (temp == false) then ret = false end end end end for k,v in pairs( tbl.s ) do self.prf = self.prf + 1 if (!checked[v]) then checked[v] = true if (exploitables[type(v)] or tbl.stypes[k] == "e") then ret = false elseif (tbl.stypes[k] == "t") then local temp = ExploitFix( self, v, checked ) if (temp == false) then ret = false end end end end return ret end local DEFAULT = {n={},ntypes={},s={},stypes={},size=0,istable=true,depth=0} -- decodes a glon string and returns an table e2function table glonDecodeTable(string data) if (!data or data == "") then return table.Copy(DEFAULT) end self.prf = self.prf + string.len(data) / 2 data = string.Replace(data, "\7xwl", "\7xxx") local ok, ret = pcall(glon.decode, data) if not ok then last_glon_error = ret ErrorNoHalt("glon.decode error: "..ret) return table.Copy(DEFAULT) end if (!ret or !ret.istable) then return table.Copy(DEFAULT) end if (type(ret) != "table" or ExploitFix( self, ret, { [ret] = true } ) == false) then -- Exploit check --MsgN( "[E2] WARNING! " .. self.player:Nick() .. " (" .. self.player:SteamID() .. ") tried to read a non-table type as a table. This is a known and serious exploit that has been prevented." ) --error( "Tried to read a non-table type as a table." ) return table.Copy(DEFAULT) end return ret or table.Copy(DEFAULT) end __e2setcost(nil)
[E2] glon.lua: Committed LukS's fix for glon...
[E2] glon.lua: Committed LukS's fix for glon...
Lua
apache-2.0
plinkopenguin/wiremod,dvdvideo1234/wire,thegrb93/wire,Python1320/wire,CaptainPRICE/wire,Grocel/wire,garrysmodlua/wire,bigdogmat/wire,rafradek/wire,notcake/wire,wiremod/wire,sammyt291/wire,immibis/wiremod,NezzKryptic/Wire,mms92/wire,mitterdoo/wire
11253d978c027528c2a6600aebbbf135ba25299d
ejoy2d/shader.lua
ejoy2d/shader.lua
local s = require "ejoy2d.shader.c" local PRECISION = "" local PRECISION_HIGH = "" if s.version() == 2 then -- Opengl ES 2.0 need float precision specifiers PRECISION = "precision lowp float;\n" PRECISION_HIGH = "precision highp float;\n" end local sprite_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = tmp.xyz * v_color.xyz; gl_FragColor.w = tmp.w; gl_FragColor *= v_color.w; gl_FragColor.xyz += additive.xyz * tmp.w; } ]] local sprite_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec4 v_color; void main() { gl_Position = position + vec4(-1.0,1.0,0,0); v_texcoord = texcoord; v_color = color; } ]] local text_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { float c = texture2D(texture0, v_texcoord).w; float alpha = clamp(c, 0.0, 0.5) * 2.0; gl_FragColor.xyz = (v_color.xyz + additive) * alpha; gl_FragColor.w = alpha; gl_FragColor *= v_color.w; } ]] local text_edge_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { float c = texture2D(texture0, v_texcoord).w; float alpha = clamp(c, 0.0, 0.5) * 2.0; float color = (clamp(c, 0.5, 1.0) - 0.5) * 2.0; gl_FragColor.xyz = (v_color.xyz + additive) * color; gl_FragColor.w = alpha; gl_FragColor *= v_color.w; } ]] local gray_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); vec4 c; c.xyz = tmp.xyz * v_color.xyz; c.w = tmp.w; c *= v_color.w; c.xyz += additive.xyz * tmp.w; float g = dot(c.rgb , vec3(0.299, 0.587, 0.114)); gl_FragColor = vec4(g,g,g,c.a); } ]] local color_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = v_color.xyz * tmp.w; gl_FragColor.w = tmp.w; } ]] local blend_fs = [[ varying vec2 v_texcoord; varying vec2 v_mask_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = tmp.xyz * v_color.xyz; gl_FragColor.w = tmp.w; gl_FragColor *= v_color.w; gl_FragColor.xyz += additive.xyz * tmp.w; vec4 m = texture2D(texture0, v_mask_texcoord); gl_FragColor.xyz *= m.xyz; // gl_FragColor *= m.w; } ]] local blend_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec2 v_mask_texcoord; varying vec4 v_color; uniform vec2 mask; void main() { gl_Position = position + vec4(-1,1,0,0); v_texcoord = texcoord; v_mask_texcoord = texcoord + mask; v_color = color; } ]] local renderbuffer_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec4 v_color; uniform vec4 st; void main() { gl_Position.x = position.x * st.x + st.z -1.0; gl_Position.y = position.y * st.y + st.w +1.0; v_texcoord = texcoord; v_color = color; } ]] local shader = {} local shader_name = { NORMAL = 0, RENDERBUFFER = 1, TEXT = 2, EDGE = 3, GRAY = 4, COLOR = 5, BLEND = 6, } function shader.init() s.load(shader_name.NORMAL, PRECISION .. sprite_fs, PRECISION .. sprite_vs) s.load(shader_name.TEXT, PRECISION .. text_fs, PRECISION .. sprite_vs) s.load(shader_name.EDGE, PRECISION .. text_edge_fs, PRECISION .. sprite_vs) s.load(shader_name.GRAY, PRECISION .. gray_fs, PRECISION .. sprite_vs) s.load(shader_name.COLOR, PRECISION .. color_fs, PRECISION .. sprite_vs) s.load(shader_name.BLEND, PRECISION .. blend_fs, PRECISION .. blend_vs) s.load(shader_name.RENDERBUFFER, PRECISION .. sprite_fs, PRECISION_HIGH .. renderbuffer_vs) end shader.draw = s.draw shader.blend = s.blend shader.clear = s.clear function shader.id(name) local id = assert(shader_name[name] , "Invalid shader name " .. name) return id end return shader
local s = require "ejoy2d.shader.c" local PRECISION = "" local PRECISION_HIGH = "" if s.version() == 2 then -- Opengl ES 2.0 need float precision specifiers PRECISION = "precision lowp float;\n" PRECISION_HIGH = "precision highp float;\n" end local sprite_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = tmp.xyz * v_color.xyz; gl_FragColor.w = tmp.w; gl_FragColor *= v_color.w; gl_FragColor.xyz += additive.xyz * tmp.w; } ]] local sprite_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec4 v_color; void main() { gl_Position = position + vec4(-1.0,1.0,0,0); v_texcoord = texcoord; v_color = color; } ]] local text_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { float c = texture2D(texture0, v_texcoord).w; float alpha = clamp(c, 0.0, 0.5) * 2.0; gl_FragColor.xyz = (v_color.xyz + additive) * alpha; gl_FragColor.w = alpha; gl_FragColor *= v_color.w; } ]] local text_edge_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { float c = texture2D(texture0, v_texcoord).w; float alpha = clamp(c, 0.0, 0.5) * 2.0; float color = (clamp(c, 0.5, 1.0) - 0.5) * 2.0; gl_FragColor.xyz = (v_color.xyz + additive) * color; gl_FragColor.w = alpha; gl_FragColor *= v_color.w; } ]] local gray_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); vec4 c; c.xyz = tmp.xyz * v_color.xyz; c.w = tmp.w; c *= v_color.w; c.xyz += additive.xyz * tmp.w; float g = dot(c.rgb , vec3(0.299, 0.587, 0.114)); gl_FragColor = vec4(g,g,g,c.a); } ]] local color_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = v_color.xyz * tmp.w; gl_FragColor.w = tmp.w; } ]] local blend_fs = [[ varying vec2 v_texcoord; varying vec2 v_mask_texcoord; varying vec4 v_color; uniform sampler2D texture0; uniform vec3 additive; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = tmp.xyz * v_color.xyz; gl_FragColor.w = tmp.w; gl_FragColor *= v_color.w; gl_FragColor.xyz += additive.xyz * tmp.w; vec4 m = texture2D(texture0, v_mask_texcoord); gl_FragColor.xyz *= m.xyz; // gl_FragColor *= m.w; } ]] local blend_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec2 v_mask_texcoord; varying vec4 v_color; uniform vec2 mask; void main() { gl_Position = position + vec4(-1,1,0,0); v_texcoord = texcoord; v_mask_texcoord = texcoord + mask; v_color = color; } ]] local renderbuffer_fs = [[ varying vec2 v_texcoord; varying vec4 v_color; uniform sampler2D texture0; void main() { vec4 tmp = texture2D(texture0, v_texcoord); gl_FragColor.xyz = tmp.xyz * v_color.xyz; gl_FragColor.w = tmp.w; gl_FragColor *= v_color.w; } ]] local renderbuffer_vs = [[ attribute vec4 position; attribute vec2 texcoord; attribute vec4 color; varying vec2 v_texcoord; varying vec4 v_color; uniform vec4 st; void main() { gl_Position.x = position.x * st.x + st.z -1.0; gl_Position.y = position.y * st.y + st.w +1.0; gl_Position.z = position.z; gl_Position.w = position.w; v_texcoord = texcoord; v_color = color; } ]] local shader = {} local shader_name = { NORMAL = 0, RENDERBUFFER = 1, TEXT = 2, EDGE = 3, GRAY = 4, COLOR = 5, BLEND = 6, } function shader.init() s.load(shader_name.NORMAL, PRECISION .. sprite_fs, PRECISION .. sprite_vs) s.load(shader_name.TEXT, PRECISION .. text_fs, PRECISION .. sprite_vs) s.load(shader_name.EDGE, PRECISION .. text_edge_fs, PRECISION .. sprite_vs) s.load(shader_name.GRAY, PRECISION .. gray_fs, PRECISION .. sprite_vs) s.load(shader_name.COLOR, PRECISION .. color_fs, PRECISION .. sprite_vs) s.load(shader_name.BLEND, PRECISION .. blend_fs, PRECISION .. blend_vs) s.load(shader_name.RENDERBUFFER, PRECISION .. renderbuffer_fs, PRECISION_HIGH .. renderbuffer_vs) end shader.draw = s.draw shader.blend = s.blend shader.clear = s.clear function shader.id(name) local id = assert(shader_name[name] , "Invalid shader name " .. name) return id end return shader
bugfix: don't ignore zw
bugfix: don't ignore zw
Lua
mit
cuit-zhaxin/ejoy2d,FelixZhang00/ejoy2d,lvshaco/ejoy2d,zhoukk/ejoy2d,catinred2/ejoy2d,cdd990/ejoy2d,xebecnan/ejoy2d,czlc/ejoy2d,spracle/ejoy2d,yinjun322/ejoy2d,lvshaco/ejoy2d,javachengwc/ejoy2d,ejoy/ejoy2d,Just-D/ejoy2d,rainfiel/ejoy2d,javachengwc/ejoy2d,yinjun322/ejoy2d,czlc/ejoy2d,lvshaco/ejoy2d,fusijie/ejoy2d,xebecnan/ejoy2d,Just-D/ejoy2d,zhoukk/ejoy2d,fusijie/ejoy2d,MonCoder/ejoy2d,lvshaco/ejoy2d,ejoy/ejoy2d,spracle/ejoy2d,rainfiel/ejoy2d,catinred2/ejoy2d,lvshaco/ejoy2d,zgpxgame/ejoy2d,luningcowboy/ejoy2d,zgpxgame/ejoy2d,lvshaco/ejoy2d,MonCoder/ejoy2d,danjia/ejoy2d,cuit-zhaxin/ejoy2d,cdd990/ejoy2d,FelixZhang00/ejoy2d,danjia/ejoy2d,luningcowboy/ejoy2d
c1f17496be99fba40931cf0c29db699da13d488a
share/lua/website/ted.lua
share/lua/website/ted.lua
-- libquvi-scripts -- Copyright (C) 2011 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2011 Bastien Nocera <hadess@hadess.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Ted = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "ted%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/talks/.+$"}) return r end -- Query available formats. function query_formats(self) local page = quvi.fetch(self.page_url) local formats = Ted.iter_formats(page) local t = {} for _,v in pairs(formats) do table.insert(t, Ted.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse video URL. function parse(self) self.host_id = "ted" local page = quvi.fetch(self.page_url) self.id = page:match('ti:"(%d+)"') or error("no match: media id") self.title = page:match('<title>(.-)%s+|') or error("no match: media title") self.thumbnail_url = page:match('rel="image_src" href="(.-)"') or '' local formats = Ted.iter_formats(page) local U = require 'quvi/util' self.url = {U.choose_format(self, formats, Ted.choose_best, Ted.choose_default, Ted.to_s).url or error("no match: media url")} return self end -- -- Utility functions -- function Ted.iter_formats(page) local pp = 'http://download.ted.com' local p = 'href="' ..pp.. '(.-)"' local t = {} for u in page:gfind(p) do local c = u:match('%.(%w+)$') or error('no match: container') local q = u:match('%-(%w+)%.%w+$') -- nil is acceptable here u = pp .. u if not Ted.find_duplicate(t,u) then table.insert(t, {url=u, container=c, quality=q}) -- print(u,c,q) end end return t end function Ted.find_duplicate(t,u) for _,v in pairs(t) do if v.url == u then return true end end return false end function Ted.choose_best(formats) -- Last 'mp4' is the 'best' local r = Ted.choose_default(formats) local p = '(%d+)p' for _,v in pairs(formats) do if v.container:match('mp4') then if v.quality then local a = v.quality:match(p) local b = (r.quality) and r.quality:match(p) or 0 if a and tonumber(a) > tonumber(b) then r = v end else r = v end end end return r end function Ted.choose_default(formats) -- First 'mp4' is the 'default' local r -- Return this if mp4 is not found for some reason for _,v in pairs(formats) do if v.container:match('mp4') then return v end r = v end return r end function Ted.to_s(t) return (t.quality) and string.format("%s_%s", t.container, t.quality) or string.format("%s", t.container) end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2011 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2011 Bastien Nocera <hadess@hadess.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Ted = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "ted%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/talks/.+$"}) return r end -- Query available formats. function query_formats(self) local page = quvi.fetch(self.page_url) local formats = Ted.iter_formats(page) local t = {} for _,v in pairs(formats) do table.insert(t, Ted.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse video URL. function parse(self) self.host_id = "ted" local page = quvi.fetch(self.page_url) self.id = page:match('ti:"(%d+)"') or error("no match: media id") self.title = page:match('<title>(.-)%s+|') or error("no match: media title") self.thumbnail_url = page:match('rel="image_src" href="(.-)"') or '' local formats = Ted.iter_formats(page) local U = require 'quvi/util' local r = U.choose_format(self, formats, Ted.choose_best, Ted.choose_default, Ted.to_s) or error("no match: media url") self.url = {r.url} return self end -- -- Utility functions -- function Ted.iter_formats(page) local pp = 'http://download.ted.com' local p = 'href="' ..pp.. '(.-)"' local t = {} for u in page:gfind(p) do local c = u:match('%.(%w+)$') or error('no match: container') local q = u:match('%-(%w+)%.%w+$') -- nil is acceptable here u = pp .. u if not Ted.find_duplicate(t,u) then table.insert(t, {url=u, container=c, quality=q}) -- print(u,c,q) end end return t end function Ted.find_duplicate(t,u) for _,v in pairs(t) do if v.url == u then return true end end return false end function Ted.choose_best(formats) -- Last 'mp4' is the 'best' local r = Ted.choose_default(formats) local p = '(%d+)p' for _,v in pairs(formats) do if v.container:match('mp4') then if v.quality then local a = v.quality:match(p) local b = (r.quality) and r.quality:match(p) or 0 if a and tonumber(a) > tonumber(b) then r = v end else r = v end end end return r end function Ted.choose_default(formats) -- First 'mp4' is the 'default' local r -- Return this if mp4 is not found for some reason for _,v in pairs(formats) do if v.container:match('mp4') then return v end r = v end return r end function Ted.to_s(t) return (t.quality) and string.format("%s_%s", t.container, t.quality) or string.format("%s", t.container) end -- vim: set ts=4 sw=4 tw=72 expandtab:
ted.lua: Fix media URL check
ted.lua: Fix media URL check
Lua
lgpl-2.1
hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts
01ee82d55c94d13abf37070168db09ed85d04821
BIOS/init.lua
BIOS/init.lua
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig setfenv(bconfC,{P = P}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC = love.filesystem.load("/BIOS/bconf.lua") setfenv(bconfC,{P = P}) --BConfig sandboxing bconfC() end --Load the default BConfig --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,48 do for y=1,16 do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end drawAnim() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage < 5 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 4 then drawAnim() else g.clear() end end end if stage == 5 then --Create the coroutine stage = 6 --So coroutine don't get duplicated end end) end --Booting the system ! --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig setfenv(bconfC,{P = P}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC = love.filesystem.load("/BIOS/bconf.lua") setfenv(bconfC,{P = P}) --BConfig sandboxing bconfC() end --Load the default BConfig --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,48 do for y=1,16 do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end g.clear() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage == 6 then --Create the coroutine stage = 7 --So coroutine don't get duplicated end if stage < 6 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 5 then drawAnim() elseif stage == 5 then g.clear() end end end end) else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation end --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
82d595c6da9e5a686c4dec4fd63ca28bb35a5e4e
lua/include/namespaces.lua
lua/include/namespaces.lua
local mod = {} local ffi = require "ffi" local serpent = require "Serpent" local stp = require "StackTracePlus" local lock = require "lock" ffi.cdef [[ struct namespace { }; struct namespace* create_or_get_namespace(const char* name); void namespace_store(struct namespace* ns, const char* key, const char* value); void namespace_delete(struct namespace* ns, const char* key); const char* namespace_retrieve(struct namespace* ns, const char* key); void namespace_iterate(struct namespace* ns, void (*func)(const char* key, const char* val)); struct lock* namespace_get_lock(struct namespace* ns); ]] local C = ffi.C local namespace = {} namespace.__index = namespace local function getNameFromTrace() return debug.traceback():match("\n.-\n.-\n(.-)\n") end --- Get a namespace by its name creating it if necessary. -- @param name the name, defaults to an auto-generated string consisting of the caller's filename and line number function mod:get(name) name = name or getNameFromTrace() return C.create_or_get_namespace(name) end --- Retrieve a *copy* of a value in the namespace. -- @param key the key, must be a string function namespace:__index(key) if type(key) ~= "string" then error("table index must be a string") end if key == "forEach" then return namespace.forEach elseif key == "lock" then return C.namespace_get_lock(self) end local val = C.namespace_retrieve(self, key) return val ~= nil and loadstring(ffi.string(val))() or nil end --- Store a value in the namespace. -- @param key the key, must be a string -- @param val the value to store, will be serialized function namespace:__newindex(key, val) if type(key) ~= "string" then error("table index must be a string") end if key == "forEach" or key == "lock" then error(key .. " is reserved", 2) end if val == nil then C.namespace_delete(self, key) else C.namespace_store(self, key, serpent.dump(val)) end end --- Iterate over all keys/values in a namespace -- Note: namespaces do not offer a 'normal' iterator (e.g. through a __pair metamethod) due to locking. -- Iterating over a table requires a lock on the whole table; ensuring that the lock is released is -- easier with a forEach method than with a regular iterator. -- @param cb function to call, receives (key, value) as arguments function namespace:forEach(cb) local caughtError C.namespace_iterate(self, function(key, val) if caughtError then return end -- avoid throwing an error across the C++ frame unnecessarily -- not sure if this would work properly when compiled with clang instead of gcc local ok, err = xpcall(cb, function(err) return stp.stacktrace(err) end, ffi.string(key), loadstring(ffi.string(val))()) if not ok then caughtError = err end end) if caughtError then -- this is gonna be an ugly error message, but at least we get the full call stack error("error while calling callback, inner error: " .. caughtError) end end ffi.metatype("struct namespace", namespace) return mod
local mod = {} local ffi = require "ffi" local serpent = require "Serpent" local stp = require "StackTracePlus" local lock = require "lock" ffi.cdef [[ struct namespace { }; struct namespace* create_or_get_namespace(const char* name); void namespace_store(struct namespace* ns, const char* key, const char* value); void namespace_delete(struct namespace* ns, const char* key); const char* namespace_retrieve(struct namespace* ns, const char* key); void namespace_iterate(struct namespace* ns, void (*func)(const char* key, const char* val)); struct lock* namespace_get_lock(struct namespace* ns); ]] local C = ffi.C local namespace = {} namespace.__index = namespace local function getNameFromTrace() return debug.traceback():match("\n.-\n.-\n(.-)\n") end --- Get a namespace by its name creating it if necessary. -- @param name the name, defaults to an auto-generated string consisting of the caller's filename and line number function mod:get(name) name = name or getNameFromTrace() return C.create_or_get_namespace(name) end --- Retrieve a *copy* of a value in the namespace. -- @param key the key, must be a string function namespace:__index(key) if type(key) ~= "string" then error("table index must be a string") end if key == "forEach" then return namespace.forEach elseif key == "lock" then return C.namespace_get_lock(self) end local val = C.namespace_retrieve(self, key) return val ~= nil and loadstring(ffi.string(val))() or nil end --- Store a value in the namespace. -- @param key the key, must be a string -- @param val the value to store, will be serialized function namespace:__newindex(key, val) if type(key) ~= "string" then error("table index must be a string") end if key == "forEach" or key == "lock" then error(key .. " is reserved", 2) end if val == nil then C.namespace_delete(self, key) else C.namespace_store(self, key, serpent.dump(val)) end end --- Iterate over all keys/values in a namespace -- Note: namespaces do not offer a 'normal' iterator (e.g. through a __pair metamethod) due to locking. -- Iterating over a table requires a lock on the whole table; ensuring that the lock is released is -- easier with a forEach method than with a regular iterator. -- @param func function to call, receives (key, value) as arguments function namespace:forEach(func) local caughtError local cb = ffi.cast("void (*)(const char* key, const char* val)", function(key, val) if caughtError then return end -- avoid throwing an error across the C++ frame unnecessarily -- not sure if this would work properly when compiled with clang instead of gcc local ok, err = xpcall(func, function(err) return stp.stacktrace(err) end, ffi.string(key), loadstring(ffi.string(val))()) if not ok then caughtError = err end end) C.namespace_iterate(self, cb) cb:free() if caughtError then -- this is gonna be an ugly error message, but at least we get the full call stack error("error while calling callback, inner error: " .. caughtError) end end ffi.metatype("struct namespace", namespace) return mod
namespaces: fix memory leak
namespaces: fix memory leak
Lua
mit
wenhuizhang/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,slyon/MoonGen,slyon/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,bmichalo/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,atheurer/MoonGen,emmericp/MoonGen,werpat/MoonGen,kidaa/MoonGen,scholzd/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,schoenb/MoonGen,dschoeffm/MoonGen,bmichalo/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,werpat/MoonGen,duk3luk3/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,scholzd/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,kidaa/MoonGen,wenhuizhang/MoonGen,schoenb/MoonGen,kidaa/MoonGen,slyon/MoonGen,scholzd/MoonGen,duk3luk3/MoonGen,slyon/MoonGen,werpat/MoonGen,bmichalo/MoonGen
432745efe5ae1e012dd805d6f9f22656f8ec2092
transferometer.lua
transferometer.lua
#!/usr/bin/env lua -- Copyright (C) 2017 Linus Ruth -- -- This is free software, licensed under the Apache License, Version 2.0. local label = {} local transfer = {} function Label (table) if table.mac then label[table.mac] = { name = table.name, tags = table.tags } end end function Transfer (table) if table.date then transfer[table.date] = { bytes_in = table.bytes_in, bytes_out = table.bytes_out, bytes_total = table.bytes_total } end end local function file_exists (path) local file = io.open(path, 'r') if file then return file:close() end return false end local function command_result (command) local file = assert(io.popen(command, 'r')) local result = file:read('*a') file:close() return result end local function command_result_array (command) local file = assert(io.popen(command, 'r')) local result = {} local i = 1 for line in file:lines() do result[i] = line i = i + 1 end file:close() return result end -- Create an accounting chain (ex. TRANSFEROMETER_INPUT) for a built-in chain -- (ex. INPUT) to contain rules for logging host data throughput. local function create_accounting_chain (built_in_chain) os.execute('iptables -t mangle -N TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Delete an accounting chain (ex. TRANSFEROMETER_INPUT) for a built-in chain -- (ex. INPUT) including any rules it may contain. local function delete_accounting_chain (built_in_chain) os.execute('iptables -t mangle -F TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') os.execute('iptables -t mangle -X TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Insert rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT). -- It must be evaluated first, so it will be inserted at the head of the chain. local function insert_diversion_rule (built_in_chain) os.execute('iptables -t mangle -I ' .. built_in_chain .. ' -j TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Delete rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT), -- including any duplicates of the rule which may exist. local function delete_diversion_rule (built_in_chain) local command = 'iptables -t mangle -D ' .. built_in_chain .. ' -j TRANSFEROMETER_' .. built_in_chain .. ' 2>&1' repeat until string.match(command_result(command), "%S+") end -- Verifies that the rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT), -- exists at the head of the built-in chain, and is unique within it. -- If either condition is false, then all diversion rules will be deleted -- and a new diversion rule will be inserted at the head of the built-in chain. local function maintain_diversion_rule (built_in_chain) local command = 'iptables -t mangle -n --line-numbers -L ' .. built_in_chain .. ' 2>&1' local output = command_result(command) local accounting_chain = 'TRANSFEROMETER_' .. built_in_chain local rules = {} for rule_number in string.gmatch(output, "(%d+)%s*" .. accounting_chain) do table.insert(rules, rule_number) end if rules[1] == '1' and #rules == 1 then break else delete_diversion_rule(built_in_chain) insert_diversion_rule(built_in_chain) end end local function demo () print 'MAC Label DB:' local label_db = io.read() if file_exists(label_db) then dofile(label_db) else print 'File not found!' os.exit() end print 'Transfer DB:' local transfer_db = io.read() if file_exists(transfer_db) then dofile(transfer_db) else print 'File not found!' os.exit() end for k, v in pairs(transfer) do print('Date: ' .. k) for k, v in pairs(v.bytes_total) do print('\tMAC: ' .. k, 'Name: ' .. label[k].name, '\tBytes Total: ' .. v) end end end local function test () create_accounting_chain('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') verify_diversion_rule('INPUT') delete_diversion_rule('INPUT') delete_accounting_chain('INPUT') end test()
#!/usr/bin/env lua -- Copyright (C) 2017 Linus Ruth -- -- This is free software, licensed under the Apache License, Version 2.0. local label = {} local transfer = {} function Label (table) if table.mac then label[table.mac] = { name = table.name, tags = table.tags } end end function Transfer (table) if table.date then transfer[table.date] = { bytes_in = table.bytes_in, bytes_out = table.bytes_out, bytes_total = table.bytes_total } end end local function file_exists (path) local file = io.open(path, 'r') if file then return file:close() end return false end local function command_result (command) local file = assert(io.popen(command, 'r')) local result = file:read('*a') file:close() return result end local function command_result_array (command) local file = assert(io.popen(command, 'r')) local result = {} local i = 1 for line in file:lines() do result[i] = line i = i + 1 end file:close() return result end -- Create an accounting chain (ex. TRANSFEROMETER_INPUT) for a built-in chain -- (ex. INPUT) to contain rules for logging host data throughput. local function create_accounting_chain (built_in_chain) os.execute('iptables -t mangle -N TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Delete an accounting chain (ex. TRANSFEROMETER_INPUT) for a built-in chain -- (ex. INPUT) including any rules it may contain. local function delete_accounting_chain (built_in_chain) os.execute('iptables -t mangle -F TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') os.execute('iptables -t mangle -X TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Insert rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT). -- It must be evaluated first, so it will be inserted at the head of the chain. local function insert_diversion_rule (built_in_chain) os.execute('iptables -t mangle -I ' .. built_in_chain .. ' -j TRANSFEROMETER_' .. built_in_chain .. ' 1>/dev/null 2>&1') end -- Delete rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT), -- including any duplicates of the rule which may exist. local function delete_diversion_rule (built_in_chain) local command = 'iptables -t mangle -D ' .. built_in_chain .. ' -j TRANSFEROMETER_' .. built_in_chain .. ' 2>&1' repeat until string.match(command_result(command), "%S+") end -- Verifies that the rule necessary to divert packets from a built-in chain -- (ex. INPUT) to a corresponding accounting chain (ex. TRANSFEROMETER_INPUT), -- exists at the head of the built-in chain, and is unique within it. -- If either condition is false, then all diversion rules will be deleted -- and a new diversion rule will be inserted at the head of the built-in chain. local function maintain_diversion_rule (built_in_chain) local command = 'iptables -t mangle -n --line-numbers -L ' .. built_in_chain .. ' 2>&1' local output = command_result(command) local accounting_chain = 'TRANSFEROMETER_' .. built_in_chain local rules = {} for rule_number in string.gmatch(output, "(%d+)%s*" .. accounting_chain) do table.insert(rules, rule_number) end if rules[1] ~= '1' or #rules ~= 1 then delete_diversion_rule(built_in_chain) insert_diversion_rule(built_in_chain) end end local function demo () print 'MAC Label DB:' local label_db = io.read() if file_exists(label_db) then dofile(label_db) else print 'File not found!' os.exit() end print 'Transfer DB:' local transfer_db = io.read() if file_exists(transfer_db) then dofile(transfer_db) else print 'File not found!' os.exit() end for k, v in pairs(transfer) do print('Date: ' .. k) for k, v in pairs(v.bytes_total) do print('\tMAC: ' .. k, 'Name: ' .. label[k].name, '\tBytes Total: ' .. v) end end end local function test () create_accounting_chain('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') insert_diversion_rule('INPUT') maintain_diversion_rule('INPUT') delete_diversion_rule('INPUT') delete_accounting_chain('INPUT') end test()
fix: maintain_diversion_rule logic and incorrect use of 'break'
fix: maintain_diversion_rule logic and incorrect use of 'break'
Lua
apache-2.0
linusruth/transferometer
7cebd8f1a83532c9d0c2c88b4e0f22c1042152ea
src/output.lua
src/output.lua
-- ============================================================================= -- import -- ============================================================================= local convert = require("convert") -- ============================================================================= -- output -- ============================================================================= local output = { -- inner bitmap data = nil, -- outputbase base = 2, -- range from = nil, to = nil, -- style flags gap = 4, sep = " ", islist = false, -- if display with sheet } -- private function-------------------- local function reverse(_table) if type(_table) ~= "table" then return nil, "error: expect got table" end local b, e = 1, #_table while(b < e) do _table[b], _table[e] = _table[e], _table[b] b = b + 1 e = e - 1 end return _table end local function print_string(output) local gap = 1 local str_arr = {} local to, from = output:get_range() local head = string.format("%d,%d:", to - 1, from - 1) local binstr = output:binstr() local str = convert.output_convert(binstr, output.base) for word in string.gmatch(str, "%w") do table.insert(str_arr, word) if gap == output.gap then table.insert(str_arr, output.sep) gap = 1 else gap = gap + 1 end end -- insert white-space and replace the first separator if str_arr[1] == output.sep then str_arr[1] = " " else table.insert(str_arr, 1, " ") end local body = table.concat(str_arr) print(head .. body) end local function print_list(output) local gap = 1 local str_arr = {} local from, to = output:get_range() local head = string.format("%d,%d:\n", to - 1, from - 1) for i = from, to, 1 do local templete = string.format("[%d] = %s", i - 1, output:bitat(i)) table.insert(str_arr, 1, templete) end local body = table.concat(str_arr, "\n") print(head .. body) end -- public function--------------------- function output:get_range() return self.from, self.to end function output:bitat(idx) return self.data[idx] end function output:isfull() if self.from ~= 1 then return false end if #self.data ~= self.to then return false end return true end function output:binstr() return convert.table_to_binstr(self.data, self:get_range()) end -- ======= config function ============ --[[ the range only be configed one times --]] function output:set_range_once(from, to) self.from = self.from or from self.to = self.to or to end --[[ the output range --]] function output:set_range(pattern) local from, to = convert.parse_range(pattern) self:set_range_once(from, to) end --[[ the style of output( separator, gap) --]] function output:set_style(sep, gap) self.sep = sep or self.sep self.gap = gap or self.gap end --[[ Did the output with list-style. --]] function output:set_list(islist) self.islist = islist end function output:set_base(obase) self.base = obase end --[[ @bits_table usually from bitmap:get() --]] function output:set(bits_table) self.data = bits_table self:set_range_once(1, #bits_table) end function output:print() if self.base == 2 and self.islist then print_list(self) else print_string(self) end end return output
-- ============================================================================= -- import -- ============================================================================= local convert = require("convert") -- ============================================================================= -- output -- ============================================================================= local output = { -- inner bitmap data = nil, -- outputbase base = 2, -- range from = nil, to = nil, -- style flags gap = 4, sep = " ", islist = false, -- if display with sheet } -- private function-------------------- local function reverse(_table) if type(_table) ~= "table" then return nil, "error: expect got table" end local b, e = 1, #_table while(b < e) do _table[b], _table[e] = _table[e], _table[b] b = b + 1 e = e - 1 end return _table end local function print_string(output) local gap = 1 local str_arr = {} local to, from = output:get_range() local head = string.format("%d,%d:", to - 1, from - 1) local binstr = output:binstr() local str = convert.output_convert(binstr, output.base) for word in string.gmatch(str, "%w") do table.insert(str_arr, word) end for i = #str_arr, 1, -1 do if gap == output.gap then table.insert(str_arr, i, output.sep) gap = 1 else gap = gap + 1 end end -- insert white-space and replace the first separator if str_arr[1] == output.sep then str_arr[1] = " " else table.insert(str_arr, 1, " ") end local body = table.concat(str_arr) print(head .. body) end local function print_list(output) local gap = 1 local str_arr = {} local from, to = output:get_range() local head = string.format("%d,%d:\n", to - 1, from - 1) for i = from, to, 1 do local templete = string.format("[%d] = %s", i - 1, output:bitat(i)) table.insert(str_arr, 1, templete) end local body = table.concat(str_arr, "\n") print(head .. body) end -- public function--------------------- function output:get_range() return self.from, self.to end function output:bitat(idx) return self.data[idx] end function output:isfull() if self.from ~= 1 then return false end if #self.data ~= self.to then return false end return true end function output:binstr() return convert.table_to_binstr(self.data, self:get_range()) end -- ======= config function ============ --[[ the range only be configed one times --]] function output:set_range_once(from, to) self.from = self.from or from self.to = self.to or to end --[[ the output range --]] function output:set_range(pattern) local from, to = convert.parse_range(pattern) self:set_range_once(from, to) end --[[ the style of output( separator, gap) --]] function output:set_style(sep, gap) self.sep = sep or self.sep self.gap = gap or self.gap end --[[ Did the output with list-style. --]] function output:set_list(islist) self.islist = islist end function output:set_base(obase) self.base = obase end --[[ @bits_table usually from bitmap:get() --]] function output:set(bits_table) self.data = bits_table self:set_range_once(1, #bits_table) end function output:print() if self.base == 2 and self.islist then print_list(self) else print_string(self) end end return output
fix(output): error gap site
fix(output): error gap site
Lua
mit
mum-chen/bit-util
1be6ccfffe4920d7e237f970a12a911d383ac8fc
state/initialize.lua
state/initialize.lua
--[[-- INITIALIZE STATE ---- Initialize resources needed for the game. --]]-- local st = RunState.new() local mt = {__tostring = function() return 'RunState.initialize' end} setmetatable(st, mt) function st:init() -- entity databases HeroDB = getClass('wyx.entity.HeroEntityDB')() EnemyDB = getClass('wyx.entity.EnemyEntityDB')() ItemDB = getClass('wyx.entity.ItemEntityDB')() -- create systems RenderSystem = getClass('wyx.system.RenderSystem')() TimeSystem = getClass('wyx.system.TimeSystem')() CollisionSystem = getClass('wyx.system.CollisionSystem')() -- instantiate world World = getClass('wyx.map.World')() end function st:enter(prevState, nextState) if Console then Console:show() end self._nextState = nextState self._loadStep = 0 self._doLoadStep = true end function st:leave() self._doLoadStep = nil self._loadStep = nil end function st:destroy() World:destroy() EntityRegistry = nil -- destroy systems RenderSystem:destroy() TimeSystem:destroy() CollisionSystem:destroy() RenderSystem = nil TimeSystem = nil CollisionSystem = nil -- destroy entity databases HeroDB:destroy() EnemyDB:destroy() ItemDB:destroy() HeroDB = nil EnemyDB = nil ItemDB = nil end function st:_makeEntityRegistry() -- TODO: make this not global EntityRegistry = World:getEntityRegistry() end -- make a ridiculous seed for the PRNG function st:_makeGameSeed() local time = os.time() local ltime = math.floor(love.timer.getTime() * 10000000) local mtime = math.floor(love.timer.getMicroTime() * 1000) local mx = love.mouse.getX() local my = love.mouse.getY() if time < ltime then time, ltime = ltime, time end GAMESEED = (time - ltime) + mtime + mx + my math.randomseed(GAMESEED) math.random() math.random() math.random() local rand = math.floor(math.random() * 10000000) GAMESEED = GAMESEED + rand -- create the real global PRNG instance with this ridiculous seed Random = random.new(GAMESEED) end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_makeGameSeed() end, [2] = function() self:_makeEntityRegistry() end, [3] = function() HeroDB:load() end, [4] = function() EnemyDB:load() end, [5] = function() ItemDB:load() end, [6] = function() RunState.switch(State[self._nextState]) end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() end function st:keypressed(key, unicode) end return st
--[[-- INITIALIZE STATE ---- Initialize resources needed for the game. --]]-- local st = RunState.new() local mt = {__tostring = function() return 'RunState.initialize' end} setmetatable(st, mt) local maxn = table.maxn function st:init() -- entity databases HeroDB = getClass('wyx.entity.HeroEntityDB')() EnemyDB = getClass('wyx.entity.EnemyEntityDB')() ItemDB = getClass('wyx.entity.ItemEntityDB')() -- create systems RenderSystem = getClass('wyx.system.RenderSystem')() TimeSystem = getClass('wyx.system.TimeSystem')() CollisionSystem = getClass('wyx.system.CollisionSystem')() -- instantiate world World = getClass('wyx.map.World')() end function st:enter(prevState, ...) if Console then Console:show() end self._nextStates = {...} self._loadStep = 0 self._doLoadStep = true end function st:leave() if self._nextStates then for k in pairs(self._nextStates) do self._nextStates[k] = nil end self._nextStates = nil end self._doLoadStep = nil self._loadStep = nil end function st:destroy() World:destroy() EntityRegistry = nil -- destroy systems RenderSystem:destroy() TimeSystem:destroy() CollisionSystem:destroy() RenderSystem = nil TimeSystem = nil CollisionSystem = nil -- destroy entity databases HeroDB:destroy() EnemyDB:destroy() ItemDB:destroy() HeroDB = nil EnemyDB = nil ItemDB = nil end function st:_makeEntityRegistry() -- TODO: make this not global EntityRegistry = World:getEntityRegistry() end -- make a ridiculous seed for the PRNG function st:_makeGameSeed() local time = os.time() local ltime = math.floor(love.timer.getTime() * 10000000) local mtime = math.floor(love.timer.getMicroTime() * 1000) local mx = love.mouse.getX() local my = love.mouse.getY() if time < ltime then time, ltime = ltime, time end GAMESEED = (time - ltime) + mtime + mx + my math.randomseed(GAMESEED) math.random() math.random() math.random() local rand = math.floor(math.random() * 10000000) GAMESEED = GAMESEED + rand -- create the real global PRNG instance with this ridiculous seed Random = random.new(GAMESEED) end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_makeGameSeed() end, [2] = function() self:_makeEntityRegistry() end, [3] = function() HeroDB:load() end, [4] = function() EnemyDB:load() end, [5] = function() ItemDB:load() end, [6] = function() local states = self._nextStates if states then local nextState = states[1] if #states > 1 then RunState.switch(State[nextState], unpack(states, 2, maxn(states))) else RunState.switch(State[nextState]) end end end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() end function st:keypressed(key, unicode) end return st
fix state stack in initialize state
fix state stack in initialize state
Lua
mit
scottcs/wyx
094b20aae7352fade66def63d21a0d72611304a3
lualib/snax/gateserver.lua
lualib/snax/gateserver.lua
local skynet = require "skynet" local netpack = require "skynet.netpack" local socketdriver = require "skynet.socketdriver" local gateserver = {} local socket -- listen socket local queue -- message queue local maxclient -- max client local client_number = 0 local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end }) local nodelay = false local connection = {} function gateserver.openclient(fd) if connection[fd] then socketdriver.start(fd) end end function gateserver.closeclient(fd) local c = connection[fd] if c then connection[fd] = false socketdriver.close(fd) end end function gateserver.start(handler) assert(handler.message) assert(handler.connect) function CMD.open( source, conf ) assert(not socket) local address = conf.address or "0.0.0.0" local port = assert(conf.port) maxclient = conf.maxclient or 1024 nodelay = conf.nodelay skynet.error(string.format("Listen on %s:%d", address, port)) socket = socketdriver.listen(address, port) socketdriver.start(socket) if handler.open then return handler.open(source, conf) end end function CMD.close() assert(socket) socketdriver.close(socket) end local MSG = {} local function dispatch_msg(fd, msg, sz) if connection[fd] then handler.message(fd, msg, sz) else skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz))) end end MSG.data = dispatch_msg local function dispatch_queue() local fd, msg, sz = netpack.pop(queue) if fd then -- may dispatch even the handler.message blocked -- If the handler.message never block, the queue should be empty, so only fork once and then exit. skynet.fork(dispatch_queue) dispatch_msg(fd, msg, sz) for fd, msg, sz in netpack.pop, queue do dispatch_msg(fd, msg, sz) end end end MSG.more = dispatch_queue function MSG.open(fd, msg) if client_number >= maxclient then socketdriver.close(fd) return end if nodelay then socketdriver.nodelay(fd) end connection[fd] = true client_number = client_number + 1 handler.connect(fd, msg) end local function close_fd(fd) local c = connection[fd] if c ~= nil then connection[fd] = nil client_number = client_number - 1 end end function MSG.close(fd) if fd ~= socket then if handler.disconnect then handler.disconnect(fd) end close_fd(fd) else socket = nil end end function MSG.error(fd, msg) if fd == socket then skynet.error("gateserver accpet error:",msg) else if handler.error then handler.error(fd, msg) end close_fd(fd) end end function MSG.warning(fd, size) if handler.warning then handler.warning(fd, size) end end skynet.register_protocol { name = "socket", id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6 unpack = function ( msg, sz ) return netpack.filter( queue, msg, sz) end, dispatch = function (_, _, q, type, ...) queue = q if type then MSG[type](...) end end } local function init() skynet.dispatch("lua", function (_, address, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(address, ...))) else skynet.ret(skynet.pack(handler.command(cmd, address, ...))) end end) end if handler.embed then init() else skynet.start(init) end end return gateserver
local skynet = require "skynet" local netpack = require "skynet.netpack" local socketdriver = require "skynet.socketdriver" local gateserver = {} local socket -- listen socket local queue -- message queue local maxclient -- max client local client_number = 0 local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end }) local nodelay = false local connection = {} -- true : connected -- nil : closed -- false : close read function gateserver.openclient(fd) if connection[fd] then socketdriver.start(fd) end end function gateserver.closeclient(fd) local c = connection[fd] if c ~= nil then connection[fd] = nil socketdriver.close(fd) end end function gateserver.start(handler) assert(handler.message) assert(handler.connect) function CMD.open( source, conf ) assert(not socket) local address = conf.address or "0.0.0.0" local port = assert(conf.port) maxclient = conf.maxclient or 1024 nodelay = conf.nodelay skynet.error(string.format("Listen on %s:%d", address, port)) socket = socketdriver.listen(address, port) socketdriver.start(socket) if handler.open then return handler.open(source, conf) end end function CMD.close() assert(socket) socketdriver.close(socket) end local MSG = {} local function dispatch_msg(fd, msg, sz) if connection[fd] then handler.message(fd, msg, sz) else skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz))) end end MSG.data = dispatch_msg local function dispatch_queue() local fd, msg, sz = netpack.pop(queue) if fd then -- may dispatch even the handler.message blocked -- If the handler.message never block, the queue should be empty, so only fork once and then exit. skynet.fork(dispatch_queue) dispatch_msg(fd, msg, sz) for fd, msg, sz in netpack.pop, queue do dispatch_msg(fd, msg, sz) end end end MSG.more = dispatch_queue function MSG.open(fd, msg) if client_number >= maxclient then socketdriver.shutdown(fd) return end if nodelay then socketdriver.nodelay(fd) end connection[fd] = true client_number = client_number + 1 handler.connect(fd, msg) end function MSG.close(fd) if fd ~= socket then client_number = client_number - 1 if connection[fd] then connection[fd] = false -- close read end if handler.disconnect then handler.disconnect(fd) else socketdriver.close(fd) end else socket = nil end end function MSG.error(fd, msg) if fd == socket then skynet.error("gateserver accpet error:",msg) else socketdriver.shutdown(fd) if handler.error then handler.error(fd, msg) end end end function MSG.warning(fd, size) if handler.warning then handler.warning(fd, size) end end skynet.register_protocol { name = "socket", id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6 unpack = function ( msg, sz ) return netpack.filter( queue, msg, sz) end, dispatch = function (_, _, q, type, ...) queue = q if type then MSG[type](...) end end } local function init() skynet.dispatch("lua", function (_, address, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(address, ...))) else skynet.ret(skynet.pack(handler.command(cmd, address, ...))) end end) end if handler.embed then init() else skynet.start(init) end end return gateserver
fix half close issue, #1358
fix half close issue, #1358
Lua
mit
xjdrew/skynet,icetoggle/skynet,icetoggle/skynet,cloudwu/skynet,pigparadise/skynet,korialuo/skynet,wangyi0226/skynet,xjdrew/skynet,cloudwu/skynet,sanikoyes/skynet,korialuo/skynet,cloudwu/skynet,korialuo/skynet,pigparadise/skynet,hongling0/skynet,pigparadise/skynet,hongling0/skynet,hongling0/skynet,sanikoyes/skynet,icetoggle/skynet,wangyi0226/skynet,wangyi0226/skynet,sanikoyes/skynet,xjdrew/skynet
6826e51fa01c5838010adc33524c272a6c825078
testflight.lua
testflight.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "app" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, item_value) then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and not string.match(url, "/static/") then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "app" then if string.match(url, "testflightapp%.com/install/"..item_value.."/") then html = read_file(file) if string.match(html, "find the build you are looking for%. Perhaps it was removed or you were sent an incorrect url%.") then local newurl1 = "https://www.testflightapp.com/api/builds/"..item_value.."/6280ca3ee10631fd6817100ffd1ee849-MTMzMzc3.plist" check(newurl1) local newurl2 = "https://www.testflightapp.com/join/"..item_value.."/" check(newurl2) local newurl3 = "https://www.testflightapp.com/join/login/"..item_value.."/" check(newurl3) end end if stringmatch(url, "testflightapp%.com/api/builds/"..item_value.."/6280ca3ee10631fd6817100ffd1ee849%-MTMzMzc3%.plist") then html = read_file(file) for newurl in string.gmatch(html, ">(https?://[^<]+)<") do check(newurl) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.EXIT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "app" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, item_value) or string.match(url, "%.cloudfront%.net") then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and not string.match(url, "/static/") then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "app" then if string.match(url, "testflightapp%.com/install/"..item_value.."/") then html = read_file(file) if not string.match(html, "find the build you are looking for%. Perhaps it was removed or you were sent an incorrect url%.") then local newurl1 = "https://www.testflightapp.com/api/builds/"..item_value.."/6280ca3ee10631fd6817100ffd1ee849-MTMzMzc3.plist" check(newurl1) local newurl2 = "https://www.testflightapp.com/join/"..item_value.."/" check(newurl2) local newurl3 = "https://www.testflightapp.com/join/login/"..item_value.."/" check(newurl3) end end if stringmatch(url, "testflightapp%.com/api/builds/"..item_value.."/6280ca3ee10631fd6817100ffd1ee849%-MTMzMzc3%.plist") then html = read_file(file) for newurl in string.gmatch(html, ">(https?://[^<]+)<") do check(newurl) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.EXIT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
testflight.lua: fix
testflight.lua: fix
Lua
unlicense
ArchiveTeam/testflight-grab,ArchiveTeam/testflight-grab
2dabe443cbd401b119d687caf45d7940c5ff1145
Farming/harvest.lua
Farming/harvest.lua
local args = {...} local direction -- Print usage if #args ~= 2 then print("Usage: harvest <x> <z> <left|right>") return else -- left = 0; right = 1 direction = argument == "right" and 1 or 0 end function checkItem(item) for i = 1, 16 do if turtle.getItemDetail(i).name == item then return turtle.select(i) end end return false end function checkGrowth() local _, data = turtle.inspectDown() return (data ~= nil and data.name == "minecraft:wheat" and data.metadata == 7) end function placeSeed() if checkItem("minecraft:wheat_seeds") then turtle.placeDown() end end function turn(z) if z % 2 == 0 then turtle.turnLeft() turtle.forward() turtle.turnLeft() else turtle.turnRight() turtle.forward() turtle.turnRight() end end for z = 1, args[2] do for x = 1, args[1] do -- Harvest fully grown wheat if checkGrowth() then turtle.digDown() end -- Place seed. Only successful if above dirt. placeSeed() if x == tonumber(args[1]) then if z == tonumber(args[2]) then -- Back up if odd z level if z % 2 > 0 then for i = 1, x do turtle.back() end end turn(z - direction) for i = 1, z do turtle.forward() end end -- Turn facing specified direction to next x row turn(z + direction) else while not turtle.forward() do turtle.dig() end end end end
local args = {...} local direction -- Print usage if #args ~= 3 then print("Usage: harvest <x> <z> <left|right>") return else -- left = 0; right = 1 direction = argument == "right" and 1 or 0 end function checkItem(item) for i = 1, 16 do if turtle.getItemDetail(i) ~= nil and turtle.getItemDetail(i).name == item then return turtle.select(i) end end return false end function checkGrowth() local _, data = turtle.inspectDown() return (data ~= nil and data.name == "minecraft:wheat" and data.metadata == 7) end function placeSeed() if checkItem("minecraft:wheat_seeds") then turtle.placeDown() end end function nextRow(z) if z % 2 == 0 then turtle.turnLeft() turtle.forward() turtle.turnLeft() else turtle.turnRight() turtle.forward() turtle.turnRight() end end function turn(z) if (z) % 2 == 0 then turtle.turnLeft() else turtle.turnRight() end end for z = 1, args[2] do for x = 1, args[1] do -- Harvest fully grown wheat if checkGrowth() then turtle.digDown() end -- Place seed. Only successful if above dirt. placeSeed() if x == tonumber(args[1]) then if z == tonumber(args[2]) then -- Back up if odd z level if z % 2 ~= 0 then for i = 1, x do turtle.back() end end turn(z + direction - 1) for _ = 1, z - 1 do turtle.forward() end turn(z + direction - 1) else -- Turn facing specified direction to next x row nextRow(z + direction) end else while not turtle.forward() do turtle.dig() end end end end
Fix bug when going to start pos
Fix bug when going to start pos
Lua
unlicense
Carlgo11/computercraft
4bc782490f0dc420f64100d3d1bcc69ee4bc1a4d
src/instanceutils/src/Shared/RxInstanceUtils.lua
src/instanceutils/src/Shared/RxInstanceUtils.lua
--[=[ Utility functions to observe the state of Roblox. This is a very powerful way to query Roblox's state. :::tip Use RxInstanceUtils to program streaming enabled games, and make it easy to debug. This API surface lets you use Roblox as a source-of-truth which is very valuable. ::: @class RxInstanceUtils ]=] local require = require(script.Parent.loader).load(script) local Brio = require("Brio") local Maid = require("Maid") local Observable = require("Observable") local Rx = require("Rx") local RxInstanceUtils = {} --[=[ Observes an instance's property @param instance Instance @param propertyName string @return Observable<T> ]=] function RxInstanceUtils.observeProperty(instance, propertyName) assert(typeof(instance) == "Instance", "Not an instance") assert(type(propertyName) == "string", "Bad propertyName") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(instance:GetPropertyChangedSignal(propertyName):Connect(function() sub:Fire(instance[propertyName], instance) end)) sub:Fire(instance[propertyName], instance) return maid end) end --[=[ Observes an instance's ancestry @param instance Instance @return Observable<Instance> ]=] function RxInstanceUtils.observeAncestry(instance) local startWithParent = Rx.start(function() return instance, instance.Parent end) return startWithParent(Rx.fromSignal(instance.AncestryChanged)) end --[=[ Returns a brio of the property value @param instance Instance @param propertyName string @param predicate ((value: T) -> boolean)? -- Optional filter @return Observable<Brio<T>> ]=] function RxInstanceUtils.observePropertyBrio(instance, propertyName, predicate) assert(typeof(instance) == "Instance", "Bad instance") assert(type(propertyName) == "string", "Bad propertyName") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local function handlePropertyChanged() maid._property = nil local propertyValue = instance[propertyName] if not predicate or predicate(propertyValue) then local brio = Brio.new(instance[propertyName]) maid._property = brio sub:Fire(brio) end end maid:GiveTask(instance:GetPropertyChangedSignal(propertyName):Connect(handlePropertyChanged)) handlePropertyChanged() return maid end) end --[=[ Observes the last child with a specific name. @param parent Instance @param className string @param name string @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeLastNamedChildBrio(parent, className, name) assert(typeof(parent) == "Instance", "Bad parent") assert(type(className) == "string", "Bad className") assert(type(name) == "string", "Bad name") return Observable.new(function(sub) local topMaid = Maid.new() local function handleChild(child) if not child:IsA(className) then return end local maid = Maid.new() local function handleNameChanged() if child.Name == name then local brio = Brio.new(child) maid._brio = brio topMaid._lastBrio = brio sub:Fire(brio) else maid._brio = nil end end maid:GiveTask(child:GetPropertyChangedSignal("Name"):Connect(handleNameChanged)) handleNameChanged() topMaid[child] = maid end topMaid:GiveTask(parent.ChildAdded:Connect(handleChild)) topMaid:GiveTask(parent.ChildRemoved:Connect(function(child) topMaid[child] = nil end)) for _, child in pairs(parent:GetChildren()) do handleChild(child) end return topMaid end) end --[=[ Observes all children of a specific class @param parent Instance @param className string @return Observable<Instance> ]=] function RxInstanceUtils.observeChildrenOfClassBrio(parent, className) assert(typeof(parent) == "Instance", "Bad parent") assert(type(className) == "string", "Bad className") return RxInstanceUtils.observeChildrenBrio(parent, function(child) return child:IsA(className) end) end --[=[ Observes all children @param parent Instance @param predicate ((value: Instance) -> boolean)? -- Optional filter @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeChildrenBrio(parent, predicate) assert(typeof(parent) == "Instance", "Bad parent") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local function handleChild(child) if not predicate or predicate(child) then local value = Brio.new(child) maid[child] = value sub:Fire(value) end end maid:GiveTask(parent.ChildAdded:Connect(handleChild)) maid:GiveTask(parent.ChildRemoved:Connect(function(child) maid[child] = nil end)) for _, child in pairs(parent:GetChildren()) do handleChild(child) end return maid end) end --[=[ Observes all descendants that match a predicate @param parent Instance @param predicate ((value: Instance) -> boolean)? -- Optional filter @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeDescendants(parent, predicate) assert(typeof(parent) == "Instance", "Bad parent") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local added = {} local function handleDescendant(child) if not predicate or predicate(child) then added[child] = true sub:Fire(child, true) end end maid:GiveTask(parent.DescendantAdded:Connect(handleDescendant)) maid:GiveTask(parent.DescendantRemoving:Connect(function(child) if added[child] then added[child] = nil sub:Fire(child, false) end end)) for _, descendant in pairs(parent:GetDescendants()) do handleDescendant(descendant) end return maid end) end return RxInstanceUtils
--[=[ Utility functions to observe the state of Roblox. This is a very powerful way to query Roblox's state. :::tip Use RxInstanceUtils to program streaming enabled games, and make it easy to debug. This API surface lets you use Roblox as a source-of-truth which is very valuable. ::: @class RxInstanceUtils ]=] local require = require(script.Parent.loader).load(script) local Brio = require("Brio") local Maid = require("Maid") local Observable = require("Observable") local Rx = require("Rx") local RxInstanceUtils = {} --[=[ Observes an instance's property @param instance Instance @param propertyName string @return Observable<T> ]=] function RxInstanceUtils.observeProperty(instance, propertyName) assert(typeof(instance) == "Instance", "'instance' should be of type Instance") assert(type(propertyName) == "string", "'propertyName' should be of type string") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(instance:GetPropertyChangedSignal(propertyName):Connect(function() sub:Fire(instance[propertyName], instance) end)) sub:Fire(instance[propertyName], instance) return maid end) end --[=[ Observes an instance's ancestry @param instance Instance @return Observable<Instance> ]=] function RxInstanceUtils.observeAncestry(instance) local startWithParent = Rx.start(function() return instance, instance.Parent end) return startWithParent(Rx.fromSignal(instance.AncestryChanged)) end --[=[ Returns a brio of the property value @param instance Instance @param propertyName string @param predicate ((value: T) -> boolean)? -- Optional filter @return Observable<Brio<T>> ]=] function RxInstanceUtils.observePropertyBrio(instance, propertyName, predicate) assert(typeof(instance) == "Instance", "Bad instance") assert(type(propertyName) == "string", "Bad propertyName") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local function handlePropertyChanged() maid._property = nil local propertyValue = instance[propertyName] if not predicate or predicate(propertyValue) then local brio = Brio.new(instance[propertyName]) maid._property = brio sub:Fire(brio) end end maid:GiveTask(instance:GetPropertyChangedSignal(propertyName):Connect(handlePropertyChanged)) handlePropertyChanged() return maid end) end --[=[ Observes the last child with a specific name. @param parent Instance @param className string @param name string @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeLastNamedChildBrio(parent, className, name) assert(typeof(parent) == "Instance", "Bad parent") assert(type(className) == "string", "Bad className") assert(type(name) == "string", "Bad name") return Observable.new(function(sub) local topMaid = Maid.new() local function handleChild(child) if not child:IsA(className) then return end local maid = Maid.new() local function handleNameChanged() if child.Name == name then local brio = Brio.new(child) maid._brio = brio topMaid._lastBrio = brio sub:Fire(brio) else maid._brio = nil end end maid:GiveTask(child:GetPropertyChangedSignal("Name"):Connect(handleNameChanged)) handleNameChanged() topMaid[child] = maid end topMaid:GiveTask(parent.ChildAdded:Connect(handleChild)) topMaid:GiveTask(parent.ChildRemoved:Connect(function(child) topMaid[child] = nil end)) for _, child in pairs(parent:GetChildren()) do handleChild(child) end return topMaid end) end --[=[ Observes all children of a specific class @param parent Instance @param className string @return Observable<Instance> ]=] function RxInstanceUtils.observeChildrenOfClassBrio(parent, className) assert(typeof(parent) == "Instance", "Bad parent") assert(type(className) == "string", "Bad className") return RxInstanceUtils.observeChildrenBrio(parent, function(child) return child:IsA(className) end) end --[=[ Observes all children @param parent Instance @param predicate ((value: Instance) -> boolean)? -- Optional filter @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeChildrenBrio(parent, predicate) assert(typeof(parent) == "Instance", "Bad parent") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local function handleChild(child) if not predicate or predicate(child) then local value = Brio.new(child) maid[child] = value sub:Fire(value) end end maid:GiveTask(parent.ChildAdded:Connect(handleChild)) maid:GiveTask(parent.ChildRemoved:Connect(function(child) maid[child] = nil end)) for _, child in pairs(parent:GetChildren()) do handleChild(child) end return maid end) end --[=[ Observes all descendants that match a predicate @param parent Instance @param predicate ((value: Instance) -> boolean)? -- Optional filter @return Observable<Brio<Instance>> ]=] function RxInstanceUtils.observeDescendants(parent, predicate) assert(typeof(parent) == "Instance", "Bad parent") assert(type(predicate) == "function" or predicate == nil, "Bad predicate") return Observable.new(function(sub) local maid = Maid.new() local added = {} local function handleDescendant(child) if not predicate or predicate(child) then added[child] = true sub:Fire(child, true) end end maid:GiveTask(parent.DescendantAdded:Connect(handleDescendant)) maid:GiveTask(parent.DescendantRemoving:Connect(function(child) if added[child] then added[child] = nil sub:Fire(child, false) end end)) for _, descendant in pairs(parent:GetDescendants()) do handleDescendant(descendant) end return maid end) end return RxInstanceUtils
fix: Better error messages on RxInstanceUtils.observeProperty(instance, propertyName)
fix: Better error messages on RxInstanceUtils.observeProperty(instance, propertyName)
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
fc93182c58d4074cf5e4220fde066285f83594ce
data/scripts/player/eventscheduler.lua
data/scripts/player/eventscheduler.lua
if onServer() then package.path = package.path .. ";data/scripts/lib/?.lua" require ("randomext") require ("utility") -- <dcc title="require event balancer"> require ("dcc-event-balance/main") -- </dcc> local events = { {schedule = random():getInt(45, 60) * 60, script = "convoidistresssignal", arguments = {true}, to = 560}, {schedule = random():getInt(60, 80) * 60, script = "fakedistresssignal", arguments = {true}, to = 560}, {schedule = random():getInt(60, 80) * 60, script = "piratehunter", to = 560}, {schedule = random():getInt(25, 50) * 60, script = "alienattack", arguments = {0}, minimum = 5 * 60, from = 0, to = 500}, {schedule = random():getInt(35, 70) * 60, script = "alienattack", arguments = {1}, minimum = 25 * 60, to = 500}, {schedule = random():getInt(60, 80) * 60, script = "alienattack", arguments = {2}, minimum = 60 * 60, to = 350}, {schedule = random():getInt(80, 120) * 60, script = "alienattack", arguments = {3}, minimum = 120 * 60, to = 300}, {schedule = random():getInt(50, 70) * 60, script = "spawntravellingmerchant", to = 520}, } -- <dcc title="increase event delay"> local pause = (5 * 60) * EventBalance.PauseMultiplier -- </dcc> local pauseTime = pause function initialize() for _, event in pairs(events) do event.time = (event.minimum or 5 * 60) + math.random() * event.schedule end local frequency = 0 for _, event in pairs(events) do frequency = frequency + 1 / event.schedule end print ("player events roughly every " .. round((1 / frequency + pause) / 60, 2) .. " minutes") end function getUpdateInterval() return 5 end function updateServer(timeStep) local player = Player() -- timeStep = timeStep * 60 -- only run script for the lowest player index in the sector -> no stacking events local players = {Sector():getPlayers()} for _, p in pairs(players) do -- when there is a player with a lower index, we return if p.index < player.index then return end end -- <dcc title="disable multiple players speeding up events"> -- -- but, if we're not alone, we speed up events by 50% -- if #players > 1 then timeStep = timeStep * 1.5 end -- </dcc> if pauseTime > 0 then pauseTime = pauseTime - timeStep return end -- update times of events for _, event in pairs(events) do event.time = event.time - timeStep if event.time < 0 then -- check if the location is OK local from = event.from or 0 local to = event.to or math.huge local position = length(vec2(Sector():getCoordinates())) if position >= from and position <= to then -- <dcc title="determine if event should be skipped"> if EventBalance.ShouldSkipEvent(event) then print("event `" .. event.script .. "` skipped") return end -- </dcc> -- start event local arguments = event.arguments or {} Player():addScriptOnce(event.script, unpack(arguments)) event.time = event.schedule print ("starting event " .. event.script) pauseTime = pause break; end end end end function secure() local times = {} for _, event in pairs(events) do table.insert(times, event.time) end return times end function restore(times) for i = 1, math.min(#times, #events) do events[i].time = times[i] end end end
if onServer() then package.path = package.path .. ";data/scripts/lib/?.lua" require ("randomext") require ("utility") -- <dcc title="require event balancer"> require ("dcc-event-balance/main") -- </dcc> local events = { {schedule = random():getInt(45, 60) * 60, script = "convoidistresssignal", arguments = {true}, to = 560}, {schedule = random():getInt(60, 80) * 60, script = "fakedistresssignal", arguments = {true}, to = 560}, {schedule = random():getInt(60, 80) * 60, script = "piratehunter", to = 560}, {schedule = random():getInt(25, 50) * 60, script = "alienattack", arguments = {0}, minimum = 5 * 60, from = 0, to = 500}, {schedule = random():getInt(35, 70) * 60, script = "alienattack", arguments = {1}, minimum = 25 * 60, to = 500}, {schedule = random():getInt(60, 80) * 60, script = "alienattack", arguments = {2}, minimum = 60 * 60, to = 350}, {schedule = random():getInt(80, 120) * 60, script = "alienattack", arguments = {3}, minimum = 120 * 60, to = 300}, {schedule = random():getInt(50, 70) * 60, script = "spawntravellingmerchant", to = 520}, } -- <dcc title="increase event delay"> local pause = (5 * 60) * EventBalance.PauseMultiplier -- </dcc> local pauseTime = pause function initialize() for _, event in pairs(events) do event.time = (event.minimum or 5 * 60) + math.random() * event.schedule end local frequency = 0 for _, event in pairs(events) do frequency = frequency + 1 / event.schedule end print ("player events roughly every " .. round((1 / frequency + pause) / 60, 2) .. " minutes") end function getUpdateInterval() return 5 end function updateServer(timeStep) local player = Player() -- timeStep = timeStep * 60 -- only run script for the lowest player index in the sector -> no stacking events local players = {Sector():getPlayers()} for _, p in pairs(players) do -- when there is a player with a lower index, we return if p.index < player.index then return end end -- <dcc title="disable multiple players speeding up events"> -- -- but, if we're not alone, we speed up events by 50% -- if #players > 1 then timeStep = timeStep * 1.5 end -- </dcc> if pauseTime > 0 then pauseTime = pauseTime - timeStep return end -- update times of events for _, event in pairs(events) do event.time = event.time - timeStep if event.time < 0 then -- check if the location is OK local from = event.from or 0 local to = event.to or math.huge local position = length(vec2(Sector():getCoordinates())) if position >= from and position <= to then -- <dcc title="determine if event should be skipped"> if EventBalance.ShouldSkipEvent(event) then print("event `" .. event.script .. "` skipped") event.time = event.schedule return end -- </dcc> -- start event local arguments = event.arguments or {} Player():addScriptOnce(event.script, unpack(arguments)) event.time = event.schedule print ("starting event " .. event.script) pauseTime = pause break; end end end end function secure() local times = {} for _, event in pairs(events) do table.insert(times, event.time) end return times end function restore(times) for i = 1, math.min(#times, #events) do events[i].time = times[i] end end end
maybe fix events constantly attmepting forever when denied.
maybe fix events constantly attmepting forever when denied.
Lua
bsd-2-clause
darkconsole/avorion-event-balance,darkconsole/avorion-event-balance
1b6ee32abb09f9ee2b27a3773139f6a68a5ce9c2
plugins/mod_legacyauth.lua
plugins/mod_legacyauth.lua
local st = require "util.stanza"; local send = require "core.sessionmanager".send_to_session; local t_concat = table.concat; add_iq_handler("c2s_unauthed", "jabber:iq:auth", function (session, stanza) local username = stanza.tags[1]:child_with_name("username"); local password = stanza.tags[1]:child_with_name("password"); local resource = stanza.tags[1]:child_with_name("resource"); if not (username and password and resource) then local reply = st.reply(stanza); send(session, reply:query("jabber:iq:auth") :tag("username"):up() :tag("password"):up() :tag("resource"):up()); return true; else username, password, resource = t_concat(username), t_concat(password), t_concat(resource); local reply = st.reply(stanza); require "core.usermanager" if usermanager.validate_credentials(session.host, username, password) then -- Authentication successful! local success, err = sessionmanager.make_authenticated(session, username); if success then local err_type, err_msg; success, err_type, err, err_msg = sessionmanager.bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); return true; end end send(session, st.reply(stanza)); return true; else local reply = st.reply(stanza); reply.attr.type = "error"; reply:tag("error", { code = "401", type = "auth" }) :tag("not-authorized", { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" }); send(session, reply); return true; end end end);
local st = require "util.stanza"; local t_concat = table.concat; add_iq_handler("c2s_unauthed", "jabber:iq:auth", function (session, stanza) local username = stanza.tags[1]:child_with_name("username"); local password = stanza.tags[1]:child_with_name("password"); local resource = stanza.tags[1]:child_with_name("resource"); if not (username and password and resource) then local reply = st.reply(stanza); session.send(reply:query("jabber:iq:auth") :tag("username"):up() :tag("password"):up() :tag("resource"):up()); return true; else username, password, resource = t_concat(username), t_concat(password), t_concat(resource); local reply = st.reply(stanza); require "core.usermanager" if usermanager.validate_credentials(session.host, username, password) then -- Authentication successful! local success, err = sessionmanager.make_authenticated(session, username); if success then local err_type, err_msg; success, err_type, err, err_msg = sessionmanager.bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); return true; end end session.send(st.reply(stanza)); return true; else local reply = st.reply(stanza); reply.attr.type = "error"; reply:tag("error", { code = "401", type = "auth" }) :tag("not-authorized", { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" }); session.send(reply); return true; end end end);
Fixed mod_legacyauth to use session.send for sending stanzas
Fixed mod_legacyauth to use session.send for sending stanzas
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
022d8f4a9321caae63d60ac3b5d8e48a5339efdb
inventory.lua
inventory.lua
local component = require("component") local ic = component.inventory_controller local robot = require("robot") local sides = require("sides") local util = require("util") local inventory = {} function inventory.isOneOf(item, checkList) for _,chk in ipairs(checkList) do if chk == "!tool" then if item.maxDamage > 0 then return true end elseif string.match(item.name, chk) then return true end end return false end function inventory.dropAll(side, fromSlotNumber, exceptFor) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true exceptFor = exceptFor or {} fromSlotNumber = fromSlotNumber or 1 for i=fromSlotNumber,robot.inventorySize() do local c = robot.count(i) if c > 0 then local stack = ic.getStackInInternalSlot(i) if not inventory.isOneOf(stack, exceptFor) then robot.select(i) if side == nil or side == sides.front then robot.drop() elseif side == sides.bottom then robot.dropDown() elseif side == sides.top then robot.dropUp() end -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end --isOneOf end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) local isX = (x % 12) if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then return false end -- we skip every other x torch in the first row, -- and the 'other' every other torch in the next row local zRow = math.floor(z / 7) % 2 if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then return false end return true end function inventory.selectItem(pattern) for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and string.find(stack.name, pattern) ~= nil then robot.select(i) return true end end return false end function inventory.placeTorch(sideOfRobot, sideOfBlock) if inventory.selectItem("torch$") then local success if sideOfRobot == nil or sideOfRobot == sides.down then success = robot.placeDown(sideOfBlock or sides.bottom) elseif sideOfRobot == sides.front then success = robot.place(sideOfBlock or sides.bottom) end if success then return true end end return false end function inventory.isLocalFull() -- backwards cuz the later slots fill up last for i=robot.inventorySize(),1,-1 do local stack = ic.getStackInInternalSlot(i) if stack == nil then return false end end return true end function inventory.toolIsBroken() local d = robot.durability() d = util.trunc(d or 0, 2) return d <= 0 end function inventory.pickUpFreshTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local size = ic.getInventorySize(sideOfRobot) if size == nil then return false end local count = 0 for i=1,size do local stack = ic.getStackInSlot(sideOfRobot, i) -- is this the tool we want and fully repaired? if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) and stack.damage == stack.maxDamage then -- found one, get it! robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that if not ic.suckFromSlot(sideOfRobot, i) then return false end count = count + 1 end end return true, count end function inventory.dropBrokenTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local brokenToolsCount = 0 for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 -- drop it robot.select(i) local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or (sideOfRobot == sides.front and robot.drop(1)) if not result then return false, brokenToolsCount end end end end -- finally we need to see if the tool we are holding is broken robot.select(1) ic.equip() local stack = ic.getStackInInternalSlot(1) if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 if not robot.dropDown(1) then ic.equip() return false, brokenToolsCount end end end ic.equip() return true, brokenToolsCount end function inventory.equipFreshTool(itemName) if itemName == nil then -- use the currently selected tool as the pattern. -- first we must see what tool it is we currently have -- swap it with slot 1 robot.select(1) ic.equip() local currentTool = ic.getStackInInternalSlot() -- equip it back since whatever was in slot 1 might be important ic.equip() if currentTool == nil then -- no current tool, sorry return false end itemName = currentTool.name end for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if itemName == "!empty" then if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then -- found an empty slot or at least something that doesn't use durability robot.select(i) ic.equip() return true end elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then robot.select(i) ic.equip() -- found one but we need to check if it's got durability if not inventory.toolIsBroken() then return true end -- not durable enough, so put it back and keep looking ic.equip() end end return false end return inventory
local component = require("component") local ic = component.inventory_controller local robot = require("robot") local sides = require("sides") local util = require("util") local inventory = {} function inventory.isOneOf(item, checkList) for _,chk in ipairs(checkList) do if chk == "!tool" then if item.maxDamage > 0 then return true end elseif string.match(item.name, chk) then return true end end return false end function inventory.dropAll(side, fromSlotNumber, exceptFor) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true exceptFor = exceptFor or {} fromSlotNumber = fromSlotNumber or 1 for i=fromSlotNumber,robot.inventorySize() do local c = robot.count(i) if c > 0 then local stack = ic.getStackInInternalSlot(i) if not inventory.isOneOf(stack, exceptFor) then robot.select(i) if side == nil or side == sides.front then robot.drop() elseif side == sides.bottom then robot.dropDown() elseif side == sides.top then robot.dropUp() end -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end --isOneOf end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) local isX = (x % 12) if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then return false end -- we skip every other x torch in the first row, -- and the 'other' every other torch in the next row local zRow = math.floor(z / 7) % 2 if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then return false end return true end function inventory.selectItem(pattern) for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and string.find(stack.name, pattern) ~= nil then robot.select(i) return true end end return false end function inventory.placeTorch(sideOfRobot, sideOfBlock) if inventory.selectItem("torch$") then local success if sideOfRobot == nil or sideOfRobot == sides.down then success = robot.placeDown(sideOfBlock or sides.bottom) elseif sideOfRobot == sides.front then success = robot.place(sideOfBlock or sides.bottom) end if success then return true end end return false end function inventory.isLocalFull() -- backwards cuz the later slots fill up last for i=robot.inventorySize(),1,-1 do local stack = ic.getStackInInternalSlot(i) if stack == nil then return false end end return true end function inventory.toolIsBroken() local d = robot.durability() d = util.trunc(d or 0, 2) return d <= 0 end function inventory.stackIsItem(stack, nameOrPattern) return stack ~= nil and (stack.name == nameOrPattern or string.match(stack.name, nameOrPattern)) end function inventory.pickUpFreshTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local size = ic.getInventorySize(sideOfRobot) if size == nil then return false end local count = 0 for i=1,size do local stack = ic.getStackInSlot(sideOfRobot, i) -- is this the tool we want and fully repaired? if inventory.stackIsItem(stack, toolName) and stack.damage == 0 then -- found one, get it! robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that if not ic.suckFromSlot(sideOfRobot, i) then return false end count = count + 1 end end return true, count end function inventory.dropBrokenTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local brokenToolsCount = 0 for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if inventory.stackIsItem(stack, toolName) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 -- drop it robot.select(i) local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or (sideOfRobot == sides.front and robot.drop(1)) if not result then return false, brokenToolsCount end end end end -- finally we need to see if the tool we are holding is broken robot.select(1) ic.equip() local stack = ic.getStackInInternalSlot(1) if inventory.stackIsItem(stack, toolName) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 if not robot.dropDown(1) then ic.equip() return false, brokenToolsCount end end end ic.equip() return true, brokenToolsCount end function inventory.equipFreshTool(itemName) if itemName == nil then -- use the currently selected tool as the pattern. -- first we must see what tool it is we currently have -- swap it with slot 1 robot.select(1) ic.equip() local currentTool = ic.getStackInInternalSlot() -- equip it back since whatever was in slot 1 might be important ic.equip() if currentTool == nil then -- no current tool, sorry return false end itemName = currentTool.name end for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if itemName == "!empty" then if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then -- found an empty slot or at least something that doesn't use durability robot.select(i) ic.equip() return true end elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then robot.select(i) ic.equip() -- found one but we need to check if it's got durability if not inventory.toolIsBroken() then return true end -- not durable enough, so put it back and keep looking ic.equip() end end return false end return inventory
refactor, and reverse bug with detecting fresh tools
refactor, and reverse bug with detecting fresh tools
Lua
apache-2.0
InfinitiesLoop/oclib
736b6859f7d4e76fcd59e9da6f934c74c9fd3990
hermes.lua
hermes.lua
-- -- hermes.lua -- -- -- Folder bindings for imap collector. -- -- -- Space 0: Folder Bindings and IMAP Collector State. -- Tuple: { coll_id (NUM), rmt_fld_id (STR), fld_id (NUM), uid_validity (NUM), up_uid (NUM), down_uid (NUM), up_date (NUM), down_date (NUM), modseq (STR), state (STR) } -- Index 0: TREE { coll_id, rmt_fld_id } -- function hermes_get(coll_id) coll_id = box.unpack('i', coll_id) return box.select_limit(0, 0, 0, 1000000, coll_id) end function hermes_drop(coll_id) coll_id = box.unpack('i', coll_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do box.delete(0, coll_id, tuple[1]) end end function hermes_rebase(coll_id) coll_id = box.unpack('i', coll_id) for tuple in box.space[0].index[0]:iterator(box.index.EQ, coll_id) do box.update(0, { coll_id, tuple[1] }, "=p", 2, -1) end end function hermes_update(coll_id, rmt_fld_id, fld_id, uid_validity, up_uid, down_uid, up_date, down_date) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) uid_validity = box.unpack('i', uid_validity) up_uid = box.unpack('i', up_uid) down_uid = box.unpack('i', down_uid) up_date = box.unpack('i', up_date) down_date = box.unpack('i', down_date) box.replace(0, coll_id, rmt_fld_id, fld_id, uid_validity, up_uid, down_uid, up_date, down_date) end function hermes_drop_by_rmt_fld(coll_id, rmt_fld_id) coll_id = box.unpack('i', coll_id) box.delete(0, coll_id, rmt_fld_id) end function hermes_drop_by_fld(coll_id, fld_id) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do if box.unpack('i', tuple[2]) == fld_id then box.delete(0, coll_id, tuple[1]) end end end function hermes_update_up_uid(coll_id, rmt_fld_id, up_uid, up_date) coll_id = box.unpack('i', coll_id) up_uid = box.unpack('i', up_uid) up_date = box.unpack('i', up_date) local t = box.update(0, { coll_id, rmt_fld_id }, "=p=p", 4, up_uid, 6, up_date) if t ~= nil then return 1 else return 0 end end function hermes_update_rmt_fld(coll_id, fld_id, new_rmt_fld_id) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do if box.unpack('i', tuple[2]) == fld_id then box.update(0, { coll_id, tuple[1] }, "=p", 1, new_rmt_fld_id) return 1 end end return 0 end function hermes_update_modseq(coll_id, rmt_fld_id, modseq) coll_id = box.unpack('i', coll_id) local t = box.update(0, { coll_id, rmt_fld_id }, "=p", 8, modseq) if t ~= nil then return 1 else return 0 end end function hermes_update_state(coll_id, rmt_fld_id, state) coll_id = box.unpack('i', coll_id) local status, t = pcall(box.update, 0, { coll_id, rmt_fld_id }, "=p", 9, state) if not status then t = box.update(0, { coll_id, rmt_fld_id }, "=p=p", 8, "", 9, state) end if t ~= nil then return 1 else return 0 end end
-- -- hermes.lua -- -- -- Folder bindings for imap collector. -- -- -- Space 0: Folder Bindings and IMAP Collector State. -- Tuple: { coll_id (NUM), rmt_fld_id (STR), fld_id (NUM), uid_validity (NUM), up_uid (NUM), down_uid (NUM), up_date (NUM), down_date (NUM), modseq (STR), state (STR) } -- Index 0: TREE { coll_id, rmt_fld_id } -- function hermes_get(coll_id) coll_id = box.unpack('i', coll_id) return box.select_limit(0, 0, 0, 1000000, coll_id) end function hermes_drop(coll_id) coll_id = box.unpack('i', coll_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do box.delete(0, coll_id, tuple[1]) end end function hermes_rebase(coll_id) coll_id = box.unpack('i', coll_id) for tuple in box.space[0].index[0]:iterator(box.index.EQ, coll_id) do box.update(0, { coll_id, tuple[1] }, "=p", 2, -1) end end function hermes_update(coll_id, rmt_fld_id, fld_id, uid_validity, up_uid, down_uid, up_date, down_date) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) uid_validity = box.unpack('i', uid_validity) up_uid = box.unpack('i', up_uid) down_uid = box.unpack('i', down_uid) up_date = box.unpack('i', up_date) down_date = box.unpack('i', down_date) local status, _ = pcall(box.update, 0, { coll_id, rmt_fld_id }, "=p=p=p=p=p=p", 2, fld_id, 3, uid_validity, 4, up_uid, 5, down_uid, 6, up_date, 7, down_date) if not status then box.replace(0, coll_id, rmt_fld_id, fld_id, uid_validity, up_uid, down_uid, up_date, down_date) end end function hermes_drop_by_rmt_fld(coll_id, rmt_fld_id) coll_id = box.unpack('i', coll_id) box.delete(0, coll_id, rmt_fld_id) end function hermes_drop_by_fld(coll_id, fld_id) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do if box.unpack('i', tuple[2]) == fld_id then box.delete(0, coll_id, tuple[1]) end end end function hermes_update_up_uid(coll_id, rmt_fld_id, up_uid, up_date) coll_id = box.unpack('i', coll_id) up_uid = box.unpack('i', up_uid) up_date = box.unpack('i', up_date) local t = box.update(0, { coll_id, rmt_fld_id }, "=p=p", 4, up_uid, 6, up_date) if t ~= nil then return 1 else return 0 end end function hermes_update_rmt_fld(coll_id, fld_id, new_rmt_fld_id) coll_id = box.unpack('i', coll_id) fld_id = box.unpack('i', fld_id) local tuples = { box.select_limit(0, 0, 0, 1000000, coll_id) } for _, tuple in pairs(tuples) do if box.unpack('i', tuple[2]) == fld_id then box.update(0, { coll_id, tuple[1] }, "=p", 1, new_rmt_fld_id) return 1 end end return 0 end function hermes_update_modseq(coll_id, rmt_fld_id, modseq) coll_id = box.unpack('i', coll_id) local t = box.update(0, { coll_id, rmt_fld_id }, "=p", 8, modseq) if t ~= nil then return 1 else return 0 end end function hermes_update_state(coll_id, rmt_fld_id, state) coll_id = box.unpack('i', coll_id) local status, t = pcall(box.update, 0, { coll_id, rmt_fld_id }, "=p", 9, state) if not status then t = box.update(0, { coll_id, rmt_fld_id }, "=p=p", 8, "", 9, state) end if t ~= nil then return 1 else return 0 end end
hermes.lua: fix bug in hermes_update
hermes.lua: fix bug in hermes_update hermes_update clears state and modseq fields. this is a bug. fixed.
Lua
bsd-2-clause
BHYCHIK/tntlua,grechkin-pogrebnyakov/tntlua,derElektrobesen/tntlua,spectrec/tntlua,mailru/tntlua
0d2e7e0b03719bdffcf2fd1cee18cdbeae3251e0
MMOCoreORB/bin/scripts/screenplays/poi/dathomir_nightsister_labor_camp.lua
MMOCoreORB/bin/scripts/screenplays/poi/dathomir_nightsister_labor_camp.lua
NightSisterLaborCampScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "NightSisterLaborCampScreenPlay", lootContainers = { 8715535, 8715534, 164440 }, lootLevel = 38, lootGroups = { { groups = { {group = "color_crystals", chance = 3500000}, {group = "junk", chance = 3500000}, {group = "rifles", chance = 1000000}, {group = "pistols", chance = 1000000}, {group = "clothing_attachments", chance = 500000}, {group = "armor_attachments", chance = 500000} }, lootChance = 8000000 } }, lootContainerRespawn = 1800 -- 30 minutes } registerScreenPlay("NightSisterLaborCampScreenPlay", true) function NightSisterLaborCampScreenPlay:start() if (isZoneEnabled("dathomir")) then self:spawnMobiles() self:initializeLootContainers() end end function NightSisterLaborCampScreenPlay:spawnMobiles() spawnMobile("dathomir", "nightsister_initiate",900,2544,123.0,-1671,-169,0) spawnMobile("dathomir", "nightsister_outcast",900,2553,123,-1680,-54,0) spawnMobile("dathomir", "nightsister_ranger",900,2543,110.8,-1610,51,0) spawnMobile("dathomir", "escaped_nightsister_slave",900,2540,126.3,-1604,-24,0) spawnMobile("dathomir", "nightsister_sentry",900,2497,129.4,-1616,178,0) spawnMobile("dathomir", "nightsister_sentry",900,2469,126.7,-1670,-110,0) spawnMobile("dathomir", "nightsister_sentry",900,2500,117.7,-1745,6,0) spawnMobile("dathomir", "nightsister_sentry",900,2619,130.4,-1614,-100,0) spawnMobile("dathomir", "escaped_nightsister_slave",900,2450,110.0,-1600,80,0) spawnMobile("dathomir", "nightsister_sentry",900,26.2,-39.1,-39.0,5,8575576) spawnMobile("dathomir", "nightsister_sentry",900,22.2,-39.3,-40.3,7,8575576) spawnMobile("dathomir", "nightsister_sentry",900,21.1,-41.4,-70.1,2,8575576) spawnMobile("dathomir", "nightsister_sentry",900,23.3,-41.9,-70.4,7,8575576) spawnMobile("dathomir", "nightsister_sentry",900,40.9,-47.2,-36.9,177,8575576) spawnMobile("dathomir", "nightsister_sentry",900,45.6,-47.7,-37.0,176,8575576) spawnMobile("dathomir", "nightsister_sentry",900,48.4,-47.6,-70.9,-118,8575576) spawnMobile("dathomir", "nightsister_sentry",900,53.5,-47.5,-69.8,-32,8575576) spawnMobile("dathomir", "nightsister_ranger",900,48.0,-47.3,-11.4,133,8575576) spawnMobile("dathomir", "nightsister_ranger",900,82.6,-46.2,-118.0,20,8575579) spawnMobile("dathomir", "nightsister_ranger",900,96.4,-46.7,-114.9,-68,8575579) spawnMobile("dathomir", "nightsister_ranger",900,91.6,-46.2,-100.3,-166,8575579) spawnMobile("dathomir", "nightsister_spell_weaver",900,83.3,-46.2,-137.8,70,8575585) spawnMobile("dathomir", "nightsister_spell_weaver",900,81.5,-46.4,-147.9,7,8575585) spawnMobile("dathomir", "nightsister_elder",3600,72.1,-45.7,-142.8,86,8575585) spawnMobile("dathomir", "nightsister_initiate",900,90.2,-61.2,-7.9,-153,8575577) spawnMobile("dathomir", "nightsister_initiate",900,92.1,-61.7,-164,2,8575577) spawnMobile("dathomir", "nightsister_slave",900,83.6,-65.3,-28.6,7,8575577) spawnMobile("dathomir", "nightsister_slave",900,84.9,-64.0,-24.5,2,8575577) spawnMobile("dathomir", "nightsister_slave",900,86.2,-65.0,-28.9,2,8575577) spawnMobile("dathomir", "nightsister_sentry",900,94.6,-67.7,-38.1,7,8575577) spawnMobile("dathomir", "nightsister_sentry",900,95.0,-66.3,-34.5,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,71.8,-68.0,-36.0,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,70.5,-69.3,-39.4,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,68.6,-76.7,-69.1,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,63.8,-75.7,-69.0,2,8575578) spawnMobile("dathomir", "nightsister_rancor_tamer",900,91.0,-76.4,-86.9,2,8575578) spawnMobile("dathomir", "nightsister_rancor_tamer",900,95.6,-76.2,-85.0,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,66.0,-76.8,-87.6,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,63.2,-76.5,-65.2,2,8575578) spawnMobile("dathomir", "nightsister_slave",900,61.2,-69.1,-125.9,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,57.7,-68.6,-126.4,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,59.0,-69.4,-124.4,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,59.7,-68.6,-127.1,2,8575580) spawnMobile("dathomir", "nightsister_stalker",900,96.7,-66.4,-106.0,-168,8575579) spawnMobile("dathomir", "nightsister_stalker",900,92.9,-66.6,-105.0,178,8575579) spawnMobile("dathomir", "nightsister_sentinel",900,114.4,-66.9,-86.0,-143,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,110.8,-66.8,-85.8,135,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,112.9,-67.2,-87.6,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,126.6,-66.6,-110.8,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,126.2,-66.7,-107.6,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,124.3,-66.8,-109.3,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,125.3,-66.8,-107.3,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,135.4,-66.4,-119.9,-155,8575582) spawnMobile("dathomir", "nightsister_slave",900,134.8,-66.2,-117.7,-125,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,156.0,-65.4,-129.4,2,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,155.9,-65.4,-126.0,2,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,154.2,-65.7,-128.5,2,8575582) spawnMobile("dathomir", "nightsister_stalker",900,135.1,-66.9,-93.4,-127,8575582) spawnMobile("dathomir", "nightsister_stalker",900,137.4,-67.2,-95.3,112,8575582) spawnMobile("dathomir", "nightsister_spell_weaver",900,183.3,-66.0,-95.5,-103,8575583) spawnMobile("dathomir", "nightsister_spell_weaver",900,183.9,-65.7,-105.8,2,8575583) spawnMobile("dathomir", "nightsister_protector",900,192.5,-66.7,-99.4,-90,8575583) spawnMobile("dathomir", "nightsister_protector",900,52.2,-67.9,-41.0,77,8575576) spawnMobile("dathomir", "nightsister_stalker",900,129.5,-66.3,-114.0,55,8575582) end
NightSisterLaborCampScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "NightSisterLaborCampScreenPlay", lootContainers = { 8715535, 8715534, 164440 }, lootLevel = 38, lootGroups = { { groups = { {group = "color_crystals", chance = 3500000}, {group = "junk", chance = 3500000}, {group = "rifles", chance = 1000000}, {group = "pistols", chance = 1000000}, {group = "clothing_attachments", chance = 500000}, {group = "armor_attachments", chance = 500000} }, lootChance = 8000000 } }, lootContainerRespawn = 1800 -- 30 minutes } registerScreenPlay("NightSisterLaborCampScreenPlay", true) function NightSisterLaborCampScreenPlay:start() if (isZoneEnabled("dathomir")) then self:spawnMobiles() self:initializeLootContainers() end end function NightSisterLaborCampScreenPlay:spawnMobiles() spawnMobile("dathomir", "nightsister_initiate",900,2544,123.0,-1671,-169,0) spawnMobile("dathomir", "nightsister_outcast",900,2553,123,-1680,-54,0) spawnMobile("dathomir", "nightsister_ranger",900,2543,110.8,-1610,51,0) spawnMobile("dathomir", "escaped_nightsister_slave",900,2540,126.3,-1604,-24,0) spawnMobile("dathomir", "nightsister_sentry",900,2497,129.4,-1616,178,0) spawnMobile("dathomir", "nightsister_sentry",900,2469,126.7,-1670,-110,0) spawnMobile("dathomir", "nightsister_sentry",900,2500,117.7,-1745,6,0) spawnMobile("dathomir", "nightsister_sentry",900,2619,130.4,-1614,-100,0) spawnMobile("dathomir", "escaped_nightsister_slave",900,2450,110.0,-1600,80,0) spawnMobile("dathomir", "nightsister_sentry",900,26.2,-39.1,-39.0,5,8575576) spawnMobile("dathomir", "nightsister_sentry",900,22.2,-39.3,-40.3,7,8575576) spawnMobile("dathomir", "nightsister_sentry",900,21.1,-41.4,-70.1,2,8575576) spawnMobile("dathomir", "nightsister_sentry",900,23.3,-41.9,-70.4,7,8575576) spawnMobile("dathomir", "nightsister_sentry",900,40.9,-47.2,-36.9,177,8575576) spawnMobile("dathomir", "nightsister_sentry",900,45.6,-47.7,-37.0,176,8575576) spawnMobile("dathomir", "nightsister_sentry",900,48.4,-47.6,-70.9,-118,8575576) spawnMobile("dathomir", "nightsister_sentry",900,53.5,-47.5,-69.8,-32,8575576) spawnMobile("dathomir", "nightsister_ranger",900,48.0,-47.3,-11.4,133,8575576) spawnMobile("dathomir", "nightsister_ranger",900,82.6,-46.2,-118.0,20,8575579) spawnMobile("dathomir", "nightsister_ranger",900,96.4,-46.7,-114.9,-68,8575579) spawnMobile("dathomir", "nightsister_ranger",900,91.6,-46.2,-100.3,-166,8575579) spawnMobile("dathomir", "nightsister_spell_weaver",900,83.3,-46.2,-137.8,70,8575585) spawnMobile("dathomir", "nightsister_spell_weaver",900,81.5,-46.4,-147.9,7,8575585) spawnMobile("dathomir", "nightsister_elder",3600,72.1,-45.7,-142.8,86,8575585) spawnMobile("dathomir", "nightsister_initiate",900,90.2,-61.2,-7.9,-153,8575577) spawnMobile("dathomir", "nightsister_slave",900,83.6,-65.3,-28.6,7,8575577) spawnMobile("dathomir", "nightsister_slave",900,84.9,-64.0,-24.5,2,8575577) spawnMobile("dathomir", "nightsister_slave",900,86.2,-65.0,-28.9,2,8575577) spawnMobile("dathomir", "nightsister_sentry",900,94.6,-67.7,-38.1,7,8575577) spawnMobile("dathomir", "nightsister_sentry",900,95.0,-66.3,-34.5,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,71.8,-68.0,-36.0,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,70.5,-69.3,-39.4,2,8575577) spawnMobile("dathomir", "nightsister_initiate",900,85.1,-76.2,-59.7,0,8575578) spawnMobile("dathomir", "nightsister_initiate",900,68.6,-76.7,-69.1,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,63.8,-75.7,-69.0,2,8575578) spawnMobile("dathomir", "nightsister_rancor_tamer",900,91.0,-76.4,-86.9,2,8575578) spawnMobile("dathomir", "nightsister_rancor_tamer",900,95.6,-76.2,-85.0,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,66.0,-76.8,-87.6,2,8575578) spawnMobile("dathomir", "nightsister_initiate",900,63.2,-75.5,-65.1,12,8575578) spawnMobile("dathomir", "nightsister_slave",900,61.2,-69.1,-125.9,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,57.7,-68.6,-126.4,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,59.0,-69.4,-124.4,2,8575580) spawnMobile("dathomir", "nightsister_slave",900,59.7,-68.6,-127.1,2,8575580) spawnMobile("dathomir", "nightsister_stalker",900,96.7,-66.4,-106.0,-168,8575579) spawnMobile("dathomir", "nightsister_stalker",900,92.9,-66.6,-105.0,178,8575579) spawnMobile("dathomir", "nightsister_sentinel",900,114.4,-66.9,-86.0,-143,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,110.8,-66.8,-85.8,135,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,112.9,-67.2,-87.6,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,126.6,-66.6,-110.8,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,126.2,-66.7,-107.6,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,124.3,-66.8,-109.3,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,125.3,-66.8,-107.3,2,8575582) spawnMobile("dathomir", "nightsister_slave",900,135.4,-66.4,-119.9,-155,8575582) spawnMobile("dathomir", "nightsister_slave",900,134.8,-66.2,-117.7,-125,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,156.0,-65.4,-129.4,2,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,155.9,-65.4,-126.0,2,8575582) spawnMobile("dathomir", "nightsister_sentinel",900,154.2,-65.7,-128.5,2,8575582) spawnMobile("dathomir", "nightsister_stalker",900,135.1,-66.9,-93.4,-127,8575582) spawnMobile("dathomir", "nightsister_stalker",900,137.4,-67.2,-95.3,112,8575582) spawnMobile("dathomir", "nightsister_spell_weaver",900,183.3,-66.0,-95.5,-103,8575583) spawnMobile("dathomir", "nightsister_spell_weaver",900,183.9,-65.7,-105.8,2,8575583) spawnMobile("dathomir", "nightsister_protector",900,192.5,-66.7,-99.4,-90,8575583) spawnMobile("dathomir", "nightsister_protector",900,52.2,-67.9,-41.0,77,8575576) spawnMobile("dathomir", "nightsister_stalker",900,129.5,-66.3,-114.0,55,8575582) end
[Fixed] A few NS spawns. Mantis #3849
[Fixed] A few NS spawns. Mantis #3849 Change-Id: I94e627de55a4e032882ad497c2282492f0dfa668
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
50042c0962150ee51f1a9310dd6d5c2ede47a708
GTWmechanic/mechanic-s.lua
GTWmechanic/mechanic-s.lua
--[[ ******************************************************************************** Project: GTW RPG [2.0.4] Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: 2.0.4 Status: Stable release ******************************************************************************** ]]-- local default_money = 428 -- Global definition based on what mechanics earn IRL/year -- divided by 12 and then 31 as in days multiplied by 4 --[[ Pay for repair and refuel ]]-- function pay_repair(mech, owner) local pacc = getPlayerAccount(mech) local repaired_cars = getAccountData(pacc, "acorp_stats_repaired_cars") or 0 if isElement(owner) then takePlayerMoney(owner, default_money*3) end givePlayerMoney(mech, (default_money*2)+repaired_cars) end function pay_refuel(mech, owner) local pacc = getPlayerAccount(mech) local repaired_cars = getAccountData(pacc, "acorp_stats_repaired_cars") or 0 if owner and isElement(owner) then takePlayerMoney(owner, default_money) end givePlayerMoney(mech, (default_money/2)+repaired_cars) end --[[ Repair vehicle as mechanic ]]-- function repair_veh(veh, repairTime) if not veh or not isElement(veh) then outPutTopbarMessage("No vehicle found", client, 255, 0, 0) return end local acc = getElementData(veh, "owner") if not acc then return end local owner = getAccountPlayer(getAccount(acc)) if not owner then outPutTopbarMessage("The owner of this vehicle is currently offline!", client, 255, 0, 0) return end -- Freeze elements during repair setElementFrozen(veh, true) setElementFrozen(client, true) setPedAnimation(client, "GRAFFITI", "spraycan_fire", -1, true, false) showCursor(client, true) outPutTopbarMessage("Reparing vehicle...", client, 0, 255, 0) outPutTopbarMessage("Your vehicle is repaired...", owner, 0, 255, 0) -- Reset after repair setTimer(fixVehicle, math.floor(repairTime), 1, veh) setTimer(showCursor, math.floor(repairTime), 1, client, false) setTimer(setElementFrozen, math.floor(repairTime), 1, veh, false) setTimer(setElementFrozen, math.floor(repairTime), 1, client, false) setTimer(outPutTopbarMessage, math.floor(repairTime), 1, "Vehicle was sucsessfully repaired!", client, 0, 255, 0) setTimer(outPutTopbarMessage, math.floor(repairTime), 1, "Your vehicle was repaired by: "..getPlayerName(client), owner, 0, 255, 0) setTimer(pay_repair, math.floor(repairTime), 1, client, owner) setTimer(setPedAnimation, math.floor(repairTime), 1, client, nil, nil) -- Increase stats by 1 local playeraccount = getPlayerAccount(client) local repaired_cars = getAccountData(playeraccount, "acorp_stats_repaired_cars") or 0 setAccountData(playeraccount, "acorp_stats_repaired_cars", repaired_cars + 1) end addEvent("GTWmechanic.repair", true) addEventHandler("GTWmechanic.repair", root, repair_veh) --[[ Refule as mechanic ]]-- function refuel_veh(veh, refuelTime) if not veh or not isElement(veh) then outPutTopbarMessage("No vehicle found", client, 255, 0, 0) return end local acc = getElementData(veh, "owner") if not acc then return end local owner = getAccountPlayer(getAccount(acc)) if not owner then outPutTopbarMessage("The owner of this vehicle is currently offline!", client, 255, 0, 0) return end -- Freeze elements during repair setElementFrozen(veh, true) setElementFrozen(client, true) setPedAnimation(client, "GRAFFITI", "spraycan_fire", -1, true, false) showCursor(client, true) outPutTopbarMessage("Refueling vehicle...", client, 0, 255, 0) outPutTopbarMessage("Your vehicle is being refuled...", owner, 0, 255, 0) -- Reset after repair setTimer(showCursor, math.floor(refuelTime), 1, client, false) setTimer(setElementFrozen, math.floor(refuelTime), 1, veh, false) setTimer(setElementFrozen, math.floor(refuelTime), 1, client, false) setTimer(outPutTopbarMessage, math.floor(refuelTime), 1, "Vehicle was sucsessfully refuled!", client, 0, 255, 0) setTimer(outPutTopbarMessage, math.floor(refuelTime), 1, "Your vehicle was refuled by: "..getPlayerName(client), owner, 0, 255, 0) setTimer(setPedAnimation, math.floor(refuelTime), 1, client, nil, nil) setTimer(pay_refuel, math.floor(refuelTime), 1, client, owner) setTimer(setElementData, math.floor(refuelTime), 1, veh, "vehicleFuel", 100) end addEvent("GTWmechanic.refuel", true) addEventHandler("GTWmechanic.refuel", root, refuel_veh) --[[ Fix and repair as staff ]]-- function staff_repair(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end outPutTopbarMessage("Vehicle was sucsessfully repaired!", client, 0, 255, 0) setElementData(veh, "vehicleFuel", 100) fixVehicle(veh) end addEvent("GTWmechanic.staff.repair", true) addEventHandler("GTWmechanic.staff.repair", root, staff_repair) --[[ Enter any vehicle as staff ]]-- function staff_enter(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end warpPedIntoVehicle(client, veh) end addEvent("GTWmechanic.staff.enter", true) addEventHandler("GTWmechanic.staff.enter", root, staff_enter) --[[ Staff destroy vehicle ]]-- function staff_destroy(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end if getElementData(veh,"owner") then outPutTopbarMessage("Vehicle was sucsessfully removed!", client, 0, 255, 0) outputServerLog("VEH_ADMIN: Vehicle was removed at: "..getZoneName(getElementPosition(veh)).. ", by: "..getPlayerName(client).." owner was: "..getElementData(veh,"owner")) end -- Clean up if owned vehicle bought in shop triggerEvent("GTWvehicleshop.onPlayerVehicleDestroy", root, veh, true) end addEvent("GTWmechanic.destroy", true) addEventHandler("GTWmechanic.destroy", root, staff_destroy) function outPutTopbarMessage(message, thePlayer, r, g, b) exports.GTWtopbar:dm(message, thePlayer, r, g, b) end
--[[ ******************************************************************************** Project: GTW RPG [2.0.4] Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: 2.0.4 Status: Stable release ******************************************************************************** ]]-- local default_money = 428 -- Global definition based on what mechanics earn IRL/year -- divided by 12 and then 31 as in days multiplied by 4 --[[ Pay for repair and refuel ]]-- function pay_repair(mech, owner) local pacc = getPlayerAccount(mech) local repaired_cars = getAccountData(pacc, "acorp_stats_repaired_cars") or 0 if isElement(owner) then takePlayerMoney(owner, default_money*3) end givePlayerMoney(mech, (default_money*2)+repaired_cars) end function pay_refuel(mech, owner) local pacc = getPlayerAccount(mech) local repaired_cars = getAccountData(pacc, "acorp_stats_repaired_cars") or 0 if owner and isElement(owner) then takePlayerMoney(owner, default_money) end givePlayerMoney(mech, (default_money/2)+repaired_cars) end --[[ Repair vehicle as mechanic ]]-- function repair_veh(veh, repairTime) if not veh or not isElement(veh) then outPutTopbarMessage("No vehicle found", client, 255, 0, 0) return end local acc = getElementData(veh, "owner") if not acc then return end local owner = getAccountPlayer(getAccount(acc)) if not owner then outPutTopbarMessage("The owner of this vehicle is currently offline!", client, 255, 0, 0) return end -- Freeze elements during repair setElementFrozen(veh, true) setElementFrozen(client, true) setPedAnimation(client, "GRAFFITI", "spraycan_fire", -1, true, false) showCursor(client, true) outPutTopbarMessage("Reparing vehicle...", client, 0, 255, 0) outPutTopbarMessage("Your vehicle is repaired...", owner, 0, 255, 0) -- Reset after repair setTimer(fixVehicle, math.floor(repairTime), 1, veh) setTimer(showCursor, math.floor(repairTime), 1, client, false) setTimer(setElementFrozen, math.floor(repairTime), 1, veh, false) setTimer(setElementFrozen, math.floor(repairTime), 1, client, false) setTimer(outPutTopbarMessage, math.floor(repairTime), 1, "Vehicle was sucsessfully repaired!", client, 0, 255, 0) setTimer(outPutTopbarMessage, math.floor(repairTime), 1, "Your vehicle was repaired by: "..getPlayerName(client), owner, 0, 255, 0) setTimer(pay_repair, math.floor(repairTime), 1, client, owner) setTimer(setPedAnimation, math.floor(repairTime), 1, client, nil, nil) -- Increase stats by 1 (if not your own car, solution to abuse 2014-11-13) if owner == client then return end local playeraccount = getPlayerAccount(client) local repaired_cars = getAccountData(playeraccount, "acorp_stats_repaired_cars") or 0 setAccountData(playeraccount, "acorp_stats_repaired_cars", repaired_cars + 1) end addEvent("GTWmechanic.repair", true) addEventHandler("GTWmechanic.repair", root, repair_veh) --[[ Refule as mechanic ]]-- function refuel_veh(veh, refuelTime) if not veh or not isElement(veh) then outPutTopbarMessage("No vehicle found", client, 255, 0, 0) return end local acc = getElementData(veh, "owner") if not acc then return end local owner = getAccountPlayer(getAccount(acc)) if not owner then outPutTopbarMessage("The owner of this vehicle is currently offline!", client, 255, 0, 0) return end -- Freeze elements during repair setElementFrozen(veh, true) setElementFrozen(client, true) setPedAnimation(client, "GRAFFITI", "spraycan_fire", -1, true, false) showCursor(client, true) outPutTopbarMessage("Refueling vehicle...", client, 0, 255, 0) outPutTopbarMessage("Your vehicle is being refuled...", owner, 0, 255, 0) -- Reset after repair setTimer(showCursor, math.floor(refuelTime), 1, client, false) setTimer(setElementFrozen, math.floor(refuelTime), 1, veh, false) setTimer(setElementFrozen, math.floor(refuelTime), 1, client, false) setTimer(outPutTopbarMessage, math.floor(refuelTime), 1, "Vehicle was sucsessfully refuled!", client, 0, 255, 0) setTimer(outPutTopbarMessage, math.floor(refuelTime), 1, "Your vehicle was refuled by: "..getPlayerName(client), owner, 0, 255, 0) setTimer(setPedAnimation, math.floor(refuelTime), 1, client, nil, nil) setTimer(pay_refuel, math.floor(refuelTime), 1, client, owner) setTimer(setElementData, math.floor(refuelTime), 1, veh, "vehicleFuel", 100) end addEvent("GTWmechanic.refuel", true) addEventHandler("GTWmechanic.refuel", root, refuel_veh) --[[ Fix and repair as staff ]]-- function staff_repair(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end outPutTopbarMessage("Vehicle was sucsessfully repaired!", client, 0, 255, 0) setElementData(veh, "vehicleFuel", 100) fixVehicle(veh) end addEvent("GTWmechanic.staff.repair", true) addEventHandler("GTWmechanic.staff.repair", root, staff_repair) --[[ Enter any vehicle as staff ]]-- function staff_enter(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end warpPedIntoVehicle(client, veh) end addEvent("GTWmechanic.staff.enter", true) addEventHandler("GTWmechanic.staff.enter", root, staff_enter) --[[ Staff destroy vehicle ]]-- function staff_destroy(veh) local accName = getAccountName(getPlayerAccount(client)) if not (isObjectInACLGroup("user."..accName, aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName, aclGetGroup("Developer")) or isObjectInACLGroup("user."..accName, aclGetGroup("Moderator"))) then outPutTopbarMessage("You are not allowed to use this feature!", client, 255, 0, 0) return end if not veh or not isElement(veh) then return end if getElementData(veh,"owner") then outPutTopbarMessage("Vehicle was sucsessfully removed!", client, 0, 255, 0) outputServerLog("VEH_ADMIN: Vehicle was removed at: "..getZoneName(getElementPosition(veh)).. ", by: "..getPlayerName(client).." owner was: "..getElementData(veh,"owner")) end -- Clean up if owned vehicle bought in shop triggerEvent("GTWvehicleshop.onPlayerVehicleDestroy", root, veh, true) end addEvent("GTWmechanic.destroy", true) addEventHandler("GTWmechanic.destroy", root, staff_destroy) function outPutTopbarMessage(message, thePlayer, r, g, b) exports.GTWtopbar:dm(message, thePlayer, r, g, b) end
Bugfix
Bugfix Solution to people who damage their own cars to repair and gain stats.
Lua
bsd-2-clause
GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,SpRoXx/GTW-RPG
0ed51fbad791fbf43663997f18c33e7300af4d14
mod_auth_ldap/mod_auth_ldap.lua
mod_auth_ldap/mod_auth_ldap.lua
local new_sasl = require "util.sasl".new; local log = require "util.logger".init("auth_ldap"); local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)"); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local lualdap = require "lualdap"; local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:format(ldap_filter_escape(username)); })(); end local provider = {}; function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.password ~= password then ld:modify(dn, { '=', userPassword = password }); end return true end function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end module:provides("auth", provider);
local new_sasl = require "util.sasl".new; local log = require "util.logger".init("auth_ldap"); local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)"); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local lualdap = require "lualdap"; local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:format(ldap_filter_escape(username)); })(); end local provider = {}; function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end module:provides("auth", provider);
mod_auth_ldap: Fix set_password
mod_auth_ldap: Fix set_password
Lua
mit
LanceJenkinZA/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,prosody-modules/import,syntafin/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,either1/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,prosody-modules/import,mardraze/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,mmusial/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,prosody-modules/import,olax/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules
3f623f418017b939175e508817f567216c69bca8
mod_manifesto/mod_manifesto.lua
mod_manifesto/mod_manifesto.lua
-- mod_manifesto local timer = require "util.timer"; local jid_split = require "util.jid".split; local st = require "util.stanza"; local dm = require "util.datamanager"; local time = os.time; local hosts = prosody.hosts; local host = module.host; local host_session = hosts[host]; local incoming_s2s = prosody.incoming_s2s; local default_tpl = [[ Hello there. This is a brief system message to let you know about some upcoming changes to the $HOST service. Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts. The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services: $SERVICES Your affected contacts are: $CONTACTS What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT ]]; local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl); local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]); if not contact then error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0); end local contact_method = "Jabber/XMPP"; if select(2, contact:gsub("^mailto:", "")) > 0 then contact_method = "email"; end local notified; module:hook("resource-bind", function (event) local session = event.session; local now = time(); local last_notify = notified[session.username] or 0; if last_notify > ( now - 86400 * 7 ) then return end timer.add_task(15, function () local bad_contacts, bad_hosts = {}, {}; for contact_jid, item in pairs(session.roster or {}) do local _, contact_host = jid_split(contact_jid); local bad = false; local remote_host_session = host_session.s2sout[contact_host]; if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to if not remote_host_session.secure then bad = true; end end for session in pairs(incoming_s2s) do if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then if not session.secure then bad = true; end end end if bad then local contact_name = item.name; if contact_name then table.insert(bad_contacts, contact_name.." <"..contact_jid..">"); else table.insert(bad_contacts, contact_jid); end if not bad_hosts[contact_host] then bad_hosts[contact_host] = true; table.insert(bad_hosts, contact_host); end end end if #bad_contacts > 0 then local vars = { HOST = host; CONTACTS = " "..table.concat(bad_contacts, "\n "); SERVICES = " "..table.concat(bad_hosts, "\n "); CONTACTVIA = contact_method, CONTACT = contact; }; session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars))); end notified[session.username] = now; end); end); function module.load() notified = dm.load(nil, host, module.name) or {}; end function module.save() dm.store(nil, host, module.name, notified); return { notified = notified }; end function module.restore(data) notified = data.notified; end function module.unload() dm.store(nil, host, module.name, notified); end function module.uninstall() dm.store(nil, host, module.name, nil); end
-- mod_manifesto local timer = require "util.timer"; local jid_split = require "util.jid".split; local st = require "util.stanza"; local dm = require "util.datamanager"; local time = os.time; local hosts = prosody.hosts; local host = module.host; local host_session = hosts[host]; local incoming_s2s = prosody.incoming_s2s; local default_tpl = [[ Hello there. This is a brief system message to let you know about some upcoming changes to the $HOST service. Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts. The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services: $SERVICES Your affected contacts are: $CONTACTS What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT ]]; local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl); local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]); if not contact then error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0); end local contact_method = "Jabber/XMPP"; if select(2, contact:gsub("^mailto:", "")) > 0 then contact_method = "email"; end local notified; module:hook("resource-bind", function (event) local session = event.session; local now = time(); local last_notify = notified[session.username] or 0; if last_notify > ( now - 86400 * 7 ) then return end timer.add_task(15, function () if session.type ~= "c2s" then return end -- user quit already local bad_contacts, bad_hosts = {}, {}; for contact_jid, item in pairs(session.roster or {}) do local _, contact_host = jid_split(contact_jid); local bad = false; local remote_host_session = host_session.s2sout[contact_host]; if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to if not remote_host_session.secure then bad = true; end end for session in pairs(incoming_s2s) do if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then if not session.secure then bad = true; end end end if bad then local contact_name = item.name; if contact_name then table.insert(bad_contacts, contact_name.." <"..contact_jid..">"); else table.insert(bad_contacts, contact_jid); end if not bad_hosts[contact_host] then bad_hosts[contact_host] = true; table.insert(bad_hosts, contact_host); end end end if #bad_contacts > 0 then local vars = { HOST = host; CONTACTS = " "..table.concat(bad_contacts, "\n "); SERVICES = " "..table.concat(bad_hosts, "\n "); CONTACTVIA = contact_method, CONTACT = contact; }; session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars))); end notified[session.username] = now; end); end); function module.load() notified = dm.load(nil, host, module.name) or {}; end function module.save() dm.store(nil, host, module.name, notified); return { notified = notified }; end function module.restore(data) notified = data.notified; end function module.unload() dm.store(nil, host, module.name, notified); end function module.uninstall() dm.store(nil, host, module.name, nil); end
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
Lua
mit
prosody-modules/import,syntafin/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,softer/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,jkprg/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,Craige/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules
7eb52890a7dc8539de10c09899e1a2a122764662
turbo.lua
turbo.lua
--- Turbo.lua Asynchronous event based Lua Web Framework. -- It is different from all the other Lua HTTP servers out there in that it's -- modern, fresh, object oriented and easy to modify. -- It is written in pure Lua, there are no Lua C modules instead it uses the -- LuaJIT FFI to do socket and event handling. Users of the Tornado web -- server will recognize the API offered pretty quick. -- -- If you do not know Lua then do not fear as its probably one of the easiest -- languages to learn if you know C, Python or Javascript from before. -- -- Turbo.lua is non-blocking and a features a extremely fast light weight web -- server. The framework is good for REST APIs, traditional HTTP requests and -- open connections like Websockets requires beacause of its combination of -- the raw power of LuaJIT and its event driven nature. -- -- What sets Turbo.lua apart from the other evented driven servers out there, -- is that it is the fastest, most scalable and has the smallest footprint of -- them all. This is thanks to the excellent work done on LuaJIT. -- -- Its main features and design principles are: -- -- * Simple and intuitive API (much like Tornado) -- -- * Good documentation -- -- * No dependencies, except for LuaJIT the Just-In-Time compiler for Lua. -- -- * Event driven, asynchronous and threadless design -- -- * Extremely fast with LuaJIT -- -- * Written completely in pure Lua -- -- * Linux Epoll support -- -- * Small footprint -- -- Copyright John Abrahamsen 2011, 2012, 2013 -- -- 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 turbo = {} -- turbo main namespace. -- The Turbo Web version is of the form A.B.C, where A is the major version, -- B is the minor version, and C is the micro version. If the micro version -- is zero, it’s omitted from the version string. -- When a new release only fixes bugs and doesn’t add new features or -- functionality, the micro version is incremented. When new features are -- added in a backwards compatible way, the minor version is incremented and -- the micro version is set to zero. When there are backwards incompatible -- changes, the major version is incremented and others are set to zero. turbo.MAJOR_VERSION = 1 turbo.MINOR_VERSION = 0 turbo.MICRO_VERSION = 0 -- A 3-byte hexadecimal representation of the version, e.g. 0x010201 for -- version 1.2.1 and 0x010300 for version 1.3. turbo.VERSION_HEX = 0x010000 if turbo.MICRO_VERSION then turbo.VERSION = string.format("%d.%d.%d", turbo.MAJOR_VERSION, turbo.MINOR_VERSION, turbo.MICRO_VERSION) else turbo.VERSION = string.format("%d.%d", turbo.MAJOR_VERSION, turbo.MINOR_VERSION) end turbo.log = require "turbo.log" turbo.ioloop = require "turbo.ioloop" turbo.escape = require "turbo.escape" turbo.httputil = require "turbo.httputil" turbo.tcpserver = require "turbo.tcpserver" turbo.httpserver = require "turbo.httpserver" turbo.iostream = require "turbo.iostream" turbo.crypto = require "turbo.crypto" turbo.async = require "turbo.async" turbo.web = require "turbo.web" turbo.util = require "turbo.util" turbo.coctx = require "turbo.coctx" turbo.websocket = require "turbo.websocket" turbo.signal = require "turbo.signal" turbo.socket = require "turbo.socket_ffi" turbo.sockutil = require "turbo.sockutil" turbo.hash = require "turbo.hash" turbo.syscall = require "turbo.syscall" turbo.inotify = require "turbo.inotify" turbo.fs = require "turbo.fs" turbo.structs = {} turbo.structs.deque = require "turbo.structs.deque" turbo.structs.buffer = require "turbo.structs.buffer" return turbo
--- Turbo.lua Asynchronous event based Lua Web Framework. -- It is different from all the other Lua HTTP servers out there in that it's -- modern, fresh, object oriented and easy to modify. -- It is written in pure Lua, there are no Lua C modules instead it uses the -- LuaJIT FFI to do socket and event handling. Users of the Tornado web -- server will recognize the API offered pretty quick. -- -- If you do not know Lua then do not fear as its probably one of the easiest -- languages to learn if you know C, Python or Javascript from before. -- -- Turbo.lua is non-blocking and a features a extremely fast light weight web -- server. The framework is good for REST APIs, traditional HTTP requests and -- open connections like Websockets requires beacause of its combination of -- the raw power of LuaJIT and its event driven nature. -- -- What sets Turbo.lua apart from the other evented driven servers out there, -- is that it is the fastest, most scalable and has the smallest footprint of -- them all. This is thanks to the excellent work done on LuaJIT. -- -- Its main features and design principles are: -- -- * Simple and intuitive API (much like Tornado) -- -- * Good documentation -- -- * No dependencies, except for LuaJIT the Just-In-Time compiler for Lua. -- -- * Event driven, asynchronous and threadless design -- -- * Extremely fast with LuaJIT -- -- * Written completely in pure Lua -- -- * Linux Epoll support -- -- * Small footprint -- -- Copyright John Abrahamsen 2011, 2012, 2013 -- -- 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 turbo = {} -- turbo main namespace. -- The Turbo Web version is of the form A.B.C, where A is the major version, -- B is the minor version, and C is the micro version. If the micro version -- is zero, it’s omitted from the version string. -- When a new release only fixes bugs and doesn’t add new features or -- functionality, the micro version is incremented. When new features are -- added in a backwards compatible way, the minor version is incremented and -- the micro version is set to zero. When there are backwards incompatible -- changes, the major version is incremented and others are set to zero. turbo.MAJOR_VERSION = 1 turbo.MINOR_VERSION = 0 turbo.MICRO_VERSION = 0 -- A 3-byte hexadecimal representation of the version, e.g. 0x010201 for -- version 1.2.1 and 0x010300 for version 1.3. turbo.VERSION_HEX = 0x010000 if turbo.MICRO_VERSION then turbo.VERSION = string.format("%d.%d.%d", turbo.MAJOR_VERSION, turbo.MINOR_VERSION, turbo.MICRO_VERSION) else turbo.VERSION = string.format("%d.%d", turbo.MAJOR_VERSION, turbo.MINOR_VERSION) end turbo.log = require "turbo.log" turbo.ioloop = require "turbo.ioloop" turbo.escape = require "turbo.escape" turbo.httputil = require "turbo.httputil" turbo.tcpserver = require "turbo.tcpserver" turbo.httpserver = require "turbo.httpserver" turbo.iostream = require "turbo.iostream" turbo.crypto = require "turbo.crypto" turbo.async = require "turbo.async" turbo.web = require "turbo.web" turbo.util = require "turbo.util" turbo.coctx = require "turbo.coctx" turbo.websocket = require "turbo.websocket" turbo.signal = require "turbo.signal" turbo.socket = require "turbo.socket_ffi" turbo.sockutil = require "turbo.sockutil" turbo.hash = require "turbo.hash" turbo.syscall = require "turbo.syscall" turbo.inotify = require "turbo.inotify" turbo.fs = require "turbo.fs" turbo.structs = {} turbo.structs.deque = require "turbo.structs.deque" turbo.structs.buffer = require "turbo.structs.buffer" return turbo
Fix indentation. Again...
Fix indentation. Again...
Lua
apache-2.0
luastoned/turbo,mniestroj/turbo,zcsteele/turbo,luastoned/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,kernelsauce/turbo
c154f3a24946ed9781f46bb468f87a3452f4197a
OvaleBanditsGuile.lua
OvaleBanditsGuile.lua
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]------------------------------------------------------------------- --[[ This addon tracks the hidden stacking damage buff from Bandit's Guile on a combat rogue. Bandit's Guile description from wowhead.com: Your training allows you to recognize and take advantage of the natural ebb and flow of combat. Your Sinister Strike and Revealing Strike abilities increase your damage dealt by up to 30%. After reaching this maximum, the effect will fade after 15 sec and the cycle will begin anew. Mechanically, there is a hidden buff that stacks up to 12. At 4 stacks, the rogue gains Shallow Insight (10% increased damage). At 8 stacks, the rogue gains Moderate Insight (20% increased damage). At 12 stacks, the rogue gains Deep Insight (30% increased damage). This addon manages the hidden aura in OvaleAura using events triggered by either attacking with Sinister/Revealing Strike or by changes to the Insight auras on the player. The aura ID of the hidden aura is set to 84654, the spell ID of Bandit's Guile, and can be checked like any other aura using OvaleAura's public or state methods. --]] local _, Ovale = ... local OvaleBanditsGuile = Ovale:NewModule("OvaleBanditsGuile", "AceEvent-3.0") Ovale.OvaleBanditsGuile = OvaleBanditsGuile --<private-static-properties> -- Forward declarations for module dependencies. local OvaleAura = nil local OvaleSpellBook = nil local API_GetTime = GetTime local API_UnitClass = UnitClass local API_UnitGUID = UnitGUID -- Player's class. local _, self_class = API_UnitClass("player") -- Player's GUID. local self_guid = nil -- Aura IDs for visible buff from Bandit's Guile. local SHALLOW_INSIGHT = 84745 local MODERATE_INSIGHT = 84746 local DEEP_INSIGHT = 84747 -- Bandit's Guile spell ID. local BANDITS_GUILE = 84654 -- Spell IDs for abilities that proc Bandit's Guile. local BANDITS_GUILE_ATTACK = { [ 1752] = "Sinister Strike", [84617] = "Revealing Strike", } --</private-static-properties> --<public-static-properties> OvaleBanditsGuile.spellName = "Bandit's Guile" -- Bandit's Guile spell ID from spellbook; re-used as the aura ID of the hidden, stacking buff. OvaleBanditsGuile.spellId = BANDITS_GUILE OvaleBanditsGuile.start = 0 OvaleBanditsGuile.ending = math.huge OvaleBanditsGuile.duration = 15 OvaleBanditsGuile.stacks = 0 --</public-static-properties> --<public-static-methods> function OvaleBanditsGuile:OnInitialize() -- Resolve module dependencies. OvaleAura = Ovale.OvaleAura OvaleSpellBook = Ovale.OvaleSpellBook end function OvaleBanditsGuile:OnEnable() if self_class == "ROGUE" then self_guid = API_UnitGUID("player") self:RegisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:OnDisable() if self_class == "ROGUE" then self:UnregisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:Ovale_SpecializationChanged(event, specialization, previousSpecialization) -- This misses the corner case of if you're leveling and just acquire the spell. if specialization == "combat" and OvaleSpellBook:IsKnownSpell(BANDITS_GUILE) then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("Ovale_AuraAdded") self:RegisterMessage("Ovale_AuraChanged") self:RegisterMessage("Ovale_AuraRemoved") else self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterMessage("Ovale_AuraAdded") self:UnregisterMessage("Ovale_AuraChanged") self:UnregisterMessage("Ovale_AuraRemoved") end end -- This event handler uses CLEU to track Bandit's Guile before it has procced any level of the -- Insight buff. function OvaleBanditsGuile:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...) local arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 = ... if sourceGUID == self_guid and cleuEvent == "SPELL_DAMAGE" and self.stacks < 3 then local spellId = arg12 if BANDITS_GUILE_ATTACK[spellId] then local now = API_GetTime() self.start = now self.ending = self.start + self.duration self.stacks = self.stacks + 1 self:GainedAura(now) end end end -- This event handler uses Ovale_AuraAdded to track the Insight buff being applied for the first -- time and sets the implied stacks of Bandit's Guile. function OvaleBanditsGuile:Ovale_AuraAdded(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- Set stacks to count implied by seeing the given aura added to the player. if auraId == SHALLOW_INSIGHT then self.stacks = 4 elseif auraId == MODERATE_INSIGHT then self.stacks = 8 elseif auraId == DEEP_INSIGHT then self.stacks = 12 end self:GainedAura(timestamp) end end end -- This event handler uses Ovale_AuraChanged to track refreshes of the Insight buff, which indicates -- that it the hidden Bandit's Guile buff has gained extra stacks. function OvaleBanditsGuile:Ovale_AuraChanged(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- A changed Insight buff also means that the Bandit's Guile hidden buff gained a stack. self.stacks = self.stacks + 1 self:GainedAura(timestamp) end end end function OvaleBanditsGuile:Ovale_AuraRemoved(event, timestamp, target, auraId, caster) if target == self_guid then if (auraId == SHALLOW_INSIGHT and self.stacks < 8) or (auraId == MODERATE_INSIGHT and self.stacks < 12) or auraId == DEEP_INSIGHT then self.ending = timestamp self.stacks = 0 OvaleAura:LostAuraOnGUID(self_guid, timestamp, self.spellId, self_guid) end end end function OvaleBanditsGuile:GainedAura(atTime) OvaleAura:GainedAuraOnGUID(self_guid, atTime, self.spellId, self_guid, "HELPFUL", nil, nil, self.stacks, nil, self.duration, self.ending, nil, self.spellName, nil, nil, nil) end function OvaleBanditsGuile:Debug() local aura = OvaleAura:GetAuraByGUID(self_guid, self.spellId, "HELPFUL", true) if aura then Ovale:FormatPrint("Player has Bandit's Guile aura with start=%s, end=%s, stacks=%d.", aura.start, aura.ending, aura.stacks) end end --</public-static-methods>
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]------------------------------------------------------------------- --[[ This addon tracks the hidden stacking damage buff from Bandit's Guile on a combat rogue. Bandit's Guile description from wowhead.com: Your training allows you to recognize and take advantage of the natural ebb and flow of combat. Your Sinister Strike and Revealing Strike abilities increase your damage dealt by up to 30%. After reaching this maximum, the effect will fade after 15 sec and the cycle will begin anew. Mechanically, there is a hidden buff that stacks up to 12. At 4 stacks, the rogue gains Shallow Insight (10% increased damage). At 8 stacks, the rogue gains Moderate Insight (20% increased damage). At 12 stacks, the rogue gains Deep Insight (30% increased damage). This addon manages the hidden aura in OvaleAura using events triggered by either attacking with Sinister/Revealing Strike or by changes to the Insight auras on the player. The aura ID of the hidden aura is set to 84654, the spell ID of Bandit's Guile, and can be checked like any other aura using OvaleAura's public or state methods. --]] local _, Ovale = ... local OvaleBanditsGuile = Ovale:NewModule("OvaleBanditsGuile", "AceEvent-3.0") Ovale.OvaleBanditsGuile = OvaleBanditsGuile --<private-static-properties> -- Forward declarations for module dependencies. local OvaleAura = nil local API_GetTime = GetTime local API_UnitClass = UnitClass local API_UnitGUID = UnitGUID -- Player's class. local _, self_class = API_UnitClass("player") -- Player's GUID. local self_guid = nil -- Aura IDs for visible buff from Bandit's Guile. local SHALLOW_INSIGHT = 84745 local MODERATE_INSIGHT = 84746 local DEEP_INSIGHT = 84747 -- Bandit's Guile spell ID. local BANDITS_GUILE = 84654 -- Spell IDs for abilities that proc Bandit's Guile. local BANDITS_GUILE_ATTACK = { [ 1752] = "Sinister Strike", [84617] = "Revealing Strike", } --</private-static-properties> --<public-static-properties> OvaleBanditsGuile.spellName = "Bandit's Guile" -- Bandit's Guile spell ID from spellbook; re-used as the aura ID of the hidden, stacking buff. OvaleBanditsGuile.spellId = BANDITS_GUILE OvaleBanditsGuile.start = 0 OvaleBanditsGuile.ending = math.huge OvaleBanditsGuile.duration = 15 OvaleBanditsGuile.stacks = 0 --</public-static-properties> --<public-static-methods> function OvaleBanditsGuile:OnInitialize() -- Resolve module dependencies. OvaleAura = Ovale.OvaleAura end function OvaleBanditsGuile:OnEnable() if self_class == "ROGUE" then self_guid = API_UnitGUID("player") self:RegisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:OnDisable() if self_class == "ROGUE" then self:UnregisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:Ovale_SpecializationChanged(event, specialization, previousSpecialization) if specialization == "combat" then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("Ovale_AuraAdded") self:RegisterMessage("Ovale_AuraChanged") self:RegisterMessage("Ovale_AuraRemoved") else self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterMessage("Ovale_AuraAdded") self:UnregisterMessage("Ovale_AuraChanged") self:UnregisterMessage("Ovale_AuraRemoved") end end -- This event handler uses CLEU to track Bandit's Guile before it has procced any level of the -- Insight buff. function OvaleBanditsGuile:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...) local arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 = ... if sourceGUID == self_guid and cleuEvent == "SPELL_DAMAGE" and self.stacks < 3 then local spellId = arg12 if BANDITS_GUILE_ATTACK[spellId] then local now = API_GetTime() self.start = now self.ending = self.start + self.duration self.stacks = self.stacks + 1 self:GainedAura(now) end end end -- This event handler uses Ovale_AuraAdded to track the Insight buff being applied for the first -- time and sets the implied stacks of Bandit's Guile. function OvaleBanditsGuile:Ovale_AuraAdded(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- Set stacks to count implied by seeing the given aura added to the player. if auraId == SHALLOW_INSIGHT then self.stacks = 4 elseif auraId == MODERATE_INSIGHT then self.stacks = 8 elseif auraId == DEEP_INSIGHT then self.stacks = 12 end self:GainedAura(timestamp) end end end -- This event handler uses Ovale_AuraChanged to track refreshes of the Insight buff, which indicates -- that it the hidden Bandit's Guile buff has gained extra stacks. function OvaleBanditsGuile:Ovale_AuraChanged(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- A changed Insight buff also means that the Bandit's Guile hidden buff gained a stack. self.stacks = self.stacks + 1 self:GainedAura(timestamp) end end end function OvaleBanditsGuile:Ovale_AuraRemoved(event, timestamp, target, auraId, caster) if target == self_guid then if (auraId == SHALLOW_INSIGHT and self.stacks < 8) or (auraId == MODERATE_INSIGHT and self.stacks < 12) or auraId == DEEP_INSIGHT then self.ending = timestamp self.stacks = 0 OvaleAura:LostAuraOnGUID(self_guid, timestamp, self.spellId, self_guid) end end end function OvaleBanditsGuile:GainedAura(atTime) OvaleAura:GainedAuraOnGUID(self_guid, atTime, self.spellId, self_guid, "HELPFUL", nil, nil, self.stacks, nil, self.duration, self.ending, nil, self.spellName, nil, nil, nil) end function OvaleBanditsGuile:Debug() local aura = OvaleAura:GetAuraByGUID(self_guid, self.spellId, "HELPFUL", true) if aura then Ovale:FormatPrint("Player has Bandit's Guile aura with start=%s, end=%s, stacks=%d.", aura.start, aura.ending, aura.stacks) end end --</public-static-methods>
Fix Bandit's Guile detection on combat rogues.
Fix Bandit's Guile detection on combat rogues. The spellbook isn't completely catalogued when the specialization is detected, so we can't check for Bandit's Guile in the spellbook to trigger adding event handlers. Instead, just assume combat rogues have access to Bandit's Guile.
Lua
mit
eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale
61a5104d66e852cbc3d7e534bda3e904f98d3b7d
framework/libs/httpclient.lua
framework/libs/httpclient.lua
local function tappend(t, v) t[#t+1] = v end -- dep -- https://github.com/pintsized/lua-resty-http local http_handle = require('framework.libs.http').new() -- perf local setmetatable = setmetatable local HttpClient = { http_handle = http_handle } HttpClient.__index = HttpClient function HttpClient:new() return setmetatable({}, self) end local function request(self, url, method, params, headers, timeout_ms) self.http_handle:set_timeout(timeout_ms) local res, err = self.http_handle:request_uri(url, { method = method, body = params, headers = headers }) return res.body end local function build_params(params) local params_arr = {} for k, v in pairs(params) do tappend(params_arr, k .. "=" .. v) end return table.concat(params_arr, "&") end function HttpClient:get(url, params, headers, timeout_ms) if params then if string.find(url, '?') then url = url .. "&" else url = url .. "?" end url = url .. build_params(params) end return request(self, url, "GET", '', headers, timeout_ms) end function HttpClient:post(url, params, headers, timeout_ms) if not headers then headers = {} end if not headers["Content-Type"] then headers["Content-Type"] = "application/x-www-form-urlencoded" end return request(self, url, "POST", build_params(params), headers, timeout_ms) end function HttpClient:put(url, params, headers, timeout_ms) if not headers then headers = {} end if not headers["Content-Type"] then headers["Content-Type"] = "application/x-www-form-urlencoded" end return request(self, url, "PUT", build_params(params), headers, timeout_ms) end function HttpClient:delete(url, params, headers, timeout_ms) return request(self, url, "DELETE", build_params(params), headers, timeout_ms) end return HttpClient
local function tappend(t, v) t[#t+1] = v end -- dep -- https://github.com/pintsized/lua-resty-http local http = require('framework.libs.http') -- perf local setmetatable = setmetatable local HttpClient = {} HttpClient.__index = HttpClient function HttpClient:new() return setmetatable({ http_handle = http:new(), }, self) end local function request(self, url, method, params, headers, timeout_ms) self.http_handle:set_timeout(timeout_ms) local res, err = self.http_handle:request_uri(url, { method = method, body = params, headers = headers }) return res.body end local function build_params(params) local params_arr = {} for k, v in pairs(params) do tappend(params_arr, k .. "=" .. v) end return table.concat(params_arr, "&") end function HttpClient:get(url, params, headers, timeout_ms) if params then if string.find(url, '?') then url = url .. "&" else url = url .. "?" end url = url .. build_params(params) end return request(self, url, "GET", '', headers, timeout_ms) end function HttpClient:post(url, params, headers, timeout_ms) if not headers then headers = {} end if not headers["Content-Type"] then headers["Content-Type"] = "application/x-www-form-urlencoded" end return request(self, url, "POST", build_params(params), headers, timeout_ms) end function HttpClient:put(url, params, headers, timeout_ms) if not headers then headers = {} end if not headers["Content-Type"] then headers["Content-Type"] = "application/x-www-form-urlencoded" end return request(self, url, "PUT", build_params(params), headers, timeout_ms) end function HttpClient:delete(url, params, headers, timeout_ms) return request(self, url, "DELETE", build_params(params), headers, timeout_ms) end return HttpClient
fix bug, not singleton
fix bug, not singleton
Lua
bsd-2-clause
nicholaskh/strawberry,nicholaskh/strawberry
b4dfdc5942d622300b853445e8df432f848b4d80
check/redis.lua
check/redis.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 timer = require('timer') local net = require('net') local Error = require('core').Error local async = require('async') local BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local split = require('../util/misc').split local fireOnce = require('../util/misc').fireOnce local MAX_BUFFER_LENGTH = 1024 * 1024 * 1 -- 1 MB local METRICS_MAP = { redis_version = { type = 'string', alias = 'version' }, uptime_in_seconds = { type = 'uint32' }, connected_clients = { type = 'uint32' }, blocked_clients = { type = 'uint32' }, used_memory = { type = 'uint64' }, bgsave_in_progress = { type = 'uint32' }, changes_since_last_save = { type = 'uint32' }, bgrewriteaof_in_progress = { type = 'uint32' }, total_connections_received = { type = 'gauge' }, total_commands_processed = { type = 'gauge' }, expired_key = { type = 'uint32' }, evicted_keys = { type = 'uint32' }, pubsub_patterns = { type = 'uint32' } } local RedisCheck = BaseCheck:extend() function RedisCheck:initialize(params) BaseCheck.initialize(self, params) self._host = params.details.host or 'localhost' self._port = params.details.port or 6379 self._password = params.details.password or nil self._timeout = params.details.timeout or 5000 end function RedisCheck:getType() return 'agent.redis' end function RedisCheck:_parseResponse(data) local result = {}, item, mapItem, name lines = data:gmatch('([^\n]*)\n') for line in lines do item = self:_parseLine(line) if item then mapItem = METRICS_MAP[item['key']] else mapItem = nil end if mapItem ~= nil then name = mapItem['alias'] and mapItem['alias'] or item['key'] result[name] = {name = name, type = mapItem['type'], value = item['value']} end end return result end function RedisCheck:_parseLine(line) local parts = split(line, '[^:]+') local result = {}, value if #parts < 2 then return nil end result['key'] = parts[1] result['value'] = parts[2] return result end function RedisCheck:run(callback) local checkResult = CheckResult:new(self, {}) local client async.series({ function(callback) local wrappedCallback = fireOnce(callback) -- Connect client = net.createConnection(self._port, self._host, wrappedCallback) client:setTimeout(self._timeout) client:on('error', wrappedCallback) client:on('timeout', function() wrappedCallback(Error:new('Connection timed out in ' .. self._timeout .. 'ms')) end) end, function(callback) local buffer = '' -- Try to authenticate if password is provided if not self._password then callback() return end client:on('data', function(data) buffer = buffer .. data if buffer:lower():find('+ok') then callback() elseif buffer:lower():find('-err invalid password') then callback(Error:new('Could not authenticate. Invalid password.')) elseif buffer:len() > MAX_BUFFER_LENGTH then callback(Error:new('Maximum buffer length reached')) end end) client:write('AUTH ' .. self._password .. '\r\n') end, function(callback) local buffer = '' client:removeListener('data') client:removeListener('end') -- Retrieve stats client:on('data', function(data) if buffer:len() < MAX_BUFFER_LENGTH then buffer = buffer .. data else callback(Error:new('Maximum buffer length reached')) end end) client:on('end', function() local result if buffer:lower():find('-err operation not permitted') then callback(Error:new('Could not authenticate. Missing password?')) return end if buffer:lower():find('-err invalid password') then callback(Error:new('Could not authenticate. Invalid password.')) return end result = self:_parseResponse(buffer) for k, v in pairs(result) do checkResult:addMetric(v['name'], nil, v['type'], v['value']) end callback() end) client:write('INFO\r\n') client:write('QUIT\r\n') client:shutdown() end }, function(err) if err then checkResult:setError(err.message) end callback(checkResult) end) end local exports = {} exports.RedisCheck = RedisCheck 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 timer = require('timer') local net = require('net') local Error = require('core').Error local async = require('async') local BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local split = require('../util/misc').split local trim = require('../util/misc').trim local fireOnce = require('../util/misc').fireOnce local MAX_BUFFER_LENGTH = 1024 * 1024 * 1 -- 1 MB local METRICS_MAP = { redis_version = { type = 'string', alias = 'version' }, uptime_in_seconds = { type = 'uint32' }, connected_clients = { type = 'uint32' }, blocked_clients = { type = 'uint32' }, used_memory = { type = 'uint64' }, bgsave_in_progress = { type = 'uint32' }, changes_since_last_save = { type = 'uint32' }, bgrewriteaof_in_progress = { type = 'uint32' }, total_connections_received = { type = 'gauge' }, total_commands_processed = { type = 'gauge' }, expired_key = { type = 'uint32' }, evicted_keys = { type = 'uint32' }, pubsub_patterns = { type = 'uint32' } } local RedisCheck = BaseCheck:extend() function RedisCheck:initialize(params) BaseCheck.initialize(self, params) self._host = params.details.host or 'localhost' self._port = params.details.port or 6379 self._password = params.details.password or nil self._timeout = params.details.timeout or 5000 end function RedisCheck:getType() return 'agent.redis' end function RedisCheck:_parseResponse(data) local result = {}, item, mapItem, name lines = data:gmatch('([^\n]*)\n') for line in lines do item = self:_parseLine(line) if item then mapItem = METRICS_MAP[item['key']] else mapItem = nil end if mapItem ~= nil then name = mapItem['alias'] and mapItem['alias'] or item['key'] result[name] = {name = name, type = mapItem['type'], value = item['value']} end end return result end function RedisCheck:_parseLine(line) local parts = split(line, '[^:]+') local result = {}, value if #parts < 2 then return nil end result['key'] = trim(parts[1]) result['value'] = trim(parts[2]) return result end function RedisCheck:run(callback) local checkResult = CheckResult:new(self, {}) local client local connected = false async.series({ function(callback) local wrappedCallback = fireOnce(callback) -- Connect client = net.createConnection(self._port, self._host, wrappedCallback) client:setTimeout(self._timeout) client:on('error', wrappedCallback) client:on('timeout', function() wrappedCallback(Error:new('Connection timed out in ' .. self._timeout .. 'ms')) end) end, function(callback) local buffer = '' -- Try to authenticate if password is provided if not self._password then callback() return end connected = true client:on('data', function(data) buffer = buffer .. data if buffer:lower():find('+ok') then callback() elseif buffer:lower():find('-err invalid password') then callback(Error:new('Could not authenticate. Invalid password.')) elseif buffer:len() > MAX_BUFFER_LENGTH then callback(Error:new('Maximum buffer length reached')) end end) client:write('AUTH ' .. self._password .. '\r\n') end, function(callback) local buffer = '' client:removeListener('data') client:removeListener('end') -- Retrieve stats client:on('data', function(data) if buffer:len() < MAX_BUFFER_LENGTH then buffer = buffer .. data else callback(Error:new('Maximum buffer length reached')) end end) client:on('end', function() local result if buffer:lower():find('-err operation not permitted') then callback(Error:new('Could not authenticate. Missing password?')) return end if buffer:lower():find('-err invalid password') then callback(Error:new('Could not authenticate. Invalid password.')) return end result = self:_parseResponse(buffer) for k, v in pairs(result) do checkResult:addMetric(v['name'], nil, v['type'], v['value']) end callback() end) client:write('INFO\r\n') client:write('QUIT\r\n') end }, function(err) if err then checkResult:setError(err.message) end if connected then client:shutdown() end callback(checkResult) end) end local exports = {} exports.RedisCheck = RedisCheck return exports
fixes(redis): shutdown and metrics fix
fixes(redis): shutdown and metrics fix - Don't shutdown the connection until we have sent and gathered the metrics - trim the newlines out of the key and value
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
5c04addd2e13cd1b0296a719a58248ef37cceed2
mods/city_block/init.lua
mods/city_block/init.lua
-- Minetest mod "City block" -- City block disables use of water/lava buckets and also sends aggressive players to jail --This library is free software; you can redistribute it and/or --modify it under the terms of the GNU Lesser General Public --License as published by the Free Software Foundation; either --version 2.1 of the License, or (at your option) any later version. city_block={} city_block.blocks={} city_block.filename = minetest.get_worldpath() .. "/city_blocks.txt" city_block.suspects={} function city_block:save() local datastring = minetest.serialize(self.blocks) if not datastring then return end local file, err = io.open(self.filename, "w") if err then return end file:write(datastring) file:close() end function city_block:load() local file, err = io.open(self.filename, "r") if err then self.blocks = {} return end self.blocks = minetest.deserialize(file:read("*all")) if type(self.blocks) ~= "table" then self.blocks = {} end file:close() end function city_block:in_city(pos) for i, EachBlock in ipairs(self.blocks) do if pos.x > (EachBlock.pos.x - 23) and pos.x < (EachBlock.pos.x + 23) and pos.z > (EachBlock.pos.z - 23) and pos.z < (EachBlock.pos.z + 23) and pos.y > (EachBlock.pos.y - 10) then return true end end return false end function city_block:city_boundaries(pos) for i, EachBlock in ipairs(self.blocks) do if (pos.x == (EachBlock.pos.x - 23) or pos.x == (EachBlock.pos.x + 23)) and pos.z > (EachBlock.pos.z - 23) and pos.z < (EachBlock.pos.z + 23 ) then return true end if (pos.z == (EachBlock.pos.z - 23) or pos.z == (EachBlock.pos.z + 23)) and pos.x > (EachBlock.pos.x - 23) and pos.x < (EachBlock.pos.x + 23 ) then return true end end return false end city_block:load() minetest.register_node("city_block:cityblock", { description = "City block mark area 45x45 in size as part of city", tiles = {"cityblock.png"}, is_ground_content = false, groups = {cracky=1,level=3}, is_ground_content = false, light_source = LIGHT_MAX, after_place_node = function(pos, placer) if placer and placer:is_player() then table.insert(city_block.blocks, {pos=vector.round(pos), owner=placer:get_player_name()} ) city_block:save() end end, on_destruct = function(pos) for i, EachBlock in ipairs(city_block.blocks) do if vector.equals(EachBlock.pos, pos) then table.remove(city_block.blocks, i) city_block:save() end end end, }) minetest.register_craft({ output = 'city_block:cityblock', recipe = { {'default:pick_mese', 'farming:hoe_mese', 'default:sword_mese'}, {'default:sandstone', 'default:goldblock', 'default:sandstone'}, {'default:stonebrick', 'default:mese', 'default:stonebrick'}, } }) local old_bucket_water_on_place=minetest.registered_craftitems["bucket:bucket_water"].on_place minetest.registered_craftitems["bucket:bucket_water"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Don't do that in town!") return itemstack else return old_bucket_water_on_place(itemstack, placer, pointed_thing) end end local old_bucket_lava_on_place=minetest.registered_craftitems["bucket:bucket_lava"].on_place minetest.registered_craftitems["bucket:bucket_lava"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Don't do that in town!") return itemstack else return old_bucket_lava_on_place(itemstack, placer, pointed_thing) end end --[[local tnt_on_place=minetest.registered_craftitems["tnt:tnt"].on_place minetest.registered_craftitems["tnt:tnt"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Do NOT blow anything up in the city!!!!") return itemstack else return tnt_on_place(itemstack, placer, pointed_thing) end end]] minetest.register_on_dieplayer( function(player) pos=player:getpos() if city_block:in_city(pos) and not(pos.x>-25 and pos.x<25 and pos.y>-5 and pos.y<25 and pos.z>-25 and pos.z<25) then for _,suspect in pairs(minetest.get_objects_inside_radius(pos, 13.8)) do if suspect:is_player() and suspect:get_player_name()~=player:get_player_name() then suspect_name=suspect:get_player_name() if city_block.suspects[suspect_name] then if city_block.suspects[suspect_name]>3 then suspect:setpos( {x=-213, y=2, z=920} ) minetest.chat_send_all("Player "..suspect_name.." sent to PRISON as suspect for killing in town") minetest.log("action", "Player "..suspect_name.." warned for killing in town") city_block.suspects[suspect_name]=1 else city_block.suspects[suspect_name]=city_block.suspects[suspect_name]+1 end else city_block.suspects[suspect_name]=1 end return false end end end end ) --do not let lava flow across boundary of city block minetest.register_abm({ nodenames = {"default:lava_flowing"}, interval = 5, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) if pos.y>14 and city_block:city_boundaries(pos) then minetest.set_node(pos, {name="default:stone"}) end end, })
-- Minetest mod "City block" -- City block disables use of water/lava buckets and also sends aggressive players to jail -- modified by rnd: only send player in jail if he kills by punching, no more innocent players in jail --This library is free software; you can redistribute it and/or --modify it under the terms of the GNU Lesser General Public --License as published by the Free Software Foundation; either --version 2.1 of the License, or (at your option) any later version. city_block={} city_block.blocks={} city_block.filename = minetest.get_worldpath() .. "/city_blocks.txt" city_block.suspects={} function city_block:save() local datastring = minetest.serialize(self.blocks) if not datastring then return end local file, err = io.open(self.filename, "w") if err then return end file:write(datastring) file:close() end function city_block:load() local file, err = io.open(self.filename, "r") if err then self.blocks = {} return end self.blocks = minetest.deserialize(file:read("*all")) if type(self.blocks) ~= "table" then self.blocks = {} end file:close() end function city_block:in_city(pos) for i, EachBlock in ipairs(self.blocks) do if pos.x > (EachBlock.pos.x - 23) and pos.x < (EachBlock.pos.x + 23) and pos.z > (EachBlock.pos.z - 23) and pos.z < (EachBlock.pos.z + 23) and pos.y > (EachBlock.pos.y - 10) then return true end end return false end function city_block:city_boundaries(pos) for i, EachBlock in ipairs(self.blocks) do if (pos.x == (EachBlock.pos.x - 23) or pos.x == (EachBlock.pos.x + 23)) and pos.z > (EachBlock.pos.z - 23) and pos.z < (EachBlock.pos.z + 23 ) then return true end if (pos.z == (EachBlock.pos.z - 23) or pos.z == (EachBlock.pos.z + 23)) and pos.x > (EachBlock.pos.x - 23) and pos.x < (EachBlock.pos.x + 23 ) then return true end end return false end city_block:load() minetest.register_node("city_block:cityblock", { description = "City block mark area 45x45 in size as part of city", tiles = {"cityblock.png"}, is_ground_content = false, groups = {cracky=1,level=3}, is_ground_content = false, light_source = LIGHT_MAX, after_place_node = function(pos, placer) if placer and placer:is_player() then table.insert(city_block.blocks, {pos=vector.round(pos), owner=placer:get_player_name()} ) city_block:save() end end, on_destruct = function(pos) for i, EachBlock in ipairs(city_block.blocks) do if vector.equals(EachBlock.pos, pos) then table.remove(city_block.blocks, i) city_block:save() end end end, }) minetest.register_craft({ output = 'city_block:cityblock', recipe = { {'default:pick_mese', 'farming:hoe_mese', 'default:sword_mese'}, {'default:sandstone', 'default:goldblock', 'default:sandstone'}, {'default:stonebrick', 'default:mese', 'default:stonebrick'}, } }) local old_bucket_water_on_place=minetest.registered_craftitems["bucket:bucket_water"].on_place minetest.registered_craftitems["bucket:bucket_water"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Don't do that in town!") return itemstack else return old_bucket_water_on_place(itemstack, placer, pointed_thing) end end local old_bucket_lava_on_place=minetest.registered_craftitems["bucket:bucket_lava"].on_place minetest.registered_craftitems["bucket:bucket_lava"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Don't do that in town!") return itemstack else return old_bucket_lava_on_place(itemstack, placer, pointed_thing) end end --[[local tnt_on_place=minetest.registered_craftitems["tnt:tnt"].on_place minetest.registered_craftitems["tnt:tnt"].on_place=function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if city_block:in_city(pos) then minetest.chat_send_player(placer:get_player_name(), "Do NOT blow anything up in the city!!!!") return itemstack else return tnt_on_place(itemstack, placer, pointed_thing) end end]] -- rnd: now only players who kill others by punching go to jail, no more fail jailings minetest.register_on_punchplayer( function(player, hitter, time_from_last_punch, tool_capabilities, dir, damage) local hp = player:get_hp(); if hp-damage<0 then -- player will die local pos = player:getpos() if city_block:in_city(pos) and not(pos.x>-25 and pos.x<25 and pos.y>-5 and pos.y<25 and pos.z>-25 and pos.z<25) then local name = hitter:get_player_name(); local pname = player:get_player_name(); if not name or not pname then return end hitter:setpos( {x=-213, y=2, z=920} ) minetest.chat_send_all("Player "..name.." sent to PRISON as suspect for killing " .. pname .." in town") minetest.log("action", "Player "..name.." warned for killing in town") end end end ) --[[ minetest.register_on_dieplayer( function(player) local pos=player:getpos() if city_block:in_city(pos) and not(pos.x>-25 and pos.x<25 and pos.y>-5 and pos.y<25 and pos.z>-25 and pos.z<25) then for _,suspect in pairs(minetest.get_objects_inside_radius(pos, 13.8)) do if suspect:is_player() and suspect:get_player_name()~=player:get_player_name() then suspect_name=suspect:get_player_name() if city_block.suspects[suspect_name] then if city_block.suspects[suspect_name]>3 then suspect:setpos( {x=-213, y=2, z=920} ) minetest.chat_send_all("Player "..suspect_name.." sent to PRISON as suspect for killing in town") minetest.log("action", "Player "..suspect_name.." warned for killing in town") city_block.suspects[suspect_name]=1 else city_block.suspects[suspect_name]=city_block.suspects[suspect_name]+1 end else city_block.suspects[suspect_name]=1 end return false end end end end ) ]] --do not let lava flow across boundary of city block minetest.register_abm({ nodenames = {"default:lava_flowing"}, interval = 5, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) if pos.y>14 and city_block:city_boundaries(pos) then minetest.set_node(pos, {name="default:stone"}) end end, })
rnd fixed city block, it is pretty legit now
rnd fixed city block, it is pretty legit now
Lua
lgpl-2.1
maikerumine/extreme_survival
64ad486747c7b70aa63c64e492bc7318e135d75d
lib/px/utils/pxcommonutils.lua
lib/px/utils/pxcommonutils.lua
local socket = require("socket") local _M = {} function _M.get_time_in_milliseconds() return socket.gettime() * 1000 end function _M.array_index_of(array, item) if array == nil then return -1 end for i, value in ipairs(array) do if string.lower(value) == string.lower(item) then return i end end return -1 end function clone (t) -- deep-copy a table if type(t) ~= "table" then return t end local meta = getmetatable(t) local target = {} for k, v in pairs(t) do if type(v) == "table" then target[k] = clone(v) else target[k] = v end end setmetatable(target, meta) return target end function _M.filter_config(px_config) local config_copy = clone(px_config) -- remove config_copy.cookie_secret = nil config_copy.auth_token = nil return config_copy end function _M.filter_headers(sensitive_headers, isRiskRequest) local headers = ngx.req.get_headers() local request_headers = {} for k, v in pairs(headers) do -- filter sensitive headers if _M.array_index_of(sensitive_headers, k) == -1 then if isRiskRequest == true then request_headers[#request_headers + 1] = { ['name'] = k, ['value'] = v } else request_headers[k] = v end end end return request_headers end function _M.clear_first_party_sensitive_headers(sensitive_headers) if not sensitive_headers then return end for i, header in ipairs(sensitive_headers) do ngx.req.clear_header(header) end end return _M
local socket = require("socket") local _M = {} function _M.get_time_in_milliseconds() return socket.gettime() * 1000 end function _M.array_index_of(array, item) if array == nil then return -1 end for i, value in ipairs(array) do if string.lower(value) == string.lower(item) then return i end end return -1 end function clone (t) -- deep-copy a table if type(t) ~= "table" then return t end local meta = getmetatable(t) local target = {} for k, v in pairs(t) do if type(v) == "function" then target[k] = string.dump(v) elseif type(v) == "table" then target[k] = clone(v) else target[k] = v end end setmetatable(target, meta) return target end function _M.filter_config(px_config) local config_copy = clone(px_config) -- remove config_copy.cookie_secret = nil config_copy.auth_token = nil return config_copy end function _M.filter_headers(sensitive_headers, isRiskRequest) local headers = ngx.req.get_headers() local request_headers = {} for k, v in pairs(headers) do -- filter sensitive headers if _M.array_index_of(sensitive_headers, k) == -1 then if isRiskRequest == true then request_headers[#request_headers + 1] = { ['name'] = k, ['value'] = v } else request_headers[k] = v end end end return request_headers end function _M.clear_first_party_sensitive_headers(sensitive_headers) if not sensitive_headers then return end for i, header in ipairs(sensitive_headers) do ngx.req.clear_header(header) end end return _M
fixed lambda fuctions copy
fixed lambda fuctions copy
Lua
mit
PerimeterX/perimeterx-nginx-plugin
ccc7ec6f2fd76367f436bbc9f859c27352512ceb
modules/rroulette.lua
modules/rroulette.lua
local rr = ivar2.persist if(not ivar2.timers) then ivar2.timers = {} end local getBullet = function(n) return n % 10 end local getChamber = function(n) return (n - getBullet(n)) / 10 % 10 end return { PRIVMSG = { ['^%prr$'] = function(self, source, destination) local nick = source.nick if(not rr['rr:'..destination]) then rr['rr:'..destination] = 60 + math.random(1,6) end local bullet = getBullet(rr['rr:'..destination]) local chamber = getChamber(rr['rr:'..destination]) local deathKey = destination .. ':' .. nick .. ':deaths' local attemptKey = destination .. ':' .. nick .. ':attempts' local deaths = rr['rr:'..deathKey] or 0 local attempts = (rr['rr:'..attemptKey] or 0) + 1 local seed = math.random(1, chamber) if(seed == bullet) then bullet = math.random(1, 6) chamber = 6 deaths = deaths + 1 self:Kick(destination, nick, 'BANG!') say('BANG! %s died a gruesome death.', source.nick) else chamber = chamber - 1 if(bullet > chamber) then bullet = chamber end local src = 'Russian Roulette:' .. destination local timer = self:Timer(src, 15*60, function(loop, timer, revents) local n = rr['rr:'..destination] rr['rr:'..destination] = 60 + math.random(1,6) end) say('Click. %d/6', chamber) end rr['rr:'..destination] = (chamber * 10) + bullet rr['rr:'..deathKey] = deaths rr['rr:'..attemptKey] = attempts end, ['^%prrstat$'] = function(self, source, destination) local nicks = {} for n,t in pairs(self.channels[destination].nicks) do nicks[n] = destination..':'..n end local tmp = {} for nick, key in next, nicks do if(not tmp[nick]) then tmp[nick] = {} end type = 'attempts' res = tonumber(rr['rr:'..key..':'..type]) if not res then res = 0 end tmp[nick][type] = res type = 'deaths' res = tonumber(rr['rr:'..key..':'..type]) if not res then res = 0 end tmp[nick][type] = res end local stats = {} for nick, data in next, tmp do if data.deaths > 0 or data.attempts > 0 then local deathRatio = data.deaths / data.attempts table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio}) end end table.sort(stats, function(a,b) return a.ratio < b.ratio end) local out = {} for i=1, #stats do table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100)) end say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', '))) end, } }
local rr = ivar2.persist local getBullet = function(n) return n % 10 end local getChamber = function(n) return (n - getBullet(n)) / 10 % 10 end return { PRIVMSG = { ['^%prr$'] = function(self, source, destination) local nick = source.nick if(not rr['rr:'..destination]) then rr['rr:'..destination] = 60 + math.random(1,6) end local bullet = getBullet(rr['rr:'..destination]) local chamber = getChamber(rr['rr:'..destination]) local deathKey = destination .. ':' .. nick .. ':deaths' local attemptKey = destination .. ':' .. nick .. ':attempts' local deaths = rr['rr:'..deathKey] or 0 local attempts = (rr['rr:'..attemptKey] or 0) + 1 local seed = math.random(1, chamber) if(seed == bullet) then bullet = math.random(1, 6) chamber = 6 deaths = deaths + 1 self:Kick(destination, nick, 'BANG!') say('BANG! %s died a gruesome death.', source.nick) else chamber = chamber - 1 if(bullet > chamber) then bullet = chamber end local src = 'Russian Roulette:' .. destination local timer = self:Timer(src, 15*60, function(loop, timer, revents) local n = rr['rr:'..destination] rr['rr:'..destination] = 60 + math.random(1,6) end) say('Click. %d/6', chamber) end rr['rr:'..destination] = (chamber * 10) + bullet rr['rr:'..deathKey] = deaths rr['rr:'..attemptKey] = attempts end, ['^%prrstat$'] = function(self, source, destination) local nicks = {} for n,t in pairs(self.channels[destination].nicks) do nicks[n] = destination..':'..n end local tmp = {} for nick, key in next, nicks do if(not tmp[nick]) then tmp[nick] = {} end local rtype = 'attempts' local res = tonumber(rr['rr:'..key..':'..rtype]) if not res then res = 0 end tmp[nick][rtype] = res rtype = 'deaths' res = tonumber(rr['rr:'..key..':'..rtype]) if not res then res = 0 end tmp[nick][rtype] = res end local stats = {} for nick, data in next, tmp do if data.deaths > 0 or data.attempts > 0 then local deathRatio = data.deaths / data.attempts table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio}) end end table.sort(stats, function(a,b) return a.ratio < b.ratio end) local out = {} for i=1, #stats do table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100)) end say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', '))) end, } }
rroulette: fix variables usage
rroulette: fix variables usage Former-commit-id: 68af7596c65ec2f26b2de5f3f652d7f5e23da077 [formerly 05c6f1d6e1dda227bd999a04d171ccdfe1e6a7df] Former-commit-id: 788aef6225bc715fcbaa8b25079d8a038dfb0d36
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
d62947e5556cde56294c03ccf499d5c63f53fa7c
test_scripts/Polices/Policy_Table_Update/007_ATF_P_TC_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request.lua
test_scripts/Polices/Policy_Table_Update/007_ATF_P_TC_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] OnStatusUpdate(UPDATE_NEEDED) on new PTU request -- [HMI API] OnStatusUpdate -- -- Description: -- SDL should request PTU in case new application is registered and is not listed in PT -- and device is not consented. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Connect mobile phone over WiFi. -- Register new application -- 2. Performed steps -- Trigger getting device consent -- -- Expected result: -- PTU is requested. PTS is created. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI: BasicCommunication.PolicyUpdate --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_flow_SUCCEESS_EXTERNAL_PROPRIETARY() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) end function Test.Precondition_Remove_PTS() os.execute("rm /tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") if( commonSteps:file_exists("/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") ~= false) then os.execute("rm /tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") end end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request() testCasesForPolicyTable:trigger_user_request_update_from_HMI(self) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] OnStatusUpdate(UPDATE_NEEDED) on new PTU request -- [HMI API] OnStatusUpdate -- -- Description: -- SDL should request PTU in case new application is registered and is not listed in PT -- and device is not consented. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Connect mobile phone over WiFi. -- Register new application -- 2. Performed steps -- Trigger getting device consent -- -- Expected result: -- PTU is requested. PTS is created. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI: BasicCommunication.PolicyUpdate --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_flow_SUCCEESS_EXTERNAL_PROPRIETARY() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) end function Test.Precondition_Remove_PTS() os.execute("rm /tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") if( commonSteps:file_exists("/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") ~= false) then os.execute("rm /tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json") end end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request() self.hmiConnection:SendNotification("SDL.OnPolicyUpdate", {} ) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}):Times(0) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
Fix script after clarification
Fix script after clarification
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
11b271d4a9e2d4efcc42c4d65b778b3c3c37ea72
modules/luci-base/luasrc/model/cbi/admin_network/proto_static.lua
modules/luci-base/luasrc/model/cbi/admin_network/proto_static.lua
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ifc = net:get_interface() local netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw local mtu, metric, usecidr, ipaddr_single, ipaddr_multi usecidr = section:taboption("general", Value, "ipaddr_usecidr") usecidr.forcewrite = true usecidr.cfgvalue = function(self, section) local cfgvalue = self.map:get(section, "ipaddr") return (type(cfgvalue) == "table") and "1" or "0" end usecidr.render = function(self, section, scope) luci.template.Template(nil, [[ <input type="hidden"<%= attr("id", cbid) .. attr("name", cbid) .. attr("value", value) %> /> ]]):render({ cbid = self:cbid(section), value = self:cfgvalue(section) }) end usecidr.write = function(self, section) local cfgvalue = self.map:get(section, "ipaddr") local formvalue = (self:formvalue(section) == "1") and ipaddr_multi:formvalue(section) or ipaddr_single:formvalue(section) local equal = (cfgvalue == formvalue) if not equal and type(cfgvalue) == "table" and type(formvalue) == "table" then equal = true local _, v for _, v in ipairs(cfgvalue) do if v ~= formvalue[_] then equal = false break end end end if not equal then self.map:set(section, "ipaddr", formvalue or "") end return not equal end ipaddr_multi = section:taboption("general", DynamicList, "ipaddrs", translate("IPv4 address")) ipaddr_multi:depends("ipaddr_usecidr", "1") ipaddr_multi.datatype = "or(cidr4,ipnet4)" ipaddr_multi.placeholder = translate("Add IPv4 address…") ipaddr_multi.alias = "ipaddr" ipaddr_multi.write = function() end ipaddr_multi.remove = function() end ipaddr_multi.cfgvalue = function(self, section) local addr = self.map:get(section, "ipaddr") local mask = self.map:get(section, "netmask") if type(addr) == "string" and type(mask) == "string" and #addr > 0 and #mask > 0 then return { "%s/%s" %{ addr, mask } } elseif type(addr) == "table" then return addr else return {} end end ipaddr_single = section:taboption("general", Value, "ipaddr", translate("IPv4 address")) ipaddr_single:depends("ipaddr_usecidr", "0") ipaddr_single.datatype = "ip4addr" ipaddr_single.template = "cbi/ipaddr" ipaddr_single.write = function() end ipaddr_single.remove = function() end netmask = section:taboption("general", Value, "netmask", translate("IPv4 netmask")) netmask:depends("ipaddr_usecidr", "0") netmask.datatype = "ip4addr" netmask:value("255.255.255.0") netmask:value("255.255.0.0") netmask:value("255.0.0.0") gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway")) gateway.datatype = "ip4addr" broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast")) broadcast.datatype = "ip4addr" dns = section:taboption("general", DynamicList, "dns", translate("Use custom DNS servers")) dns.datatype = "ipaddr" dns.cast = "string" if luci.model.network:has_ipv6() then local ip6assign = section:taboption("general", Value, "ip6assign", translate("IPv6 assignment length"), translate("Assign a part of given length of every public IPv6-prefix to this interface")) ip6assign:value("", translate("disabled")) ip6assign:value("64") ip6assign.datatype = "max(64)" local ip6hint = section:taboption("general", Value, "ip6hint", translate("IPv6 assignment hint"), translate("Assign prefix parts using this hexadecimal subprefix ID for this interface.")) for i=33,64 do ip6hint:depends("ip6assign", i) end ip6addr = section:taboption("general", DynamicList, "ip6addr", translate("IPv6 address")) ip6addr.datatype = "ip6addr" ip6addr.placeholder = translate("Add IPv6 address…") ip6addr:depends("ip6assign", "") ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway")) ip6gw.datatype = "ip6addr" ip6gw:depends("ip6assign", "") local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("Public prefix routed to this device for distribution to clients.")) ip6prefix.datatype = "ip6addr" ip6prefix:depends("ip6assign", "") local ip6ifaceid = s:taboption("general", Value, "ip6ifaceid", translate("IPv6 suffix"), translate("Optional. Allowed values: 'eui64', 'random', fixed value like '::1' " .. "or '::1:2'. When IPv6 prefix (like 'a:b:c:d::') is received from a " .. "delegating server, use the suffix (like '::1') to form the IPv6 address " .. "('a:b:c:d::1') for the interface.")) ip6ifaceid.datatype = "ip6hostid" ip6ifaceid.placeholder = "::1" ip6ifaceid.rmempty = true end luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address")) mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ifc = net:get_interface() local netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw local mtu, metric, usecidr, ipaddr_single, ipaddr_multi local function is_cidr(s) return (type(s) == "string" and luci.ip.IPv4(s) and s:find("/")) end usecidr = section:taboption("general", Value, "ipaddr_usecidr") usecidr.forcewrite = true usecidr.cfgvalue = function(self, section) local cfgvalue = self.map:get(section, "ipaddr") return (type(cfgvalue) == "table" or is_cidr(cfgvalue)) and "1" or "0" end usecidr.render = function(self, section, scope) luci.template.Template(nil, [[ <input type="hidden"<%= attr("id", cbid) .. attr("name", cbid) .. attr("value", value) %> /> ]]):render({ cbid = self:cbid(section), value = self:cfgvalue(section) }) end usecidr.write = function(self, section) local cfgvalue = self.map:get(section, "ipaddr") local formvalue = (self:formvalue(section) == "1") and ipaddr_multi:formvalue(section) or ipaddr_single:formvalue(section) local equal = (cfgvalue == formvalue) if not equal and type(cfgvalue) == "table" and type(formvalue) == "table" then equal = true local _, v for _, v in ipairs(cfgvalue) do if v ~= formvalue[_] then equal = false break end end end if not equal then self.map:set(section, "ipaddr", formvalue or "") end return not equal end ipaddr_multi = section:taboption("general", DynamicList, "ipaddrs", translate("IPv4 address")) ipaddr_multi:depends("ipaddr_usecidr", "1") ipaddr_multi.datatype = "or(cidr4,ipnet4)" ipaddr_multi.placeholder = translate("Add IPv4 address…") ipaddr_multi.alias = "ipaddr" ipaddr_multi.write = function() end ipaddr_multi.remove = function() end ipaddr_multi.cfgvalue = function(self, section) local addr = self.map:get(section, "ipaddr") local mask = self.map:get(section, "netmask") if is_cidr(addr) then return { addr } elseif type(addr) == "string" and type(mask) == "string" and #addr > 0 and #mask > 0 then return { "%s/%s" %{ addr, mask } } elseif type(addr) == "table" then return addr else return {} end end ipaddr_single = section:taboption("general", Value, "ipaddr", translate("IPv4 address")) ipaddr_single:depends("ipaddr_usecidr", "0") ipaddr_single.datatype = "ip4addr" ipaddr_single.template = "cbi/ipaddr" ipaddr_single.write = function() end ipaddr_single.remove = function() end netmask = section:taboption("general", Value, "netmask", translate("IPv4 netmask")) netmask:depends("ipaddr_usecidr", "0") netmask.datatype = "ip4addr" netmask:value("255.255.255.0") netmask:value("255.255.0.0") netmask:value("255.0.0.0") gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway")) gateway.datatype = "ip4addr" broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast")) broadcast.datatype = "ip4addr" dns = section:taboption("general", DynamicList, "dns", translate("Use custom DNS servers")) dns.datatype = "ipaddr" dns.cast = "string" if luci.model.network:has_ipv6() then local ip6assign = section:taboption("general", Value, "ip6assign", translate("IPv6 assignment length"), translate("Assign a part of given length of every public IPv6-prefix to this interface")) ip6assign:value("", translate("disabled")) ip6assign:value("64") ip6assign.datatype = "max(64)" local ip6hint = section:taboption("general", Value, "ip6hint", translate("IPv6 assignment hint"), translate("Assign prefix parts using this hexadecimal subprefix ID for this interface.")) for i=33,64 do ip6hint:depends("ip6assign", i) end ip6addr = section:taboption("general", DynamicList, "ip6addr", translate("IPv6 address")) ip6addr.datatype = "ip6addr" ip6addr.placeholder = translate("Add IPv6 address…") ip6addr:depends("ip6assign", "") ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway")) ip6gw.datatype = "ip6addr" ip6gw:depends("ip6assign", "") local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("Public prefix routed to this device for distribution to clients.")) ip6prefix.datatype = "ip6addr" ip6prefix:depends("ip6assign", "") local ip6ifaceid = s:taboption("general", Value, "ip6ifaceid", translate("IPv6 suffix"), translate("Optional. Allowed values: 'eui64', 'random', fixed value like '::1' " .. "or '::1:2'. When IPv6 prefix (like 'a:b:c:d::') is received from a " .. "delegating server, use the suffix (like '::1') to form the IPv6 address " .. "('a:b:c:d::1') for the interface.")) ip6ifaceid.datatype = "ip6hostid" ip6ifaceid.placeholder = "::1" ip6ifaceid.rmempty = true end luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address")) mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
luci-base: properly option ipaddr in single cidr string notation as well
luci-base: properly option ipaddr in single cidr string notation as well When an interface configuration specifies both "option ipaddr 1.2.3.4/24" and "option netmask", then netifd will ignore the netmask in favor to the prefix encoded in the cidr string. Support this variant as well by treating a sole cidr string value as singöe-item cidr list. Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
artynet/luci,openwrt-es/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,artynet/luci,nmav/luci,artynet/luci,rogerpueyo/luci,tobiaswaldvogel/luci,nmav/luci,hnyman/luci,Noltari/luci,Noltari/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,nmav/luci,Noltari/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt/luci,openwrt-es/openwrt-luci,openwrt/luci,openwrt/luci,openwrt-es/openwrt-luci,artynet/luci,artynet/luci,hnyman/luci,nmav/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,hnyman/luci,hnyman/luci,nmav/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,rogerpueyo/luci,artynet/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,lbthomsen/openwrt-luci,Noltari/luci,tobiaswaldvogel/luci,rogerpueyo/luci,openwrt/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,hnyman/luci,nmav/luci,openwrt/luci,openwrt/luci,Noltari/luci,lbthomsen/openwrt-luci,Noltari/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,nmav/luci,nmav/luci,rogerpueyo/luci,hnyman/luci,Noltari/luci,artynet/luci,openwrt/luci
2d90fb8c09ac8428510ba80363d7fe3f89fe0fae
config/nvim/lua/gb/lsp.lua
config/nvim/lua/gb/lsp.lua
local utils = require("gb.utils") local nvim_lsp = require("lspconfig") keymap = utils.map opt = utils.opt local function custom_on_init() print("Language Server Protocol started!") end local function custom_root_dir() if (string.find(vim.fn.expand("%f"), "node_modules/") == nil) then return nvim_lsp.util.root_pattern(".git") end return nil end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true nvim_lsp.vimls.setup {} --must have run: npm install -g typescript nvim_lsp.tsserver.setup { -- This makes sure tsserver is not used for formatting -- on_attach = nvim_lsp.tsserver_on_attach, root_dir = nvim_lsp.util.root_pattern("tsconfig.json", ".git"), cmd = { "typescript-language-server", "--tsserver-log-file", vim.env.HOME .. "/src/tsserver.log", "--tsserver-log-verbosity", "verbose", "--stdio" }, settings = {documentFormatting = false}, on_init = custom_on_init } --must run: npm install -g pyright nvim_lsp.pyright.setup { on_init = custom_on_init } nvim_lsp.rust_analyzer.setup { on_init = custom_on_init, settings = { ["rust-analyzer"] = { assist = { importMergeBehavior = "last", importPrefix = "by_self" }, cargo = { loadOutDirsFromCheck = true }, procMacro = { enable = true } } } } vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = true, signs = true, update_in_insert = true } ) -- npm i -g vscode-css-languageserver-bin nvim_lsp.cssls.setup { on_init = custom_on_init } -- npm i -g vscode-html-languageserver-bin nvim_lsp.html.setup { on_init = custom_on_init, capabilities = capabilities } local eslint_d = { lintCommand = "eslint_d -f unix --stdin --stdin-filename ${INPUT}", lintIgnoreExitCode = true, lintStdin = true, lintFormats = {"%f:%l:%c: %m"} } local rustExe = "rustfmt" local rustArgs = "--emit=stdout" local rustStdin = true local rustfmt = { formatCommand = rustExe .. rustArgs .. "${INPUT}", formatStdin = rustStdin } local prettierArgs = {"--stdin", "--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"} local prettier = { formatCommand = "./node_modules/.bin/prettier" .. table.concat(prettierArgs, " "), formatStdin = true } local languages = { typescript = {prettier, eslint_d}, javascript = {prettier, eslint_d}, typescriptreact = {prettier, eslint_d}, ["typescript.tsx"] = {prettier, eslint_d}, javascriptreact = {prettier, eslint_d}, ["javascript.jsx"] = {prettier, eslint_d}, yaml = {prettier}, json = {prettier}, html = {prettier}, scss = {prettier}, css = {prettier}, markdown = {prettier}, rust = {rustfmt}, python = { { formatCommand = "black", formatStdin = true }, { formatCommand = "isort", formatStdin = true } } } nvim_lsp.efm.setup { init_options = {documentFormatting = true}, filetypes = vim.tbl_keys(languages), root_dir = custom_root_dir(), settings = { languages = languages } } require "compe".setup { enabled = true, autocomplete = true, debug = false, min_length = 1, preselect = "enable", throttle_time = 80, source_timeout = 200, incomplete_delay = 400, max_abbr_width = 100, max_kind_width = 100, max_menu_width = 100, documentation = true, source = { path = true, buffer = true, nvim_lsp = true, nvim_lua = true, spell = true } } require("lspsaga").init_lsp_saga( { error_sign = "▊", warn_sign = "▊", hint_sign = "▊", infor_sign = "▊", dianostic_header_icon = "  ", code_action_icon = "", finder_definition_icon = " ", finder_reference_icon = " ", definition_preview_icon = " ", border_style = 1, rename_prompt_prefix = "❱❱", rename_action_keys = { quit = {"<C-c>", "<esc>"}, exec = "<CR>" -- quit can be a table } } ) require("lspkind").init( { with_text = true, symbol_map = { Text = "  ", Method = "  ", Function = "  ", Constructor = "  ", Variable = "[]", Class = "  ", Interface = " 蘒", Module = "  ", Property = "  ", Unit = " 塞 ", Value = "  ", Enum = " 練", Keyword = "  ", Snippet = "  ", Color = "", File = "", Folder = " ﱮ ", EnumMember = "  ", Constant = "  ", Struct = "  " } } ) vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"} opt("o", "completeopt", "menu,menuone,noselect") local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local check_back_space = function() local col = vim.fn.col(".") - 1 if col == 0 or vim.fn.getline("."):sub(col, col):match("%s") then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif check_back_space() then return t "<Tab>" else return vim.fn["compe#complete"]() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" else return t "<S-Tab>" end end keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true}) keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true}) keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) keymap("n", "gd", ":lua vim.lsp.buf.definition()<CR>", {silent = true}) keymap("n", "gR", ":Lspsaga rename<CR>") keymap("n", "gr", "LspTrouble lsp_references", {cmd_cr = true}) keymap("n", "gs", ":Lspsaga signature_help<CR>") keymap("n", "<leader>e", ":Lspsaga diagnostic_jump_next<CR>", {silent = true}) keymap("n", "<leader>cd", ":Lspsaga show_line_diagnostics<CR>", {silent = true}) keymap("n", "K", ":Lspsaga hover_doc<CR>", {silent = true}) keymap("i", "<C-Space>", "compe#complete()", {silent = true, expr = true}) keymap("i", "<CR>", 'compe#confirm("<CR>")', {silent = true, expr = true})
local utils = require("gb.utils") local nvim_lsp = require("lspconfig") keymap = utils.map opt = utils.opt local function custom_on_init() print("Language Server Protocol started!") end local function custom_root_dir() if (string.find(vim.fn.expand("%f"), "node_modules/") == nil) then return nvim_lsp.util.root_pattern(".git") end return nil end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true nvim_lsp.vimls.setup {} --must have run: npm install -g typescript nvim_lsp.tsserver.setup { -- This makes sure tsserver is not used for formatting -- on_attach = nvim_lsp.tsserver_on_attach, on_attach = function(client) if client.config.flags then client.config.flags.allow_incremental_sync = true end client.resolved_capabilities.document_formatting = false end, root_dir = nvim_lsp.util.root_pattern("tsconfig.json", ".git"), cmd = { "typescript-language-server", "--tsserver-log-file", vim.env.HOME .. "/src/tsserver.log", "--tsserver-log-verbosity", "verbose", "--stdio" }, settings = {documentFormatting = false}, on_init = custom_on_init } --must run: npm install -g pyright nvim_lsp.pyright.setup { on_init = custom_on_init } nvim_lsp.rust_analyzer.setup { on_init = custom_on_init, settings = { ["rust-analyzer"] = { assist = { importMergeBehavior = "last", importPrefix = "by_self" }, cargo = { loadOutDirsFromCheck = true }, procMacro = { enable = true } } } } vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = true, signs = true, update_in_insert = true } ) -- npm i -g vscode-css-languageserver-bin nvim_lsp.cssls.setup { on_init = custom_on_init } -- npm i -g vscode-html-languageserver-bin nvim_lsp.html.setup { on_init = custom_on_init, capabilities = capabilities } local eslint_d = { lintCommand = "eslint_d --stdin --fix-to-stdout --stdin-filename ${INPUT}", lintIgnoreExitCode = true, lintStdin = true, lintFormats = {"%f:%l:%c: %m"}, formatCommand = "eslint_d --fix-to-stdout --stdin --stdin-filename ${INPUT}", formatStdin = true } local rustExe = "rustfmt" local rustArgs = "--emit=stdout" local rustStdin = true local rustfmt = { formatCommand = rustExe .. rustArgs .. "${INPUT}", formatStdin = rustStdin } local prettierArgs = {"--stdin", "--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"} local prettier = { formatCommand = "./node_modules/.bin/prettier" .. table.concat(prettierArgs, " "), formatStdin = true } local languages = { typescript = {prettier, eslint_d}, javascript = {prettier, eslint_d}, typescriptreact = {prettier, eslint_d}, ["typescript.tsx"] = {prettier, eslint_d}, javascriptreact = {prettier, eslint_d}, ["javascript.jsx"] = {prettier, eslint_d}, yaml = {prettier}, json = {prettier}, html = {prettier}, scss = {prettier}, css = {prettier}, markdown = {prettier}, rust = {rustfmt}, python = { { formatCommand = "black", formatStdin = true }, { formatCommand = "isort", formatStdin = true } } } nvim_lsp.efm.setup { init_options = {documentFormatting = true}, filetypes = vim.tbl_keys(languages), root_dir = custom_root_dir(), settings = { languages = languages } } require "compe".setup { enabled = true, autocomplete = true, debug = false, min_length = 1, preselect = "enable", throttle_time = 80, source_timeout = 200, incomplete_delay = 400, max_abbr_width = 100, max_kind_width = 100, max_menu_width = 100, documentation = true, source = { path = true, buffer = true, nvim_lsp = true, nvim_lua = true, spell = true } } require("lspsaga").init_lsp_saga( { error_sign = "▊", warn_sign = "▊", hint_sign = "▊", infor_sign = "▊", dianostic_header_icon = "  ", code_action_icon = "", finder_definition_icon = " ", finder_reference_icon = " ", definition_preview_icon = " ", border_style = 1, rename_prompt_prefix = "❱❱", rename_action_keys = { quit = {"<C-c>", "<esc>"}, exec = "<CR>" -- quit can be a table } } ) require("lspkind").init( { with_text = true, symbol_map = { Text = "  ", Method = "  ", Function = "  ", Constructor = "  ", Variable = "[]", Class = "  ", Interface = " 蘒", Module = "  ", Property = "  ", Unit = " 塞 ", Value = "  ", Enum = " 練", Keyword = "  ", Snippet = "  ", Color = "", File = "", Folder = " ﱮ ", EnumMember = "  ", Constant = "  ", Struct = "  " } } ) vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"} opt("o", "completeopt", "menu,menuone,noselect") local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local check_back_space = function() local col = vim.fn.col(".") - 1 if col == 0 or vim.fn.getline("."):sub(col, col):match("%s") then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif check_back_space() then return t "<Tab>" else return vim.fn["compe#complete"]() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" else return t "<S-Tab>" end end keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true}) keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true}) keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) keymap("n", "gd", ":lua vim.lsp.buf.definition()<CR>", {silent = true}) keymap("n", "gR", ":Lspsaga rename<CR>") keymap("n", "gr", "LspTrouble lsp_references", {cmd_cr = true}) keymap("n", "gs", ":Lspsaga signature_help<CR>") keymap("n", "<leader>e", ":Lspsaga diagnostic_jump_next<CR>", {silent = true}) keymap("n", "<leader>cd", ":Lspsaga show_line_diagnostics<CR>", {silent = true}) keymap("n", "K", ":Lspsaga hover_doc<CR>", {silent = true}) keymap("i", "<C-Space>", "compe#complete()", {silent = true, expr = true}) keymap("i", "<CR>", 'compe#confirm("<CR>")', {silent = true, expr = true})
Fix eslint?
Fix eslint?
Lua
mit
gblock0/dotfiles
1dce70b5db66de100de18c5d0aa90e86c6278faa
core/hyphenator-liang.lua
core/hyphenator-liang.lua
local function addPattern(h, p) local t = h.trie; for char in p:gmatch('%D') do if not(t[char]) then t[char] = {} end t = t[char] end t["_"] = {}; local lastWasDigit = 0 for char in p:gmatch('.') do if char:find("%d") then lastWasDigit = 1 table.insert(t["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(t["_"], 0) end end end function loadPatterns(h, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language]; if not (languageset) then print("No patterns for language "..language) return end for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end if not languageset.exceptions then languageset.exceptions = {} end for _,exc in pairs(languageset.exceptions) do local k = exc:gsub("-", "") h.exceptions[k] = { 0 } for i in exc:gmatch(".") do table.insert(h.exceptions[k], i == "-" and 1 or 0) end end end function _hyphenate(self, w) if string.len(w) < self.minWord then return {w} end local points = self.exceptions[w:lower()] local word = {} for i in w:gmatch(".") do table.insert(word, i) end if not points then points = SU.map(function()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local t = self.trie for j = i, #work do if not t[work[j]] then break end t = t[work[j]] local p = t["_"] if p then for k = 1, #p do if points[i+k - 2] and points[i+k -2] < p[k] then points[i+k -2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1,self.leftmin do points[i] = 0 end for i = #points-self.rightmin,#points do points[i] = 0 end end local pieces = {""} for i = 1,#word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {}; _hyphenators = {}; local hyphenateNode = function(n) if not n:isNnode() or not n.text then return {n} end if not _hyphenators[n.language] then _hyphenators[n.language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} }; loadPatterns(_hyphenators[n.language], n.language) end local breaks = _hyphenate(_hyphenators[n.language],n.text); if #breaks > 1 then local newnodes = {} for j, b in ipairs(breaks) do if not(b=="") then for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do nn.parent = n table.insert(newnodes, nn) end if not (j == #breaks) then d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes("-", n.options) }) d.parent = n table.insert(newnodes, d) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end n.children = newnodes n.hyphenated = false n.done = false return newnodes end return {n} end SILE.hyphenate = function (nodelist) local newlist = {} for i = 1,#nodelist do local n = nodelist[i] local newnodes = hyphenateNode(n) for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end end return newlist end
local function addPattern(h, p) local t = h.trie; for char in p:gmatch('%D') do if not(t[char]) then t[char] = {} end t = t[char] end t["_"] = {}; local lastWasDigit = 0 for char in p:gmatch('.') do if char:find("%d") then lastWasDigit = 1 table.insert(t["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(t["_"], 0) end end end function loadPatterns(h, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language]; if not (languageset) then print("No patterns for language "..language) return end for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end if not languageset.exceptions then languageset.exceptions = {} end for _,exc in pairs(languageset.exceptions) do local k = exc:gsub("-", "") h.exceptions[k] = { 0 } for i in exc:gmatch(".") do table.insert(h.exceptions[k], i == "-" and 1 or 0) end end end function _hyphenate(self, w) if string.len(w) < self.minWord then return {w} end local points = self.exceptions[w:lower()] local word = {} for i in w:gmatch(".") do table.insert(word, i) end if not points then points = SU.map(function()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local t = self.trie for j = i, #work do if not t[work[j]] then break end t = t[work[j]] local p = t["_"] if p then for k = 1, #p do if points[i+k - 2] and points[i+k -2] < p[k] then points[i+k -2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1,self.leftmin do points[i] = 0 end for i = #points-self.rightmin,#points do points[i] = 0 end end local pieces = {""} for i = 1,#word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {}; _hyphenators = {}; local hyphenateNode = function(n) if not n:isNnode() or not n.text then return {n} end if not _hyphenators[n.language] then _hyphenators[n.language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} }; loadPatterns(_hyphenators[n.language], n.language) end local breaks = _hyphenate(_hyphenators[n.language],n.text); if #breaks > 1 then local newnodes = {} for j, b in ipairs(breaks) do if not(b=="") then for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do if nn:isNnode() then nn.parent = n table.insert(newnodes, nn) end end if not (j == #breaks) then d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes("-", n.options) }) d.parent = n table.insert(newnodes, d) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end n.children = newnodes n.hyphenated = false n.done = false return newnodes end return {n} end SILE.hyphenate = function (nodelist) local newlist = {} for i = 1,#nodelist do local n = nodelist[i] local newnodes = hyphenateNode(n) for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end end return newlist end
Subtle ICU bug - ICU inserts penalties around hyphens, which inhibits hyphenation!
Subtle ICU bug - ICU inserts penalties around hyphens, which inhibits hyphenation!
Lua
mit
alerque/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile,neofob/sile,simoncozens/sile,neofob/sile,neofob/sile
4f3b4fdb2b4af23054ee52c0079c22a59f1e0f34
applications/luci-radvd/luasrc/model/cbi/radvd.lua
applications/luci-radvd/luasrc/model/cbi/radvd.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) if m.uci:get("radvd", section) == "interface" then local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) end return m
applications/luci-radvd: fix removal of section in overview page
applications/luci-radvd: fix removal of section in overview page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6530 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
4660927ca0276c099737f61e50d54a9089b003e9
worldedit_commands/safe.lua
worldedit_commands/safe.lua
local safe_region_callback local safe_region_name local safe_region_param check_region = function(name, param) --obtain positions local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "no region selected") return nil end return worldedit.volume(pos1, pos2) end --`callback` is a callback to run when the user confirms --`nodes_needed` is a function accepting `param`, `pos1`, and `pos2` to calculate the number of nodes needed safe_region = function(callback, nodes_needed) --default node volume calculation nodes_needed = nodes_needed or check_region return function(name, param) --check if the operation applies to a safe number of nodes local count = nodes_needed(name, param) if count == nil then return end --invalid command if count < 10000 then return callback(name, param) end --save callback to call later safe_region_callback, safe_region_name, safe_region_param = callback, name, param worldedit.player_notify(name, "WARNING: this operation could affect up to " .. count .. " nodes; type //y to continue or //n to cancel") end end minetest.register_chatcommand("/y", { params = "", description = "Confirm a pending operation", func = function() local callback, name, param = safe_region_callback, safe_region_name, safe_region_param if not callback then worldedit.player_notify(name, "no operation pending") return end --obtain positions local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "no region selected") return end safe_region_callback, safe_region_name, safe_region_param = nil, nil, nil --reset pending operation callback(name, param, pos1, pos2) end, }) minetest.register_chatcommand("/n", { params = "", description = "Confirm a pending operation", func = function() if not safe_region_callback then worldedit.player_notify(name, "no operation pending") return end safe_region_callback, safe_region_name, safe_region_param = nil, nil, nil end, })
local safe_region_callback = {} local safe_region_param = {} check_region = function(name, param) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] --obtain positions if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "no region selected") return nil end return worldedit.volume(pos1, pos2) end --`callback` is a callback to run when the user confirms --`nodes_needed` is a function accepting `param`, `pos1`, and `pos2` to calculate the number of nodes needed safe_region = function(callback, nodes_needed) --default node volume calculation nodes_needed = nodes_needed or check_region return function(name, param) --check if the operation applies to a safe number of nodes local count = nodes_needed(name, param) if count == nil then return end --invalid command if count < 10000 then return callback(name, param) end --save callback to call later safe_region_callback[name], safe_region_param[name] = callback, param worldedit.player_notify(name, "WARNING: this operation could affect up to " .. count .. " nodes; type //y to continue or //n to cancel") end end minetest.register_chatcommand("/y", { params = "", description = "Confirm a pending operation", func = function(name) local callback, param = safe_region_callback[name], safe_region_param[name] if not callback then worldedit.player_notify(name, "no operation pending") return end --obtain positions local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "no region selected") return end safe_region_callback[name], safe_region_param[name] = nil, nil --reset pending operation callback(name, param, pos1, pos2) end, }) minetest.register_chatcommand("/n", { params = "", description = "Confirm a pending operation", func = function(name) if not safe_region_callback[name] then worldedit.player_notify(name, "no operation pending") return end safe_region_callback[name], safe_region_param[name] = nil, nil end, })
Fix safe region functionality (thanks ChaosWormz).
Fix safe region functionality (thanks ChaosWormz).
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
c3ddeb9d7a71c7bcbdfb6e4ec8dae81b67388d50
Tools/premake.lua
Tools/premake.lua
-- premake5.lua newoption { trigger = "with-renderdoc", description = "Include support for RenderDoc." } workspace "MitchEngine" configurations { "Debug", "Release", "Debug Editor", "Release Editor" } startproject "MitchGame" location "../" includedirs { "../MitchEngine/Source", "../ThirdParty/AssIMP/include", "../ThirdParty/Bullet/src", "../ThirdParty/GLAD/include/", "../ThirdParty/GLAD/src/", "../ThirdParty/GLM/glm", "../ThirdParty/GLFW/include", "../ThirdParty/STB", "C:/Program Files/RenderDoc" } links { "glfw3", "opengl32" } filter "configurations:Debug*" defines { "DEBUG" } symbols "On" links { "BulletDynamics_Debug", "BulletCollision_Debug", "LinearMath_Debug" } libdirs { "../ThirdParty/GLFW/src/Debug", "../ThirdParty/GLFW/src/src/Debug", "../ThirdParty/Bullet/lib/Debug" } filter "configurations:Release*" defines { "NDEBUG" } optimize "On" links { "BulletDynamics", "BulletCollision", "LinearMath" } libdirs { "../ThirdParty/GLFW/src/Release", "../ThirdParty/GLFW/src/src/Release", "../ThirdParty/Bullet/lib/Release" } filter "configurations:*Editor" defines { "MAN_EDITOR=1" } filter {} group "Engine" project "MitchEngine" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" location "../MitchEngine" pchheader "PCH.h" pchsource "../MitchEngine/Source/PCH.cpp" links { "LibAssIMP" } files { "../MitchEngine/Assets/**.*", "../MitchEngine/**.h", "../MitchEngine/**.cpp", "../MitchEngine/**.txt", "../Tools/**.lua" } vpaths { ["Build"] = "../Tools/*.lua" } configuration "with-renderdoc" defines { "MAN_ENABLE_RENDERDOC" } postbuildcommands { "xcopy /y /d \"C:\\Program Files\\RenderDoc\\renderdoc.dll\" \"$(ProjectDir)$(OutDir)\"" } filter "configurations:Debug*" postbuildcommands { "xcopy /y /d \"..\\ThirdParty\\AssIMP\\bin\\Debug\\*.dll\" \"$(ProjectDir)$(OutDir)\"", } filter "configurations:Release*" postbuildcommands { "xcopy /y /d \"..\\ThirdParty\\AssIMP\\bin\\Release\\*.dll\" \"$(ProjectDir)$(OutDir)\"", } group "Games" project "MitchGame" kind "ConsoleApp" language "C++" targetdir "../Build/%{cfg.buildcfg}" location "../MitchGame" links "MitchEngine" files { "../MitchGame/Assets/**.frag", "../MitchGame/Assets/**.vert", "../MitchGame/**.h", "../MitchGame/**.cpp" } includedirs { "../MitchGame/Source", "." } filter "configurations:Debug Editor" configuration "Debug" group "Engine/ThirdParty" externalproject "glfw" location "../ThirdParty/GLFW/src" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802C" kind "StaticLib" language "C++" toolset "v141" targetdir "../Build/%{cfg.buildcfg}" filter "configurations:Debug Editor" configuration "Debug" group "Engine/ThirdParty/Bullet" externalproject "LibBulletCollision" location "../ThirdParty/Bullet/src/BulletCollision" filename "BulletCollision" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802D" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibLinearMath" location "../ThirdParty/Bullet/src/LinearMath" filename "LinearMath" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802E" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibBulletDynamics" location "../ThirdParty/Bullet/src/BulletDynamics" filename "BulletDynamics" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802F" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" group "Engine/ThirdParty/Assimp" externalproject "LibAssIMP" location "../ThirdParty/AssIMP/code" filename "Assimp" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58021" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibAssimpIrrXML" location "../ThirdParty/AssIMP/contrib/irrXML" filename "irrXML" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58022" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibAssimpZLibStatic" location "../ThirdParty/AssIMP/contrib/zlib" filename "zlibstatic" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58023" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}"
-- premake5.lua newoption { trigger = "with-renderdoc", description = "Include support for RenderDoc." } workspace "MitchEngine" configurations { "Debug", "Release", "Debug Editor", "Release Editor" } startproject "MitchGame" location "../" includedirs { "../MitchEngine/Source", "../ThirdParty/AssIMP/include", "../ThirdParty/Bullet/src", "../ThirdParty/GLAD/include/", "../ThirdParty/GLAD/src/", "../ThirdParty/GLM/glm", "../ThirdParty/GLFW/include", "../ThirdParty/STB", "C:/Program Files/RenderDoc" } links { "opengl32", "glfw3dll" } filter "configurations:Debug*" defines { "DEBUG" } symbols "On" links { "BulletDynamics_Debug", "BulletCollision_Debug", "LinearMath_Debug" } libdirs { "../ThirdParty/Bullet/lib/Debug", "../ThirdParty/GLFW/src/Debug" } filter "configurations:Release*" defines { "NDEBUG" } optimize "On" links { "BulletDynamics", "BulletCollision", "LinearMath" } libdirs { "../ThirdParty/Bullet/lib/Release", "../ThirdParty/GLFW/src/Release" } filter "configurations:*Editor" defines { "MAN_EDITOR=1" } filter {} group "Engine" project "MitchEngine" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" location "../MitchEngine" pchheader "PCH.h" pchsource "../MitchEngine/Source/PCH.cpp" links { "LibAssIMP" } dependson { "LibAssIMP", "glfw", "LibBulletCollision" } files { "../MitchEngine/Assets/**.*", "../MitchEngine/**.h", "../MitchEngine/**.cpp", "../MitchEngine/**.txt", "../Tools/**.lua" } vpaths { ["Build"] = "../Tools/*.lua" } configuration "with-renderdoc" defines { "MAN_ENABLE_RENDERDOC" } postbuildcommands { "xcopy /y /d \"C:\\Program Files\\RenderDoc\\renderdoc.dll\" \"$(ProjectDir)$(OutDir)\"" } filter "configurations:Debug*" postbuildcommands { "xcopy /y /d \"..\\ThirdParty\\AssIMP\\bin\\Debug\\*.dll\" \"$(ProjectDir)$(OutDir)\"", "xcopy /y /d \"..\\ThirdParty\\GLFW\\src\\Debug\\*.dll\" \"$(ProjectDir)$(OutDir)\"" } filter "configurations:Release*" postbuildcommands { "xcopy /y /d \"..\\ThirdParty\\AssIMP\\bin\\Release\\*.dll\" \"$(ProjectDir)$(OutDir)\"", "xcopy /y /d \"..\\ThirdParty\\GLFW\\src\\Debug\\*.dll\" \"$(ProjectDir)$(OutDir)\"" } group "Games" project "MitchGame" kind "ConsoleApp" language "C++" targetdir "../Build/%{cfg.buildcfg}" location "../MitchGame" links "MitchEngine" files { "../MitchGame/Assets/**.frag", "../MitchGame/Assets/**.vert", "../MitchGame/**.h", "../MitchGame/**.cpp" } includedirs { "../MitchGame/Source", "." } filter "configurations:Debug Editor" configuration "Debug" group "Engine/ThirdParty" externalproject "glfw" location "../ThirdParty/GLFW/src" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802C" kind "SharedLib" language "C++" toolset "v141" targetdir "../Build/%{cfg.buildcfg}" filter "configurations:Debug Editor" configuration "Debug" group "Engine/ThirdParty/Bullet" externalproject "LibBulletCollision" location "../ThirdParty/Bullet/src/BulletCollision" filename "BulletCollision" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802D" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibLinearMath" location "../ThirdParty/Bullet/src/LinearMath" filename "LinearMath" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802E" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibBulletDynamics" location "../ThirdParty/Bullet/src/BulletDynamics" filename "BulletDynamics" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D5802F" kind "StaticLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" group "Engine/ThirdParty/Assimp" externalproject "LibAssIMP" location "../ThirdParty/AssIMP/code" filename "Assimp" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58021" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibAssimpIrrXML" location "../ThirdParty/AssIMP/contrib/irrXML" filename "irrXML" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58022" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}" externalproject "LibAssimpZLibStatic" location "../ThirdParty/AssIMP/contrib/zlib" filename "zlibstatic" uuid "8A0313E9-F6C0-4C24-9258-65C9F6D58023" kind "SharedLib" language "C++" targetdir "../Build/%{cfg.buildcfg}"
GLFW as a DLL and Hopefully fixing the build issues
GLFW as a DLL and Hopefully fixing the build issues
Lua
mit
wobbier/MitchEngine,wobbier/MitchEngine,wobbier/MitchEngine,wobbier/MitchEngine,wobbier/MitchEngine
d74d26f40f06fe0b60c835c81492160507c6d8b4
test_scripts/Polices/Policy_Table_Update/018_ATF_P_TC_Sending_PTS_to_mobile_application.lua
test_scripts/Polices/Policy_Table_Update/018_ATF_P_TC_Sending_PTS_to_mobile_application.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Sending PTS to mobile application -- [HMI API] SystemRequest request/response -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- 2. Performed steps -- HMI->SDL:BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID) -- -- Expected result: -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Sending_PTS_to_mobile_application() local is_test_fail = false local endpoints = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil} end end if #endpoints==0 then self:FailTestCase("Problem with accessing in Policy table snapshot. Value not exists") end local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", url = endpoints[1].url, appID = endpoints[1].appID }) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON", url = {endpoints[1].url}} ) end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Sending PTS to mobile application -- [HMI API] SystemRequest request/response -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- 2. Performed steps -- HMI->SDL:BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID) -- -- Expected result: -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local mobile_session = require("mobile_session") local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("user_modules/connecttest_resumption") require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:ConnectMobile() self:connectMobile() end function Test:StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end function Test:RAI() local corId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) :Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Times(0) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.registerAppInterfaceParams.appName } }) :Do( function(_, d1) self.applications[config.application1.registerAppInterfaceParams.appID] = d1.params.application.appID end) self.mobileSession:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) :Do( function() self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" }) self.mobileSession:ExpectNotification("OnPermissionsChange") :Times(1) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Trigger_getting_device_consent() local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appID] }) EXPECT_HMIRESPONSE(requestId1) :Do( function(_, d1) if d1.result.isSDLAllowed ~= true then local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", { language = "EN-US", messageCodes = { "DataConsent" } }) EXPECT_HMIRESPONSE(requestId2) :Do( function() self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", { allowed = true, source = "GUI", device = { id = config.deviceMAC, name = "127.0.0.1" } }) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do( function(_, d2) self.hmiConnection:SendResponse(d2.id,"BasicCommunication.ActivateApp", "SUCCESS", { }) self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", audioStreamingState = "AUDIBLE", systemContext = "MAIN" }) end) end) end end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }):Times(2) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do( function(_, d) self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { }) local requestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(requestId) :Do( function() local policy_file_name = "PolicyTableUpdate" self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = policy_file_name }) self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) end) end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues after clarification
Fix issues after clarification
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
78817b81b7d6a77d20c44519a46df9ff56862bd7
share/lua/website/gaskrank.lua
share/lua/website/gaskrank.lua
-- libquvi-scripts -- Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "gaskrank%.tv" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/tv/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "gaskrank" local p = quvi.fetch(self.page_url) self.title = p:match('"og:title" content="(.-)"') or error("no match: media title") self.title = self.title:gsub('Video', '') self.id = p:match('unit_long(.-)"') or error("no match: media id") self.url = {p:match('file=(.-)"') or error ("no match: media url")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "gaskrank%.tv" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/tv/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "gaskrank" local p = quvi.fetch(self.page_url) self.title = p:match('"og:title" content="(.-)"') or error("no match: media title") self.title = self.title:gsub('Video', '') self.id = self.page_url:match("%-(%d+)%.h") or error("no match: media ID") self.url = {p:match('file:%s+"(.-)"') or error("no match: media stream URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: gaskrank.lua: stream URL, ID patterns
FIX: gaskrank.lua: stream URL, ID patterns Update the patterns for media stream URL and ID, reflecting the recent changes made to the website.
Lua
agpl-3.0
alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts
1a353ec8d97381582d1de88e6b6dc2f879c89633
mod_compat_vcard/mod_compat_vcard.lua
mod_compat_vcard/mod_compat_vcard.lua
-- Compatibility with clients and servers (i.e. ejabberd) that send vcard -- requests to the full JID -- -- https://support.process-one.net/browse/EJAB-1045 local jid_bare = require "util.jid".bare; local st = require "util.stanza"; local core_process_stanza = prosody.core_process_stanza; module:hook("iq/full", function(event) local stanza = event.stanza; local payload = stanza.tags[1]; if payload.name == "vCard" and stanza.attr.type == "get" and payload.attr.xmlns == "vcard-temp" then local fixed_stanza = st.clone(event.stanza); fixed_stanza.attr.to = jid_bare(stanza.attr.to); core_process_stanza(event.origin, fixed_stanza); return true; end end, 1);
-- Compatibility with clients and servers (i.e. ejabberd) that send vcard -- requests to the full JID -- -- https://support.process-one.net/browse/EJAB-1045 local jid_bare = require "util.jid".bare; local st = require "util.stanza"; local core_process_stanza = prosody.core_process_stanza; module:hook("iq/full", function(event) local stanza = event.stanza; local payload = stanza.tags[1]; if payload and stanza.attr.type == "get" and payload.name == "vCard" and payload.attr.xmlns == "vcard-temp" then local fixed_stanza = st.clone(event.stanza); fixed_stanza.attr.to = jid_bare(stanza.attr.to); core_process_stanza(event.origin, fixed_stanza); return true; end end, 1);
mod_compat_vcard: Fix traceback from probably empty stanzas (Thanks Biszkopcik)
mod_compat_vcard: Fix traceback from probably empty stanzas (Thanks Biszkopcik)
Lua
mit
mardraze/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,Craige/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,either1/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,apung/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,prosody-modules/import,BurmistrovJ/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,apung/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,1st8/prosody-modules,olax/prosody-modules,softer/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules
34dce43012fa2394aaffaed832e8bed22e0be892
gumbo/ffi-parse.lua
gumbo/ffi-parse.lua
--[[ LuaJIT FFI bindings for the Gumbo HTML5 parsing library. Copyright (c) 2013-2014 Craig Barnes Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ]] local ffi = require "ffi" local C = require "gumbo.ffi-cdef" local Document = require "gumbo.dom.Document" local Element = require "gumbo.dom.Element" local Attr = require "gumbo.dom.Attr" local Text = require "gumbo.dom.Text" local Comment = require "gumbo.dom.Comment" local NodeList = require "gumbo.dom.NodeList" local NamedNodeMap = require "gumbo.dom.NamedNodeMap" local GumboStringPiece = ffi.typeof "GumboStringPiece" local have_tnew, tnew = pcall(require, "table.new") local createtable = have_tnew and tnew or function() return {} end local cstring, cast, new = ffi.string, ffi.cast, ffi.new local tonumber, setmetatable, format = tonumber, setmetatable, string.format local function oob(t, k) error(format("Index out of bounds: %s", k), 2) end local function LookupTable(t) return setmetatable(t, {__index = oob}) end local w3 = "http://www.w3.org/" local tagnsmap = LookupTable{w3.."2000/svg", w3.."1998/Math/MathML"} local attrnsmap = LookupTable{"xlink", "xml", "xmlns"} local quirksmap = LookupTable{[0] = "no-quirks", "quirks", "limited-quirks"} local create_node local function get_attributes(attrs) local length = attrs.length if length > 0 then local t = createtable(length, length) for i = 0, length - 1 do local attr = cast("GumboAttribute*", attrs.data[i]) local name = cstring(attr.name) local a = { name = name, value = cstring(attr.value), line = attr.name_start.line, column = attr.name_start.column, offset = attr.name_start.offset } if attr.attr_namespace ~= C.GUMBO_ATTR_NAMESPACE_NONE then a.prefix = attrnsmap[tonumber(attr.attr_namespace)] end t[i+1] = setmetatable(a, Attr) t[name] = a end return setmetatable(t, NamedNodeMap) end end local function get_tag_name(element) if element.tag_namespace == C.GUMBO_NAMESPACE_SVG then local original_tag = GumboStringPiece(element.original_tag) C.gumbo_tag_from_original_text(original_tag) local normalized = C.gumbo_normalize_svg_tagname(original_tag) if normalized ~= nil then return cstring(normalized) end end if element.tag == C.GUMBO_TAG_UNKNOWN then local original_tag = GumboStringPiece(element.original_tag) C.gumbo_tag_from_original_text(original_tag) local tag = cstring(original_tag.data, tonumber(original_tag.length)) return tag:lower() else return cstring(C.gumbo_normalized_tagname(element.tag)) end end local function add_children(parent, children) local length = children.length if length > 0 then local childNodes = createtable(length, 0) for i = 0, length - 1 do local node = create_node(cast("GumboNode*", children.data[i])) node.parentNode = parent childNodes[i+1] = node end parent.childNodes = setmetatable(childNodes, NodeList) end end local function create_document(node) local document = node.v.document local t = { quirksMode = quirksmap[tonumber(document.doc_type_quirks_mode)] } if document.has_doctype then t.doctype = { name = cstring(document.name), publicId = cstring(document.public_identifier), systemId = cstring(document.system_identifier) } end add_children(t, document.children) return setmetatable(t, Document) end local function create_element(node) local element = node.v.element local t = { localName = get_tag_name(element), attributes = get_attributes(element.attributes), line = element.start_pos.line, column = element.start_pos.column, offset = element.start_pos.offset } if element.tag_namespace ~= C.GUMBO_NAMESPACE_HTML then t.namespaceURI = tagnsmap[tonumber(element.tag_namespace)] end local parseFlags = tonumber(node.parse_flags) if parseFlags ~= 0 then t.parseFlags = parseFlags end add_children(t, element.children) return setmetatable(t, Element) end local function make_text(node) local text = node.v.text return { data = cstring(text.text), line = text.start_pos.line, column = text.start_pos.column, offset = text.start_pos.offset } end local function create_text(node) local n = make_text(node) return setmetatable(n, Text) end local function create_cdata(node) local n = make_text(node) n.type = "cdata" return setmetatable(n, Text) end local function create_whitespace(node) local n = make_text(node) n.type = "whitespace" return setmetatable(n, Text) end local function create_comment(node) local n = make_text(node) return setmetatable(n, Comment) end local typemap = LookupTable { create_element, create_text, create_cdata, create_comment, create_whitespace, } create_node = function(node) return typemap[tonumber(node.type)](node) end local function parse(input, tab_stop) assert(type(input) == "string") assert(type(tab_stop) == "number" or tab_stop == nil) local options = new("GumboOptions", C.kGumboDefaultOptions) options.tab_stop = tab_stop or 8 local output = C.gumbo_parse_with_options(options, input, #input) local document = create_document(output.document) local rootIndex = tonumber(output.root.index_within_parent) + 1 document.documentElement = document.childNodes[rootIndex] C.gumbo_destroy_output(options, output) return document end return parse
--[[ LuaJIT FFI bindings for the Gumbo HTML5 parsing library. Copyright (c) 2013-2014 Craig Barnes Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ]] local ffi = require "ffi" local C = require "gumbo.ffi-cdef" local Document = require "gumbo.dom.Document" local Element = require "gumbo.dom.Element" local Attr = require "gumbo.dom.Attr" local Text = require "gumbo.dom.Text" local Comment = require "gumbo.dom.Comment" local NodeList = require "gumbo.dom.NodeList" local NamedNodeMap = require "gumbo.dom.NamedNodeMap" local GumboStringPiece = ffi.typeof "GumboStringPiece" local have_tnew, tnew = pcall(require, "table.new") local createtable = have_tnew and tnew or function() return {} end local cstring, cast, new = ffi.string, ffi.cast, ffi.new local tonumber, setmetatable, format = tonumber, setmetatable, string.format local function oob(t, k) error(format("Index out of bounds: %s", k), 2) end local function LookupTable(t) return setmetatable(t, {__index = oob}) end local w3 = "http://www.w3.org/" local tagnsmap = LookupTable{w3.."2000/svg", w3.."1998/Math/MathML"} local attrnsmap = LookupTable{"xlink", "xml", "xmlns"} local quirksmap = LookupTable{[0] = "no-quirks", "quirks", "limited-quirks"} local create_node local function get_attributes(attrs) local length = attrs.length if length > 0 then local t = createtable(length, length) for i = 0, length - 1 do local attr = cast("GumboAttribute*", attrs.data[i]) local name = cstring(attr.name) local a = { name = name, value = cstring(attr.value), line = attr.name_start.line, column = attr.name_start.column, offset = attr.name_start.offset } if attr.attr_namespace ~= C.GUMBO_ATTR_NAMESPACE_NONE then a.prefix = attrnsmap[tonumber(attr.attr_namespace)] end t[i+1] = setmetatable(a, Attr) t[name] = a end return setmetatable(t, NamedNodeMap) end end local function get_tag_name(element) if element.tag_namespace == C.GUMBO_NAMESPACE_SVG then local original_tag = GumboStringPiece(element.original_tag) C.gumbo_tag_from_original_text(original_tag) local normalized = C.gumbo_normalize_svg_tagname(original_tag) if normalized ~= nil then return cstring(normalized) end end if element.tag == C.GUMBO_TAG_UNKNOWN then local original_tag = GumboStringPiece(element.original_tag) C.gumbo_tag_from_original_text(original_tag) local tag = cstring(original_tag.data, tonumber(original_tag.length)) return tag:lower() else return cstring(C.gumbo_normalized_tagname(element.tag)) end end local function add_children(parent, children) local length = children.length if length > 0 then local childNodes = createtable(length, 0) for i = 0, length - 1 do local node = create_node(cast("GumboNode*", children.data[i])) node.parentNode = parent childNodes[i+1] = node end parent.childNodes = setmetatable(childNodes, NodeList) end end local function create_document(node, rootIndex) local document = node.v.document local t = { quirksMode = quirksmap[tonumber(document.doc_type_quirks_mode)] } if document.has_doctype then t.doctype = { name = cstring(document.name), publicId = cstring(document.public_identifier), systemId = cstring(document.system_identifier) } end add_children(t, document.children) t.documentElement = assert(t.childNodes[rootIndex]) return setmetatable(t, Document) end local function create_element(node) local element = node.v.element local t = { localName = get_tag_name(element), attributes = get_attributes(element.attributes), line = element.start_pos.line, column = element.start_pos.column, offset = element.start_pos.offset } if element.tag_namespace ~= C.GUMBO_NAMESPACE_HTML then t.namespaceURI = tagnsmap[tonumber(element.tag_namespace)] end local parseFlags = tonumber(node.parse_flags) if parseFlags ~= 0 then t.parseFlags = parseFlags end add_children(t, element.children) return setmetatable(t, Element) end local function make_text(node) local text = node.v.text return { data = cstring(text.text), line = text.start_pos.line, column = text.start_pos.column, offset = text.start_pos.offset } end local function create_text(node) local n = make_text(node) return setmetatable(n, Text) end local function create_cdata(node) local n = make_text(node) n.type = "cdata" return setmetatable(n, Text) end local function create_whitespace(node) local n = make_text(node) n.type = "whitespace" return setmetatable(n, Text) end local function create_comment(node) local n = make_text(node) return setmetatable(n, Comment) end local typemap = LookupTable { create_element, create_text, create_cdata, create_comment, create_whitespace, } create_node = function(node) return typemap[tonumber(node.type)](node) end local function parse(input, tab_stop) assert(type(input) == "string") assert(type(tab_stop) == "number" or tab_stop == nil) local options = new("GumboOptions", C.kGumboDefaultOptions) options.tab_stop = tab_stop or 8 local output = C.gumbo_parse_with_options(options, input, #input) local rootIndex = assert(tonumber(output.root.index_within_parent)) local document = create_document(output.document, rootIndex + 1) C.gumbo_destroy_output(options, output) return document end return parse
Fix a bug in ffi-parse.lua...
Fix a bug in ffi-parse.lua... Writing to the documentElement field was being ignored because it was done after the Document metatable was already applied and is marked by that metatable as readonly. This commit restructures the code slightly so that the documentElement field is written before setmetatable() is called.
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
827e77afbeba2d387c5a4f10d1436f70e7851775
frontend/readhistory.lua
frontend/readhistory.lua
local lfs = require("libs/libkoreader-lfs") local DataStorage = require("datastorage") local DocSettings = require("docsettings") local realpath = require("ffi/util").realpath local joinPath = require("ffi/util").joinPath local dump = require("dump") local history_file = joinPath(DataStorage:getDataDir(), "history.lua") local ReadHistory = { hist = {}, } local function buildEntry(input_time, input_file) return { time = input_time, text = input_file:gsub(".*/", ""), file = realpath(input_file), callback = function() local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(input_file) end } end local function fileFirstOrdering(l, r) if l.file == r.file then return l.time > r.time else return l.file < r.file end end local function timeFirstOrdering(l, r) if l.time == r.time then return l.file < r.file else return l.time > r.time end end function ReadHistory:_indexing(start) -- TODO(Hzj_jie): Use binary search to find an item when deleting it. for i = start, #self.hist, 1 do self.hist[i].index = i end end function ReadHistory:_sort() table.sort(self.hist, fileFirstOrdering) -- TODO(zijiehe): Use binary insert instead of a loop to deduplicate. for i = #self.hist, 2, -1 do if self.hist[i].file == self.hist[i - 1].file then table.remove(self.hist, i) end end table.sort(self.hist, timeFirstOrdering) self:_indexing(1) end -- Reduces total count in hist list to a reasonable number by removing last -- several items. function ReadHistory:_reduce() while #self.hist > 500 do table.remove(self.hist, #self.hist) end end -- Flushes current history table into file. function ReadHistory:_flush() local content = {} for k, v in pairs(self.hist) do content[k] = { time = v.time, file = v.file } end local f = io.open(history_file, "w") f:write("return " .. dump(content) .. "\n") f:close() end -- Reads history table from file function ReadHistory:_read() local ok, data = pcall(dofile, history_file) if ok and data then for k, v in pairs(data) do table.insert(self.hist, buildEntry(v.time, v.file)) end end end -- Reads history from legacy history folder function ReadHistory:_readLegacyHistory() local history_dir = DataStorage:getHistoryDir() for f in lfs.dir(history_dir) do local path = joinPath(history_dir, f) if lfs.attributes(path, "mode") == "file" then path = DocSettings:getPathFromHistory(f) if path ~= nil and path ~= "" then local file = DocSettings:getNameFromHistory(f) if file ~= nil and file ~= "" then table.insert( self.hist, buildEntry(lfs.attributes(joinPath(history_dir, f), "modification"), joinPath(path, file))) end end end end end function ReadHistory:_init() self:_read() self:_readLegacyHistory() self:_sort() self:_reduce() end function ReadHistory:clearMissing() for i = #self.hist, 1, -1 do if self.hist[i].file == nil or lfs.attributes(self.hist[i].file, "mode") ~= "file" then table.remove(self.hist, i) end end end function ReadHistory:removeItem(item) table.remove(self.hist, item.index) os.remove(DocSettings:getHistoryPath(item.file)) self:_indexing(item.index) self:_flush() end function ReadHistory:addItem(file) if file ~= nil and lfs.attributes(file, "mode") == "file" then table.insert(self.hist, 1, buildEntry(os.time(), file)) -- TODO(zijiehe): We do not need to sort if we can use binary insert and -- binary search. self:_sort() self:_reduce() self:_flush() end end ReadHistory:_init() return ReadHistory
local lfs = require("libs/libkoreader-lfs") local DataStorage = require("datastorage") local DocSettings = require("docsettings") local realpath = require("ffi/util").realpath local joinPath = require("ffi/util").joinPath local dump = require("dump") local history_file = joinPath(DataStorage:getDataDir(), "history.lua") local ReadHistory = { hist = {}, } local function buildEntry(input_time, input_file) return { time = input_time, text = input_file:gsub(".*/", ""), file = realpath(input_file), callback = function() local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(input_file) end } end local function fileFirstOrdering(l, r) if l.file == r.file then return l.time > r.time else return l.file < r.file end end local function timeFirstOrdering(l, r) if l.time == r.time then return l.file < r.file else return l.time > r.time end end function ReadHistory:_indexing(start) -- TODO(Hzj_jie): Use binary search to find an item when deleting it. for i = start, #self.hist, 1 do self.hist[i].index = i end end function ReadHistory:_sort() for i = #self.hist, 1, -1 do if self.hist[i].file == nil then table.remove(self.hist, i) end end table.sort(self.hist, fileFirstOrdering) -- TODO(zijiehe): Use binary insert instead of a loop to deduplicate. for i = #self.hist, 2, -1 do if self.hist[i].file == self.hist[i - 1].file then table.remove(self.hist, i) end end table.sort(self.hist, timeFirstOrdering) self:_indexing(1) end -- Reduces total count in hist list to a reasonable number by removing last -- several items. function ReadHistory:_reduce() while #self.hist > 500 do table.remove(self.hist, #self.hist) end end -- Flushes current history table into file. function ReadHistory:_flush() local content = {} for k, v in pairs(self.hist) do content[k] = { time = v.time, file = v.file } end local f = io.open(history_file, "w") f:write("return " .. dump(content) .. "\n") f:close() end -- Reads history table from file function ReadHistory:_read() local ok, data = pcall(dofile, history_file) if ok and data then for k, v in pairs(data) do table.insert(self.hist, buildEntry(v.time, v.file)) end end end -- Reads history from legacy history folder function ReadHistory:_readLegacyHistory() local history_dir = DataStorage:getHistoryDir() for f in lfs.dir(history_dir) do local path = joinPath(history_dir, f) if lfs.attributes(path, "mode") == "file" then path = DocSettings:getPathFromHistory(f) if path ~= nil and path ~= "" then local file = DocSettings:getNameFromHistory(f) if file ~= nil and file ~= "" then table.insert( self.hist, buildEntry(lfs.attributes(joinPath(history_dir, f), "modification"), joinPath(path, file))) end end end end end function ReadHistory:_init() self:_read() self:_readLegacyHistory() self:_sort() self:_reduce() end function ReadHistory:clearMissing() for i = #self.hist, 1, -1 do if self.hist[i].file == nil or lfs.attributes(self.hist[i].file, "mode") ~= "file" then table.remove(self.hist, i) end end end function ReadHistory:removeItem(item) table.remove(self.hist, item.index) os.remove(DocSettings:getHistoryPath(item.file)) self:_indexing(item.index) self:_flush() end function ReadHistory:addItem(file) if file ~= nil and lfs.attributes(file, "mode") == "file" then table.insert(self.hist, 1, buildEntry(os.time(), file)) -- TODO(zijiehe): We do not need to sort if we can use binary insert and -- binary search. self:_sort() self:_reduce() self:_flush() end end ReadHistory:_init() return ReadHistory
FileManagerHistory: fix loop error
FileManagerHistory: fix loop error
Lua
agpl-3.0
apletnev/koreader,NiLuJe/koreader,houqp/koreader,Frenzie/koreader,NiLuJe/koreader,mwoz123/koreader,robert00s/koreader,Markismus/koreader,Hzj-jie/koreader,mihailim/koreader,Frenzie/koreader,koreader/koreader,pazos/koreader,koreader/koreader,poire-z/koreader,poire-z/koreader,lgeek/koreader
bf83695affcc2e94653d874d41de130b21c4c241
ffi/framebuffer_SDL2_0.lua
ffi/framebuffer_SDL2_0.lua
-- load common SDL input/video library local SDL = require("ffi/SDL2_0") local BB = require("ffi/blitbuffer") local util = require("ffi/util") local framebuffer = { -- this blitbuffer will be used when we use refresh emulation sdl_bb = nil, } function framebuffer:init() if not self.dummy then SDL.open() self:_newBB() else self.bb = BB.new(600, 800) end self.bb:fill(BB.COLOR_WHITE) self:refreshFull() framebuffer.parent.init(self) end function framebuffer:resize(w, h) w = w or SDL.w h = h or SDL.h if not self.dummy then self:_newBB(w, h) SDL.w = w SDL.h = h else self.bb:free() self.bb = BB.new(600, 800) end if SDL.texture then SDL.destroyTexture(SDL.texture) end SDL.texture = SDL.createTexture(w, h) self.bb:fill(BB.COLOR_WHITE) self:refreshFull() end function framebuffer:_newBB(w, h) w = w or SDL.w h = h or SDL.h local inverse if self.sdl_bb then self.sdl_bb:free() end if self.bb then inverse = self.bb:getInverse() == 1 self.bb:free() end if self.invert_bb then self.invert_bb:free() end -- we present this buffer to the outside local bb = BB.new(w, h, BB.TYPE_BBRGB32) local flash = os.getenv("EMULATE_READER_FLASH") if flash then -- in refresh emulation mode, we use a shadow blitbuffer -- and blit refresh areas from it. self.sdl_bb = bb self.bb = BB.new(w, h, BB.TYPE_BBRGB32) else self.bb = bb end self.invert_bb = BB.new(w, h, BB.TYPE_BBRGB32) -- reinit inverse mode on resize if inverse then self.bb:invert() end end function framebuffer:_render(bb, x, y, w, h) w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF) h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF) x, y, w, h = bb:getPhysicalRect(x, y, w, h) if bb:getInverse() == 1 then self.invert_bb:invertblitFrom(bb) bb = self.invert_bb end -- A viewport is a Blitbuffer object that works on a rectangular -- subset of the underlying memory without allocating new memory. local bb_rect = bb:viewport(x, y, w, h) local sdl_rect = SDL.rect(x, y, w, h) SDL.SDL.SDL_UpdateTexture(SDL.texture, sdl_rect, bb_rect.data, bb_rect.pitch) SDL.SDL.SDL_RenderClear(SDL.renderer) SDL.SDL.SDL_RenderCopy(SDL.renderer, SDL.texture, nil, nil) SDL.SDL.SDL_RenderPresent(SDL.renderer) end function framebuffer:refreshFullImp(x, y, w, h) if self.dummy then return end local bb = self.full_bb or self.bb if not (x and y and w and h) then x = 0 y = 0 w = bb:getWidth() h = bb:getHeight() end self.debug("refresh on physical rectangle", x, y, w, h) local flash = os.getenv("EMULATE_READER_FLASH") if flash then self.sdl_bb:invertRect(x, y, w, h) self:_render(self.sdl_bb, x, y, w, h) util.usleep(tonumber(flash)*1000) self.sdl_bb:setRotation(bb:getRotation()) self.sdl_bb:setInverse(bb:getInverse()) self.sdl_bb:blitFrom(bb, x, y, x, y, w, h) end self:_render(bb, x, y, w, h) end function framebuffer:setWindowTitle(new_title) framebuffer.parent.setWindowTitle(self, new_title) SDL.SDL.SDL_SetWindowTitle(SDL.screen, self.window_title) end function framebuffer:setWindowIcon(icon) SDL.setWindowIcon(icon) end function framebuffer:close() SDL.SDL.SDL_Quit() end return require("ffi/framebuffer"):extend(framebuffer)
-- load common SDL input/video library local SDL = require("ffi/SDL2_0") local BB = require("ffi/blitbuffer") local util = require("ffi/util") local framebuffer = { -- this blitbuffer will be used when we use refresh emulation sdl_bb = nil, } function framebuffer:init() if not self.dummy then SDL.open() self:_newBB() else self.bb = BB.new(600, 800) end self.bb:fill(BB.COLOR_WHITE) self:refreshFull() framebuffer.parent.init(self) end function framebuffer:resize(w, h) w = w or SDL.w h = h or SDL.h if not self.dummy then self:_newBB(w, h) SDL.w = w SDL.h = h else self.bb:free() self.bb = BB.new(600, 800) end if SDL.texture then SDL.destroyTexture(SDL.texture) end SDL.texture = SDL.createTexture(w, h) self.bb:fill(BB.COLOR_WHITE) self:refreshFull() end function framebuffer:_newBB(w, h) w = w or SDL.w h = h or SDL.h local rotation local inverse if self.sdl_bb then self.sdl_bb:free() end if self.bb then rotation = self.bb:getRotation() inverse = self.bb:getInverse() == 1 self.bb:free() end if self.invert_bb then self.invert_bb:free() end -- we present this buffer to the outside local bb = BB.new(w, h, BB.TYPE_BBRGB32) local flash = os.getenv("EMULATE_READER_FLASH") if flash then -- in refresh emulation mode, we use a shadow blitbuffer -- and blit refresh areas from it. self.sdl_bb = bb self.bb = BB.new(w, h, BB.TYPE_BBRGB32) else self.bb = bb end self.invert_bb = BB.new(w, h, BB.TYPE_BBRGB32) if rotation then self.bb:setRotation(rotation) end -- reinit inverse mode on resize if inverse then self.bb:invert() end end function framebuffer:_render(bb, x, y, w, h) w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF) h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF) -- x, y, w, h without rotation for SDL rectangle local px, py, pw, ph = bb:getPhysicalRect(x, y, w, h) if bb:getInverse() == 1 then self.invert_bb:invertblitFrom(bb) bb = self.invert_bb end -- A viewport is a Blitbuffer object that works on a rectangular -- subset of the underlying memory without allocating new memory. local bb_rect = bb:viewport(x, y, w, h) local sdl_rect = SDL.rect(px, py, pw, ph) SDL.SDL.SDL_UpdateTexture(SDL.texture, sdl_rect, bb_rect.data, bb_rect.pitch) SDL.SDL.SDL_RenderClear(SDL.renderer) SDL.SDL.SDL_RenderCopy(SDL.renderer, SDL.texture, nil, nil) SDL.SDL.SDL_RenderPresent(SDL.renderer) end function framebuffer:refreshFullImp(x, y, w, h) if self.dummy then return end local bb = self.full_bb or self.bb if not (x and y and w and h) then x = 0 y = 0 w = bb:getWidth() h = bb:getHeight() end self.debug("refresh on physical rectangle", x, y, w, h) local flash = os.getenv("EMULATE_READER_FLASH") if flash then self.sdl_bb:invertRect(x, y, w, h) self:_render(self.sdl_bb, x, y, w, h) util.usleep(tonumber(flash)*1000) self.sdl_bb:setRotation(bb:getRotation()) self.sdl_bb:setInverse(bb:getInverse()) self.sdl_bb:blitFrom(bb, x, y, x, y, w, h) end self:_render(bb, x, y, w, h) end function framebuffer:setWindowTitle(new_title) framebuffer.parent.setWindowTitle(self, new_title) SDL.SDL.SDL_SetWindowTitle(SDL.screen, self.window_title) end function framebuffer:setWindowIcon(icon) SDL.setWindowIcon(icon) end function framebuffer:close() SDL.SDL.SDL_Quit() end return require("ffi/framebuffer"):extend(framebuffer)
[fix] SDL2: resolve rotation issues (#665)
[fix] SDL2: resolve rotation issues (#665) Embarrassingly, I recently introduced two (!) regressions in rotation handling. 1. The new blitbuffer created when resizing didn't take rotation into account. Cf. https://github.com/koreader/koreader-base/pull/614 2. The feature to emulate E Ink refresh didn't properly distinguish between BB rectangles and "physical" SDL rectangles. Cf. https://github.com/koreader/koreader-base/pull/626 Reported by @poire-z in https://github.com/koreader/koreader/pull/3812#issuecomment-386806443
Lua
agpl-3.0
houqp/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader-base,houqp/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,houqp/koreader-base
202e87661746ab8f9375527b77215a7ab26ed165
src/cosy/nginx/init.lua
src/cosy/nginx/init.lua
local Loader = require "cosy.loader" local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" Configuration.load { "cosy.nginx", "cosy.redis", } local i18n = I18n.load "cosy.nginx" i18n._locale = Configuration.locale local Nginx = {} local configuration_template = [[ error_log error.log; pid {{{pidfile}}}; worker_processes 1; events { worker_connections 1024; } http { tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; proxy_temp_path proxy; proxy_cache_path cache keys_zone=foreign:10m; lua_package_path "{{{path}}}"; lua_package_cpath "{{{cpath}}}"; include /etc/nginx/mime.types; gzip on; gzip_min_length 0; gzip_types *; gzip_proxied no-store no-cache private expired auth; server { listen localhost:{{{port}}}; listen {{{host}}}:{{{port}}}; server_name "{{{name}}}"; charset utf-8; index index.html; include /etc/nginx/mime.types; default_type application/octet-stream; access_log access.log; root "{{{www}}}"; location / { add_header Access-Control-Allow-Origin *; index index.html; } location /lua { default_type application/lua; root /; set $target ""; access_by_lua ' local name = ngx.var.uri:match "/lua/(.*)" local filename = package.searchpath (name, "{{{path}}}") if filename then ngx.var.target = filename else ngx.log (ngx.ERR, "failed to locate lua module: " .. name) return ngx.exit (404) end '; try_files $target =404; } location /ws { proxy_pass http://{{{wshost}}}:{{{wsport}}}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /hook { content_by_lua ' local temporary = os.tmpname () local file = io.open (temporary, "w") file:write [==[ git pull --quiet --force luarocks install --local --force --only-deps cosyverif for rock in $(luarocks list --outdated --porcelain | cut -f 1) do luarocks install --local --force ${rock} done rm --force $0 ]==] file:close () os.execute ("bash " .. temporary .. " &") '; } location /upload { limit_except POST { deny all; } client_body_temp_path uploads/; client_body_buffer_size 128K; client_max_body_size 10240K; content_by_lua ' ngx.req.read_body () local redis = require "nginx.redis" :new () local ok, err = redis:connect ("{{{redis_host}}}", {{{redis_port}}}) if not ok then ngx.log (ngx.ERR, "failed to connect to redis: ", err) return ngx.exit (500) end redis:select ({{{redis_database}}}) local id = redis:incr "#upload" local key = "upload:" .. tostring (id) redis:set (key, ngx.req.get_body_data ()) redis:expire (key, 300) ngx.header ["Cosy-Avatar"] = key '; } {{{redirects}}} } } ]] function Nginx.configure () local resolver do local file = io.open "/etc/resolv.conf" if not file then Logger.error { _ = i18n ["nginx:no-resolver"], } end local result = {} for line in file:lines () do local address = line:match "nameserver%s+(%S+)" if address then result [#result+1] = address end end file:close () resolver = table.concat (result, " ") end os.execute ([[ if [ ! -d {{{directory}}} ] then mkdir {{{directory}}} fi if [ ! -d {{{uploads}}} ] then mkdir {{{uploads}}} fi ]] % { directory = Configuration.http.directory, uploads = Configuration.http.uploads , }) local locations = {} for url, remote in pairs (Configuration.dependencies) do if type (remote) == "string" and remote:match "^http" then locations [#locations+1] = [==[ location {{{url}}} { proxy_cache foreign; expires modified 1d; resolver {{{resolver}}}; set $target "{{{remote}}}"; proxy_pass $target$is_args$args; } ]==] % { url = url, remote = remote, resolver = resolver, } end end local configuration = configuration_template % { host = Configuration.http.interface , port = Configuration.http.port , www = Configuration.http.www , uploads = Configuration.http.uploads , pidfile = Configuration.http.pid , name = Configuration.server.name , wshost = Configuration.server.interface, wsport = Configuration.server.port , redis_host = Configuration.redis.interface , redis_port = Configuration.redis.port , redis_database = Configuration.redis.database , path = package.path, cpath = package.cpath, redirects = table.concat (locations, "\n"), } local file = io.open (Configuration.http.configuration, "w") file:write (configuration) file:close () end function Nginx.start () Nginx.stop () Nginx.configure () os.execute ([[ {{{nginx}}} -p {{{directory}}} -c {{{configuration}}} 2>> {{{error}}} ]] % { nginx = Configuration.http.nginx , directory = Configuration.http.directory , configuration = Configuration.http.configuration, error = Configuration.http.error , }) end function Nginx.stop () os.execute ([[ [ -f {{{pidfile}}} ] && { kill -QUIT $(cat {{{pidfile}}}) } ]] % { pidfile = Configuration.http.pid, }) os.execute ([[ rm -rf {{{directory}}} {{{pid}}} {{{error}}} {{{configuration}}} ]] % { pid = Configuration.http.pid, configuration = Configuration.http.configuration, error = Configuration.http.error, directory = Configuration.http.directory, }) Nginx.directory = nil end function Nginx.update () Nginx.configure () os.execute ([[ [ -f {{{pidfile}}} ] && { kill -HUP $(cat {{{pidfile}}}) } ]] % { pidfile = Configuration.http.pid, }) end Loader.hotswap.on_change ["cosy:configuration"] = function () Nginx.update () end return Nginx
local Loader = require "cosy.loader" local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" Configuration.load { "cosy.nginx", "cosy.redis", } local i18n = I18n.load "cosy.nginx" i18n._locale = Configuration.locale local Nginx = {} local configuration_template = [[ error_log error.log; pid {{{pidfile}}}; worker_processes 1; events { worker_connections 1024; } http { tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; proxy_temp_path proxy; proxy_cache_path cache keys_zone=foreign:10m; lua_package_path "{{{path}}}"; lua_package_cpath "{{{cpath}}}"; gzip on; gzip_min_length 0; gzip_types *; gzip_proxied no-store no-cache private expired auth; server { listen localhost:{{{port}}}; listen {{{host}}}:{{{port}}}; server_name "{{{name}}}"; charset utf-8; index index.html; include /etc/nginx/mime.types; default_type application/octet-stream; access_log access.log; location / { add_header Access-Control-Allow-Origin *; root www; index index.html; } location /upload { limit_except POST { deny all; } client_body_in_file_only on; client_body_temp_path uploads/; client_body_buffer_size 128K; client_max_body_size 10240K; proxy_pass_request_headers on; proxy_set_header X-File $request_body_file; proxy_set_body off; proxy_redirect off; proxy_pass http://localhost:{{{port}}}/uploaded; } location /uploaded { content_by_lua ' local file = ngx.var.http_x_file local id = file:match "./uploads/(.*)" ngx.say (id) '; } location /lua { default_type application/lua; root /; set $target ""; access_by_lua ' local name = ngx.var.uri:match "/lua/(.*)" local filename = package.searchpath (name, "{{{path}}}") if filename then ngx.var.target = filename else ngx.log (ngx.ERR, "failed to locate lua module: " .. name) return ngx.exit (404) end '; try_files $target =404; } location /ws { proxy_pass http://{{{wshost}}}:{{{wsport}}}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /hook { content_by_lua ' local temporary = os.tmpname () local file = io.open (temporary, "w") file:write [==[ git pull --quiet --force luarocks install --local --force --only-deps cosyverif for rock in $(luarocks list --outdated --porcelain | cut -f 1) do luarocks install --local --force ${rock} done rm --force $0 ]==] file:close () os.execute ("bash " .. temporary .. " &") '; } {{{redirects}}} } } ]] function Nginx.configure () local resolver do local file = io.open "/etc/resolv.conf" if not file then Logger.error { _ = i18n ["nginx:no-resolver"], } end local result = {} for line in file:lines () do local address = line:match "nameserver%s+(%S+)" if address then result [#result+1] = address end end file:close () resolver = table.concat (result, " ") end os.execute ([[ if [ ! -d {{{directory}}} ] then mkdir {{{directory}}} fi if [ ! -d {{{uploads}}} ] then mkdir {{{uploads}}} fi ]] % { directory = Configuration.http.directory, uploads = Configuration.http.uploads , }) local locations = {} for url, remote in pairs (Configuration.dependencies) do if type (remote) == "string" and remote:match "^http" then locations [#locations+1] = [==[ location {{{url}}} { proxy_cache foreign; expires modified 1d; resolver {{{resolver}}}; set $target "{{{remote}}}"; proxy_pass $target$is_args$args; } ]==] % { url = url, remote = remote, resolver = resolver, } end end local configuration = configuration_template % { host = Configuration.http.interface , port = Configuration.http.port , www = Configuration.http.www , uploads = Configuration.http.uploads , pidfile = Configuration.http.pid , name = Configuration.server.name , wshost = Configuration.server.interface, wsport = Configuration.server.port , redis_host = Configuration.redis.interface , redis_port = Configuration.redis.port , redis_database = Configuration.redis.database , path = package.path, cpath = package.cpath, redirects = table.concat (locations, "\n"), } local file = io.open (Configuration.http.configuration, "w") file:write (configuration) file:close () end function Nginx.start () Nginx.stop () Nginx.configure () os.execute ([[ {{{nginx}}} -p {{{directory}}} -c {{{configuration}}} 2>> {{{error}}} ]] % { nginx = Configuration.http.nginx , directory = Configuration.http.directory , configuration = Configuration.http.configuration, error = Configuration.http.error , }) end function Nginx.stop () os.execute ([[ [ -f {{{pidfile}}} ] && { kill -QUIT $(cat {{{pidfile}}}) } ]] % { pidfile = Configuration.http.pid, }) os.execute ([[ rm -rf {{{directory}}} {{{pid}}} {{{error}}} {{{configuration}}} ]] % { pid = Configuration.http.pid, configuration = Configuration.http.configuration, error = Configuration.http.error, directory = Configuration.http.directory, }) Nginx.directory = nil end function Nginx.update () Nginx.configure () os.execute ([[ [ -f {{{pidfile}}} ] && { kill -HUP $(cat {{{pidfile}}}) } ]] % { pidfile = Configuration.http.pid, }) end Loader.hotswap.on_change ["cosy:configuration"] = function () Nginx.update () end return Nginx
Remove redis access for file uploads. Fix #79
Remove redis access for file uploads. Fix #79
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
28793d604dd21a3417b984d8840a8d0685fb144a
src/cosy/parameters.lua
src/cosy/parameters.lua
local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Layer = require "layeredata" Configuration.load "cosy.parameters" local i18n = I18n.load "cosy.parameters" i18n._locale = Configuration.locale [nil] local Parameters = setmetatable ({}, { __index = function (_, key) return Configuration.data [key] end, }) function Parameters.check (store, request, parameters) parameters = parameters or {} if request.__DESCRIBE then local result = { required = {}, optional = {}, } local locale = Configuration.locale.default [nil] if request.locale then locale = request.locale or locale end for _, part in ipairs { "required", "optional" } do for k, v in pairs (parameters [part] or {}) do local ok, err = pcall (function () local name = tostring (v):gsub ("/whole/.data.", "") :gsub ("_", "-") :gsub ("%.", ":") result [part] [k] = { type = tostring (v):gsub ("/whole/.data.", ""), description = i18n [name] % { locale = locale, } } end) if not ok then Logger.warning { _ = i18n ["translation:failure"], reason = err, } result [part] [k] = { type = tostring (v):gsub ("/whole/.data.", ""), description = "(missing description)", } end end end error (result) end local reasons = {} local checked = {} for _, field in ipairs { "required", "optional" } do for key, parameter in pairs (parameters [field] or {}) do local value = request [key] if field == "required" and value == nil then reasons [#reasons+1] = { _ = i18n ["check:not-found"], key = key, } elseif value ~= nil then for i = 1, Layer.size (parameter.check) do local ok, reason = parameter.check [i] [nil] { parameter = parameter, request = request, key = key, store = store, } checked [key] = true if not ok then reason.parameter = key reasons [#reasons+1] = reason break end end end end end for key in pairs (request) do if not checked [key] then Logger.warning { _ = i18n ["check:no-check"], key = key, } request [key] = nil end end if #reasons ~= 0 then error { _ = i18n ["check:error"], reasons = reasons, } end end return Parameters
local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Layer = require "layeredata" Configuration.load "cosy.parameters" local i18n = I18n.load "cosy.parameters" i18n._locale = Configuration.locale [nil] local Parameters = setmetatable ({}, { __index = function (_, key) return Configuration.data [key] end, }) function Parameters.check (store, request, parameters) parameters = parameters or {} if request.__DESCRIBE then local result = { required = {}, optional = {}, } local locale = Configuration.locale.default [nil] if request.locale then locale = request.locale or locale end for _, part in ipairs { "required", "optional" } do for k, v in pairs (parameters [part] or {}) do local ok, err = pcall (function () local name = {} for i = 2, #v.__keys do name [#name+1] = v.__keys [i] end name = table.concat (name, ":") result [part] [k] = { type = tostring (v):gsub ("/whole/.data.", ""), description = i18n [name] % { locale = locale, } } end) if not ok then Logger.warning { _ = i18n ["translation:failure"], reason = err, } result [part] [k] = { type = tostring (v):gsub ("/whole/.data.", ""), description = "(missing description)", } end end end error (result) end local reasons = {} local checked = {} for _, field in ipairs { "required", "optional" } do for key, parameter in pairs (parameters [field] or {}) do local value = request [key] if field == "required" and value == nil then reasons [#reasons+1] = { _ = i18n ["check:not-found"], key = key, } elseif value ~= nil then for i = 1, Layer.size (parameter.check) do local ok, reason = parameter.check [i] [nil] { parameter = parameter, request = request, key = key, store = store, } checked [key] = true if not ok then reason.parameter = key reasons [#reasons+1] = reason break end end end end end for key in pairs (request) do if not checked [key] then Logger.warning { _ = i18n ["check:no-check"], key = key, } request [key] = nil end end if #reasons ~= 0 then error { _ = i18n ["check:error"], reasons = reasons, } end end return Parameters
Fix get of parameters descriptions.
Fix get of parameters descriptions.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
43261b086b41704332f9129cb66c2f647b4fc6aa
src/cosy/token/init.lua
src/cosy/token/init.lua
if _G.js then error "Not available" end local Configuration = require "cosy.configuration" local Digest = require "cosy.digest" local Random = require "cosy.random" local Time = require "cosy.time" local Jwt = require "luajwt" local App = require "cosy.configuration.layers".app Configuration.load "cosy.token" if Configuration.token.secret == nil then App.token = { secret = Digest (Random ()) } end local Token = {} function Token.encode (token) local secret = Configuration.token.secret local algorithm = Configuration.token.algorithm local result, err = Jwt.encode (token, secret, algorithm) if not result then error (err) end return result end function Token.decode (s) local key = Configuration.token.secret local algorithm = Configuration.token.algorithm local result, err = Jwt.decode (s, key, algorithm) if not result then error (err) end return result end function Token.administration () local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.administration, iss = Configuration.server.name, aud = nil, sub = "cosy:administration", jti = Digest (tostring (now + Random ())), contents = { type = "administration", passphrase = Configuration.server.passphrase, }, } return Token.encode (result) end function Token.validation (data) local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.validation, iss = Configuration.server.name, aud = nil, sub = "cosy:validation", jti = Digest (tostring (now + Random ())), contents = { type = "validation", username = data.username, email = data.email, }, } return Token.encode (result) end function Token.authentication (data) local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.authentication, iss = Configuration.server.name, aud = nil, sub = "cosy:authentication", jti = Digest (tostring (now + Random ())), contents = { type = "authentication", username = data.username, locale = data.locale, }, } return Token.encode (result) end return Token
if _G.js then error "Not available" end local Configuration = require "cosy.configuration" local Digest = require "cosy.digest" local Random = require "cosy.random" local Time = require "cosy.time" local Jwt = require "luajwt" local App = require "cosy.configuration.layers".app Configuration.load "cosy.token" if Configuration.token.secret == nil then App.token = { secret = Digest (Random ()) } end local Token = {} function Token.encode (token) local secret = Configuration.token.secret local algorithm = Configuration.token.algorithm local result, err = Jwt.encode (token, secret, algorithm) if not result then error (err) end return result end function Token.decode (s) local key = Configuration.token.secret local algorithm = Configuration.token.algorithm local result, err = Jwt.decode (s, key, algorithm) if not result then error (err) end return result end function Token.administration () local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.administration, iss = Configuration.server.name, aud = nil, sub = "cosy:administration", jti = Digest (tostring (now + Random ())), contents = { type = "administration", passphrase = Configuration.server.passphrase, }, } return Token.encode (result) end function Token.validation (data) local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.validation, iss = Configuration.server.name, aud = nil, sub = "cosy:validation", jti = Digest (tostring (now + Random ())), contents = { type = "validation", identifier = data.identifier, email = data.email, }, } return Token.encode (result) end function Token.authentication (data) local now = Time () local result = { iat = now, nbf = now - 1, exp = now + Configuration.expiration.authentication, iss = Configuration.server.name, aud = nil, sub = "cosy:authentication", jti = Digest (tostring (now + Random ())), contents = { type = "authentication", identifier = data.identifier, locale = data.locale, }, } return Token.encode (result) end return Token
Fix identifier in tokens.
Fix identifier in tokens.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
6fbb6e06469b5d50c88496a0a0d9d6d2d4f4d007
src/formatters/init.lua
src/formatters/init.lua
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local ok, term = pcall(require, 'term') local colors = setmetatable({ none = function(c) return c end },{ __index = function(self, key) if not ok or not term.isatty(io.stdout) or not term.colors then return function(c) return c end end return function(c) for token in key:gmatch("[^%.]+") do c = term.colors[token](c) end return c end end }) local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end -- A version of tostring which formats numbers more precisely. local function tostr(arg) if type(arg) ~= "number" then return tostring(arg) end if arg ~= arg then return "NaN" elseif arg == 1/0 then return "Inf" elseif arg == -1/0 then return "-Inf" end local str = string.format("%.20g", arg) if math.type and math.type(arg) == "float" and not str:find("[%.,]") then -- Number is a float but looks like an integer. -- Insert ".0" after first run of digits. str = str:gsub("%d+", "%0.0", 1) end return str end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostr(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg, fmtargs) if type(arg) ~= "table" then return end local tmax = assert:get_parameter("TableFormatLevel") local showrec = assert:get_parameter("TableFormatShowRecursion") local errchar = assert:get_parameter("TableErrorHighlightCharacter") or "" local errcolor = assert:get_parameter("TableErrorHighlightColor") or "none" local crumbs = fmtargs and fmtargs.crumbs or {} local function ft(t, l, cache) local cache = cache or {} if showrec and cache[t] and cache[t] > 0 then return "{ ... recursive }" end if next(t) == nil then return "{ }" end if l > tmax and tmax >= 0 then return "{ ... more }" end local result = "{" local keys, nkeys = get_sorted_keys(t) cache[t] = (cache[t] or 0) + 1 for i = 1, nkeys do local k = keys[i] local v = t[k] if type(v) == "table" then v = ft(v, l + 1, cache) elseif type(v) == "string" then v = "'"..v.."'" end local crumb = crumbs[#crumbs - l + 1] local ch = (crumb == k and errchar or "") local indent = string.rep(" ",l * 2 - ch:len()) local mark = (ch:len() == 0 and "" or colors[errcolor](ch)) result = result .. string.format("\n%s%s[%s] = %s", indent, mark, tostr(k), tostr(v)) end cache[t] = cache[t] - 1 return result .. " }" end return "(table) " .. ft(arg, 1) end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3) assert:set_parameter("TableFormatShowRecursion", false) assert:set_parameter("TableErrorHighlightCharacter", "*") assert:set_parameter("TableErrorHighlightColor", "none")
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local ok, term = pcall(require, 'term') local colors = setmetatable({ none = function(c) return c end },{ __index = function(self, key) local isatty = io.type(io.stdout) == 'file' and term.isatty(io.stdout) if not ok or not isatty or not term.colors then return function(c) return c end end return function(c) for token in key:gmatch("[^%.]+") do c = term.colors[token](c) end return c end end }) local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end -- A version of tostring which formats numbers more precisely. local function tostr(arg) if type(arg) ~= "number" then return tostring(arg) end if arg ~= arg then return "NaN" elseif arg == 1/0 then return "Inf" elseif arg == -1/0 then return "-Inf" end local str = string.format("%.20g", arg) if math.type and math.type(arg) == "float" and not str:find("[%.,]") then -- Number is a float but looks like an integer. -- Insert ".0" after first run of digits. str = str:gsub("%d+", "%0.0", 1) end return str end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostr(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg, fmtargs) if type(arg) ~= "table" then return end local tmax = assert:get_parameter("TableFormatLevel") local showrec = assert:get_parameter("TableFormatShowRecursion") local errchar = assert:get_parameter("TableErrorHighlightCharacter") or "" local errcolor = assert:get_parameter("TableErrorHighlightColor") or "none" local crumbs = fmtargs and fmtargs.crumbs or {} local function ft(t, l, cache) local cache = cache or {} if showrec and cache[t] and cache[t] > 0 then return "{ ... recursive }" end if next(t) == nil then return "{ }" end if l > tmax and tmax >= 0 then return "{ ... more }" end local result = "{" local keys, nkeys = get_sorted_keys(t) cache[t] = (cache[t] or 0) + 1 for i = 1, nkeys do local k = keys[i] local v = t[k] if type(v) == "table" then v = ft(v, l + 1, cache) elseif type(v) == "string" then v = "'"..v.."'" end local crumb = crumbs[#crumbs - l + 1] local ch = (crumb == k and errchar or "") local indent = string.rep(" ",l * 2 - ch:len()) local mark = (ch:len() == 0 and "" or colors[errcolor](ch)) result = result .. string.format("\n%s%s[%s] = %s", indent, mark, tostr(k), tostr(v)) end cache[t] = cache[t] - 1 return result .. " }" end return "(table) " .. ft(arg, 1) end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3) assert:set_parameter("TableFormatShowRecursion", false) assert:set_parameter("TableErrorHighlightCharacter", "*") assert:set_parameter("TableErrorHighlightColor", "none")
Fixes for using luassert with debugger
Fixes for using luassert with debugger When debugging with a remote debugger, `io.stdout` is not a file, but a table. This causes `isatty` to fail. Hence, before calling `isatty`, make sure `io.stdout` is a file.
Lua
mit
o-lim/luassert