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
d7934024148ff51ff39e6d248b36a16e45317597
scripts/package.lua
scripts/package.lua
--- -- Create a source or binary release package. --- --- -- Helper function: run a command while hiding its output. --- local function execQuiet(cmd, ...) cmd = string.format(cmd, ...) .. " > _output_.log 2> _error_.log" local z = os.execute(cmd) os.remove("_output_.log") os.remove("_error_.log") return z end --- -- Check the command line arguments, and show some help if needed. --- local usage = 'usage is: package <branch> <type>\n' .. ' <branch> is the name of the release branch to target\n' .. ' <type> is one of "source" or "binary"\n' if #_ARGS ~= 2 then error(usage, 0) end local branch = _ARGS[1] local kind = _ARGS[2] if kind ~= "source" and kind ~= "binary" then error(usage, 0) end -- -- Make sure I've got what I've need to be happy. -- local required = { "git" } if not os.ishost("windows") then table.insert(required, "make") table.insert(required, "cc") else if not os.getenv("VS140COMNTOOLS") then error("required tool 'Visual Studio 2015' not found", 0) end end for _, value in ipairs(required) do local z = execQuiet("%s --version", value) if not z then error("required tool '" .. value .. "' not found", 0) end end -- -- Figure out what I'm making. -- os.chdir("..") local text = os.outputof(string.format('git show %s:src/host/premake.h', branch)) local _, _, version = text:find('VERSION%s*"([%w%p]+)"') local pkgName = "premake-" .. version local pkgExt = ".zip" if not os.istarget("windows") and kind == "binary" then pkgExt = ".tar.gz" end -- -- Make sure I'm sure. -- printf("") printf("I am about to create a %s package", kind:upper()) printf(" ...named release/%s%s", pkgName, pkgExt) printf(" ...from the %s branch", branch) printf("") printf("Does this look right to you? If so, press [Enter] to begin.") io.read() -- -- Pull down the release branch. -- print("Preparing release folder") os.mkdir("release") os.chdir("release") os.rmdir(pkgName) print("Cloning source code") local z = execQuiet("git clone .. %s -b %s --recurse-submodules", pkgName, branch) if not z then error("clone failed", 0) end os.chdir(pkgName) -- -- Bootstrap Premake in the newly cloned repository -- print("Bootstraping Premake...") if os.ishost("windows") then z = execQuiet("Bootstrap.bat") else local os_map = { linux = "linux", macosx = "osx", } z = execQuiet("make -j -f Bootstrap.mak %s", os_map[os.host()]) end if not z then error("Failed to Bootstrap Premake", 0) end local premakeBin = path.translate("bin/release/Premake5") -- -- Make absolutely sure the embedded scripts have been updated -- print("Updating embedded scripts...") local z = execQuiet("%s embed %s", premakeBin, iif(kind == "source", "", "--bytecode")) if not z then error("failed to update the embedded scripts", 0) end -- -- Generate a source package. -- if kind == "source" then local function genProjects(parameters) if not execQuiet("%s %s", premakeBin, parameters) then error("failed to generate project for "..parameters, 0) end end os.rmdir("build") print("Generating project files...") genProjects("--to=build/vs2005 vs2005") genProjects("--to=build/vs2008 vs2008") genProjects("--to=build/vs2010 vs2010") genProjects("--to=build/vs2012 vs2012") genProjects("--to=build/vs2013 vs2013") genProjects("--to=build/vs2015 vs2015") genProjects("--to=build/vs2017 vs2017") genProjects("--to=build/vs2019 vs2019") genProjects("--to=build/gmake.windows --os=windows gmake") genProjects("--to=build/gmake.unix --os=linux gmake") genProjects("--to=build/gmake.macosx --os=macosx gmake") genProjects("--to=build/gmake.bsd --os=bsd gmake") print("Creating source code package...") if not execQuiet("git add -f build") or not execQuiet("git stash") or not execQuiet("git archive --format=zip -9 -o ../%s-src.zip --prefix=%s/ stash@{0}", pkgName, pkgName) or not execQuiet("git stash drop stash@{0}") then error("failed to archive release", 0) end os.chdir("..") end -- -- Create a binary package for this platform. This step requires a working -- GNU/Make/GCC environment. I use MinGW on Windows as it produces the -- smallest binaries. -- if kind == "binary" then print("Building binary...") os.chdir("bin/release") local addCommand = "git add -f premake5%s" local archiveCommand = "git archive --format=%s -o ../../../%s-%s%s stash@{0} -- ./premake5%s" if os.ishost("windows") then addCommand = string.format(addCommand, ".exe") archiveCommand = string.format(archiveCommand, "zip -9", pkgName, os.host(), pkgExt, ".exe") else addCommand = string.format(addCommand, "") archiveCommand = string.format(archiveCommand, "tar.gz", pkgName, os.host(), pkgExt, "") end if not execQuiet(addCommand) or not execQuiet("git stash") or not execQuiet(archiveCommand) or not execQuiet("git stash drop stash@{0}") then error("failed to archive release", 0) end os.chdir("../../..") end -- -- Clean up -- os.rmdir(pkgName)
--- -- Create a source or binary release package. --- --- -- Helper function: run a command while hiding its output. --- local function execQuiet(cmd, ...) cmd = string.format(cmd, ...) .. " > _output_.log 2> _error_.log" local z = os.execute(cmd) os.remove("_output_.log") os.remove("_error_.log") return z end --- -- Check the command line arguments, and show some help if needed. --- local usage = 'usage is: package <branch> <type>\n' .. ' <branch> is the name of the release branch to target\n' .. ' <type> is one of "source" or "binary"\n' if #_ARGS ~= 2 then error(usage, 0) end local branch = _ARGS[1] local kind = _ARGS[2] if kind ~= "source" and kind ~= "binary" then error(usage, 0) end -- -- Make sure I've got what I've need to be happy. -- local required = { "git" } if not os.ishost("windows") then table.insert(required, "make") table.insert(required, "cc") else if not os.getenv("VS140COMNTOOLS") then error("required tool 'Visual Studio 2015' not found", 0) end end for _, value in ipairs(required) do local z = execQuiet("%s --version", value) if not z then error("required tool '" .. value .. "' not found", 0) end end -- -- Figure out what I'm making. -- os.chdir("..") local text = os.outputof(string.format('git show %s:src/host/premake.h', branch)) local _, _, version = text:find('VERSION%s*"([%w%p]+)"') local pkgName = "premake-" .. version local pkgExt = ".zip" if not os.istarget("windows") and kind == "binary" then pkgExt = ".tar.gz" end -- -- Make sure I'm sure. -- printf("") printf("I am about to create a %s package", kind:upper()) printf(" ...named release/%s%s", pkgName, pkgExt) printf(" ...from the %s branch", branch) printf("") printf("Does this look right to you? If so, press [Enter] to begin.") io.read() -- -- Pull down the release branch. -- print("Preparing release folder") os.mkdir("release") os.chdir("release") os.rmdir(pkgName) print("Cloning source code") local z = execQuiet("git clone .. %s -b %s --recurse-submodules", pkgName, branch) if not z then error("clone failed", 0) end os.chdir(pkgName) -- -- Bootstrap Premake in the newly cloned repository -- print("Bootstraping Premake...") if os.ishost("windows") then z = execQuiet("Bootstrap.bat") else local os_map = { linux = "linux", macosx = "osx", } z = execQuiet("make -j -f Bootstrap.mak %s", os_map[os.host()]) end if not z then error("Failed to Bootstrap Premake", 0) end local premakeBin = path.translate("bin/release/Premake5") -- -- Make absolutely sure the embedded scripts have been updated -- print("Updating embedded scripts...") local z = execQuiet("%s embed %s", premakeBin, iif(kind == "source", "", "--bytecode")) if not z then error("failed to update the embedded scripts", 0) end -- -- Generate a source package. -- if kind == "source" then local function genProjects(parameters) if not execQuiet("%s %s", premakeBin, parameters) then error("failed to generate project for "..parameters, 0) end end os.rmdir("build") print("Generating project files...") genProjects("--to=build/vs2005 vs2005") genProjects("--to=build/vs2008 vs2008") genProjects("--to=build/vs2010 vs2010") genProjects("--to=build/vs2012 vs2012") genProjects("--to=build/vs2013 vs2013") genProjects("--to=build/vs2015 vs2015") genProjects("--to=build/vs2017 vs2017") genProjects("--to=build/vs2019 vs2019") genProjects("--to=build/gmake.windows --os=windows gmake") genProjects("--to=build/gmake.unix --os=linux gmake") genProjects("--to=build/gmake.macosx --os=macosx gmake") genProjects("--to=build/gmake.bsd --os=bsd gmake") print("Creating source code package...") if not execQuiet("git add -f build") or not execQuiet("git stash") or not execQuiet("git archive --format=zip -9 -o ../%s-src.zip --prefix=%s/ stash@{0}", pkgName, pkgName) or not execQuiet("git stash drop stash@{0}") then error("failed to archive release", 0) end os.chdir("..") end -- -- Create a binary package for this platform. This step requires a working -- GNU/Make/GCC environment. I use MinGW on Windows as it produces the -- smallest binaries. -- if kind == "binary" then print("Building binary...") os.chdir("bin/release") local addCommand = "git add -f premake5%s" local archiveCommand = "git archive --format=%s -o ../../../%s-%s%s stash@{0} -- ./premake5%s" if os.ishost("windows") then addCommand = string.format(addCommand, ".exe") archiveCommand = string.format(archiveCommand, "zip -9", pkgName, os.host(), pkgExt, ".exe") else addCommand = string.format(addCommand, "") archiveCommand = string.format(archiveCommand, "tar.gz", pkgName, os.host(), pkgExt, "") end if not execQuiet(addCommand) or not execQuiet("git stash") or not execQuiet(archiveCommand) or not execQuiet("git stash drop stash@{0}") then error("failed to archive release", 0) end os.chdir("../../..") end -- -- Clean up -- -- Use RMDIR token instead of os.rmdir to force remove .git dir which has read only files execQuiet(os.translateCommands("{RMDIR} "..pkgName))
Package: Fix repository not correctly removed due to git objects being read only
Package: Fix repository not correctly removed due to git objects being read only
Lua
bsd-3-clause
starkos/premake-core,LORgames/premake-core,sleepingwit/premake-core,mandersan/premake-core,dcourtois/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,mandersan/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,sleepingwit/premake-core,starkos/premake-core,LORgames/premake-core,noresources/premake-core,dcourtois/premake-core,noresources/premake-core,sleepingwit/premake-core,dcourtois/premake-core,dcourtois/premake-core,mandersan/premake-core,starkos/premake-core,premake/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,premake/premake-core,premake/premake-core,mandersan/premake-core,noresources/premake-core,starkos/premake-core,noresources/premake-core,LORgames/premake-core,premake/premake-core,sleepingwit/premake-core,premake/premake-core,dcourtois/premake-core,sleepingwit/premake-core,mandersan/premake-core
e801500901a56fb73efe8c2a89dda0e226a933a9
pud/component/CollisionComponent.lua
pud/component/CollisionComponent.lua
local Class = require 'lib.hump.class' local ModelComponent = getClass 'pud.component.ModelComponent' local property = require 'pud.component.property' local message = require 'pud.component.message' -- CollisionComponent -- local CollisionComponent = Class{name='CollisionComponent', inherits=ModelComponent, function(self, properties) self._requiredProperties = { 'BlockedBy', } ModelComponent.construct(self, properties) self._attachMessages = {'COLLIDE_CHECK'} end } -- destructor function CollisionComponent:destroy() ModelComponent.destroy(self) end function CollisionComponent:_setProperty(prop, data) prop = property(prop) data = data or property.default(prop) if prop == property('BlockedBy') then verify('table', data) else error('CollisionComponent does not support property: %s', tostring(prop)) end self._properties[prop] = data end function CollisionComponent:_collideCheck(level, pos, oldpos) print(pos, oldpos) local collision = false local entities = level:getEntitiesAtLocation(pos) if entities then for _,otherEntity in pairs(entities) do local otherEntityType = otherEntity:getType() if otherEntityType == 'enemy' then self._mediator:send(message('COLLIDE_ENEMY'), otherEntity) collision = true elseif otherEntityType == 'hero' then self._mediator:sent(message('COLLIDE_HERO'), otherEntity) collision = true end end end if not collision then local node = level:getMapNode(pos) local blocked = false local mapType = node:getMapType() local variant = mapType:getVariant() local mt = match(mapType.__class, '^(%w+)MapType') if mt then blocked = entity:query(property('BlockedBy'), function(t) for _,p in pairs(t) do if p[mt] and (variant == p[mt] or p[mt] == 'ALL') then return true end end return false end) end if blocked then entity:send(message('COLLIDE_BLOCKED'), mapType) collision = true end end if not collision then entity:send(message('COLLIDE_NONE'), pos, oldpos) end end function CollisionComponent:receive(msg, ...) if msg == message('COLLIDE_CHECK') then self:_collideCheck(...) end end -- the class return CollisionComponent
local Class = require 'lib.hump.class' local ModelComponent = getClass 'pud.component.ModelComponent' local property = require 'pud.component.property' local message = require 'pud.component.message' local match = string.match -- CollisionComponent -- local CollisionComponent = Class{name='CollisionComponent', inherits=ModelComponent, function(self, properties) self._requiredProperties = { 'BlockedBy', } ModelComponent.construct(self, properties) self._attachMessages = {'COLLIDE_CHECK'} end } -- destructor function CollisionComponent:destroy() ModelComponent.destroy(self) end function CollisionComponent:_setProperty(prop, data) prop = property(prop) data = data or property.default(prop) if prop == property('BlockedBy') then verify('table', data) else error('CollisionComponent does not support property: %s', tostring(prop)) end self._properties[prop] = data end function CollisionComponent:_collideCheck(level, pos, oldpos) local collision = false local entities = level:getEntitiesAtLocation(pos) if entities then for _,otherEntity in pairs(entities) do local otherEntityType = otherEntity:getType() if otherEntityType == 'enemy' then self._mediator:send(message('COLLIDE_ENEMY'), otherEntity) collision = true elseif otherEntityType == 'hero' then self._mediator:sent(message('COLLIDE_HERO'), otherEntity) collision = true end end end if not collision then local node = level:getMapNode(pos) local blocked = false local mapType = node:getMapType() local variant = mapType:getVariant() local mt = match(tostring(mapType.__class), '^(%w+)MapType') if mt then blocked = self._mediator:query(property('BlockedBy'), function(t) for _,p in pairs(t) do if p[mt] and (variant == p[mt] or p[mt] == 'ALL') then return true end end return false end) end if blocked then self._mediator:send(message('COLLIDE_BLOCKED'), mapType) collision = true end end if not collision then self._mediator:send(message('COLLIDE_NONE'), pos, oldpos) end end function CollisionComponent:receive(msg, ...) if msg == message('COLLIDE_CHECK') then self:_collideCheck(...) end end -- the class return CollisionComponent
fix migrating from old code
fix migrating from old code
Lua
mit
scottcs/wyx
99cc2c41e6fc026699c35eb0d08b2ae7c9301b8b
focuspoints.lrdevplugin/FocusPointDialog.lua
focuspoints.lrdevplugin/FocusPointDialog.lua
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local LrSystemInfo = import 'LrSystemInfo' local LrApplication = import 'LrApplication' local LrView = import 'LrView' local LrColor = import 'LrColor' require "Utils" FocusPointDialog = {} function FocusPointDialog.calculatePhotoDimens(targetPhoto) local appWidth, appHeight = LrSystemInfo.appWindowSize() local dimens = targetPhoto:getFormattedMetadata("croppedDimensions") local w, h = parseDimens(dimens) local viewFactory = LrView.osFactory() local contentWidth = appWidth * .7 local contentHeight = appHeight * .7 local photoWidth local photoHeight if (w > h) then photoWidth = math.min(w, contentWidth) photoHeight = h/w * photoWidth else photoHeight = math.min(h, contentHeight) photoWidth = w/h * photoHeight end return photoWidth, photoHeight end function FocusPointDialog.createDialog(targetPhoto, overlayView) local appWidth, appHeight = LrSystemInfo.appWindowSize() local photoWidth, photoHeight = FocusPointDialog.calculatePhotoDimens(targetPhoto) -- temporary for dev'ing local developSettings = targetPhoto:getDevelopSettings() local viewFactory = LrView.osFactory() local myPhoto = viewFactory:catalog_photo { width = photoWidth, height = photoHeight, photo = targetPhoto, } local myText = viewFactory:static_text { title = "" -- "CL " .. developSettings["CropLeft"] .. ", CT " .. developSettings["CropTop"] .. ", Angle " .. developSettings["CropAngle"], } local column = viewFactory:column { myPhoto, myText, } local myView = viewFactory:view { column, overlayView, place = 'overlapping', } -- windows has the z index switched if (WIN_ENV) then myView = viewFactory:view { overlayView, column, place = 'overlapping', } end return myView end
--[[ Copyright 2016 Joshua Musselwhite, Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local LrSystemInfo = import 'LrSystemInfo' local LrApplication = import 'LrApplication' local LrView = import 'LrView' local LrColor = import 'LrColor' require "Utils" FocusPointDialog = {} function FocusPointDialog.calculatePhotoDimens(targetPhoto) local appWidth, appHeight = LrSystemInfo.appWindowSize() local dimens = targetPhoto:getFormattedMetadata("croppedDimensions") local w, h = parseDimens(dimens) local contentWidth = appWidth * .88 local contentHeight = appHeight * .88 local photoWidth local photoHeight if (w > h) then photoWidth = math.min(w, contentWidth) photoHeight = h/w * photoWidth if photoHeight > contentHeight then photoHeight = math.min(h, contentHeight) photoWidth = w/h * photoHeight end else photoHeight = math.min(h, contentHeight) photoWidth = w/h * photoHeight if photoWidth > contentWidth then photoWidth = math.min(w, contentWidth) photoHeight = h/w * photoWidth end end return photoWidth, photoHeight end function FocusPointDialog.createDialog(targetPhoto, overlayView) local photoWidth, photoHeight = FocusPointDialog.calculatePhotoDimens(targetPhoto) -- temporary for dev'ing local developSettings = targetPhoto:getDevelopSettings() local viewFactory = LrView.osFactory() local myPhoto = viewFactory:catalog_photo { width = photoWidth, height = photoHeight, photo = targetPhoto, } local myText = viewFactory:static_text { title = "" -- "CL " .. developSettings["CropLeft"] .. ", CT " .. developSettings["CropTop"] .. ", Angle " .. developSettings["CropAngle"], } local column = viewFactory:column { myPhoto, myText, } local myView = viewFactory:view { column, overlayView, place = 'overlapping', } -- windows has the z index switched if (WIN_ENV) then myView = viewFactory:view { overlayView, column, place = 'overlapping', } end return myView end
Fix size calculation for image in dialog window.
Fix size calculation for image in dialog window.
Lua
apache-2.0
musselwhizzle/Focus-Points,philmoz/Focus-Points,project802/Focus-Points,project802/Focus-Points,project802/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,mkjanke/Focus-Points,mkjanke/Focus-Points,philmoz/Focus-Points,rderimay/Focus-Points,rderimay/Focus-Points
8c750eab4fe7996abe4a117595b0c78afc1f9f65
event_list_slide.lua
event_list_slide.lua
require 'text_util' local class = require '30log' local json = require 'json' local Slide = require 'slide' -- local white_block = resource.load_image('white.png') local EventListSlide = Slide:extend("EventListSlide") local EventListItem = require 'event_list_item' function EventListSlide:init(x, y, width, height, data_filename) self.super:init() self.x, self.y = x, y self.items_start = 150 self.width, self.height = width, height self.items = {} self.pages = {} self:reset() util.file_watch(data_filename, function(content) local event_list = json.decode(content) self.font = resource.load_font(event_list.font) self.title = event_list.title self.events = event_list.events self.duration = event_list.duration self.items = {} self.pages = {} for i, event in ipairs(self.events) do self.items[i] = EventListItem(WIDTH, 90, event.name, event.start, event.location, self.font) end self.pages = self:group_items() self:reset() end) end function EventListSlide:group_items() local pages = {} local current_end = self.items_start local current_page = {} for i, item in ipairs(self.items) do if (current_end + item:get_height() < self.height) then table.insert(current_page, item) current_end = current_end + item:get_height() else table.insert(pages, current_page) current_page = {} table.insert(current_page, item) current_end = self.items_start + item:get_height() end end table.insert(pages, current_page) return pages end function EventListSlide:draw() self.super:tick() write_centered(self.title, 50, self.width / 2, 50, 1, 1, 1, 1) local page_num = math.floor(self.super.active_time / self.duration) + 1 local page_time = self.super.active_time - self.duration * (page_num - 1) local item_fade = 0.2 local page_clear_start_time = self.duration - #self.pages[page_num] * item_fade local clearing_page = (page_time > page_clear_start_time) local y = self.items_start for i, item in ipairs(self.pages[page_num]) do local offset = i - 1 local alpha if clearing_page then local clearing_time = page_time - page_clear_start_time alpha = 1 - (clearing_time / item_fade - offset) else alpha = page_time / item_fade - offset end alpha = math.min(math.max(alpha, 0), 1) item:draw(50, y, alpha) y = y + item:get_height() end end function EventListSlide:reset() self.super:reset() self.x = -self.width end function EventListSlide:is_done() return (self.super.active_time > self.duration * #self.pages) end return EventListSlide
require 'text_util' local class = require '30log' local json = require 'json' local Slide = require 'slide' -- local white_block = resource.load_image('white.png') local EventListSlide = Slide:extend("EventListSlide") local EventListItem = require 'event_list_item' function EventListSlide:init(x, y, width, height, data_filename) self.super:init() self.x, self.y = x, y self.items_start = 150 self.width, self.height = width, height self.items = {} self.pages = {} self:reset() util.file_watch(data_filename, function(content) local event_list = json.decode(content) self.font = resource.load_font(event_list.font) self.title = event_list.title self.events = event_list.events self.duration = event_list.duration self.items = {} self.pages = {} for i, event in ipairs(self.events) do self.items[i] = EventListItem(WIDTH, 90, event.name, event.start, event.location, self.font) end self.pages = self:group_items() self:reset() end) end function EventListSlide:group_items() local pages = {} local current_end = self.items_start local current_page = {} for i, item in ipairs(self.items) do if (current_end + item:get_height() < self.height) then table.insert(current_page, item) current_end = current_end + item:get_height() else table.insert(pages, current_page) current_page = {} table.insert(current_page, item) current_end = self.items_start + item:get_height() end end table.insert(pages, current_page) return pages end function EventListSlide:draw() self.super:tick() write_centered(self.title, 50, self.width / 2, 50, 1, 1, 1, 1) local page_num = math.floor(self.super.active_time / self.duration) + 1 -- Handle edge case where you can get one frame past the available pages page_num = math.min(page_num, #self.pages) local page_time = self.super.active_time - self.duration * (page_num - 1) local item_fade = 0.2 local page_clear_start_time = self.duration - #(self.pages[page_num]) * item_fade local clearing_page = (page_time > page_clear_start_time) local y = self.items_start for i, item in ipairs(self.pages[page_num]) do local offset = i - 1 local alpha if clearing_page then local clearing_time = page_time - page_clear_start_time alpha = 1 - (clearing_time / item_fade - offset) else alpha = page_time / item_fade - offset end alpha = math.min(math.max(alpha, 0), 1) item:draw(50, y, alpha) y = y + item:get_height() end end function EventListSlide:reset() self.super:reset() self.x = -self.width end function EventListSlide:is_done() return (self.super.active_time > self.duration * #self.pages) end return EventListSlide
Fixed page number logic
Fixed page number logic
Lua
apache-2.0
superlou/next-beamer
137494927d7665e68b8df2d051ebf718b9fd33fb
config/nvim/after.lua
config/nvim/after.lua
local map = require('utils').map local cmd = vim.cmd -- " Commands cmd([[colorscheme dracula]]) -- " Remove trailing spaces on save cmd([[autocmd BufWritePre * :%s/\s\+$//e]]) -- " Common typos cmd(':command! WQ wq') cmd(':command! WQ wq') cmd(':command! Wq wq') cmd(':command! Wqa wqa') cmd(':command! Qall qall') cmd(':command! W w') cmd(':command! Q q') -- " Mappings -- " Search under word map('n', '<Leader>rg', '<ESC>:FZFRg<Space>', { noremap = true, silent = false }) map('n', '<Leader>rw', '<ESC>:FZFRg <C-R><C-W><enter>', { noremap = true, silent = false }) -- " Split window and file navigation map('n', '<Leader>hh', ':split<CR>', {silent = true}) map('n', '<Leader>vv', ':vsplit<CR>', {silent = true}) map('n', '\\', ':NERDTreeToggle<CR>', {noremap = true, silent = true}) map('n', '\\f', ':NERDTreeFind<CR>', {noremap = true, silent = true}) map('n', '<leader><space>', ':Vipe<CR>', {silent = true}) -- " Switch between test and production code map('n', '<Leader>.', ':A<CR>',{}) -- " Open nvim help map( "n", ",h", [[<Cmd>lua require'telescope.builtin'.help_tags({results_title='Help Results'})<CR>]], { noremap = true, silent = true }) -- " Plugin Config vim.g.gutentags_ctags_exclude = { '*.git', '*.svg', '*.hg', '*/tests/*', 'build', 'dist', '*sites/*/files/*', 'bin', 'node_modules', 'bower_components', 'cache', 'compiled', 'docs', 'example', 'bundle', 'vendor', '*.md', '*-lock.json', '*.lock', '*bundle*.js', '*build*.js', '.*rc*', '*.json', '*.min.*', '*.map', '*.bak', '*.zip', '*.pyc', '*.class', '*.sln', '*.Master', '*.csproj', '*.tmp', '*.csproj.user', '*.cache', '*.pdb', 'tags*', 'cscope.*', '*.exe', '*.dll', '*.mp3', '*.ogg', '*.flac', '*.swp', '*.swo', '*.bmp', '*.gif', '*.ico', '*.jpg', '*.png', '*.rar', '*.zip', '*.tar', '*.tar.gz', '*.tar.xz', '*.tar.bz2', '*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx', } vim.g.gutentags_add_default_project_roots = false vim.g.gutentags_project_root = {'package.json', '.git'} vim.g.gutentags_cache_dir = vim.fn.expand('~/.cache/nvim/ctags/') vim.g.gutentags_generate_on_new = true vim.g.gutentags_generate_on_missing = true vim.g.gutentags_generate_on_write = true vim.g.gutentags_generate_on_empty_buffer = true vim.cmd([[command! -nargs=0 GutentagsClearCache call system('rm ' . g:gutentags_cache_dir . '/*')]]) vim.g.gutentags_ctags_extra_args = {'--tag-relative=yes', '--fields=+ailmnS', } require'lspconfig'.solargraph.setup{} require'lspconfig'.sorbet.setup{} require'lspconfig'.gopls.setup{}
local map = require('utils').map local cmd = vim.cmd -- " Commands cmd([[colorscheme dracula]]) -- " Remove trailing spaces on save cmd([[autocmd BufWritePre * :%s/\s\+$//e]]) -- " Common typos cmd(':command! WQ wq') cmd(':command! WQ wq') cmd(':command! Wq wq') cmd(':command! Wqa wqa') cmd(':command! Qall qall') cmd(':command! W w') cmd(':command! Q q') -- " Mappings -- " Search under word map('n', '<Leader>rg', '<ESC>:FZFRg<Space>', { noremap = true, silent = false }) map('n', '<Leader>rw', '<ESC>:FZFRg <C-R><C-W><enter>', { noremap = true, silent = false }) -- " Split window and file navigation map('n', '<Leader>hh', ':split<CR>', {silent = true}) map('n', '<Leader>vv', ':vsplit<CR>', {silent = true}) map('n', '\\', ':NERDTreeToggle<CR>', {noremap = true, silent = true}) map('n', '\\f', ':NERDTreeFind<CR>', {noremap = true, silent = true}) map('n', '<leader><space>', ':Vipe<CR>', {silent = true}) -- " Switch between test and production code map('n', '<Leader>.', ':A<CR>',{}) -- " Open nvim help map( "n", ",h", [[<Cmd>lua require'telescope.builtin'.help_tags({results_title='Help Results'})<CR>]], { noremap = true, silent = true }) -- " Plugin Config vim.g.gutentags_ctags_exclude = { '*.git', '*.svg', '*.hg', '*/tests/*', 'build', 'dist', '*sites/*/files/*', 'bin', 'node_modules', 'bower_components', 'cache', 'compiled', 'docs', 'example', 'bundle', 'vendor', '*.md', '*-lock.json', '*.lock', '*bundle*.js', '*build*.js', '.*rc*', '*.json', '*.min.*', '*.map', '*.bak', '*.zip', '*.pyc', '*.class', '*.sln', '*.Master', '*.csproj', '*.tmp', '*.csproj.user', '*.cache', '*.pdb', 'tags*', 'cscope.*', '*.exe', '*.dll', '*.mp3', '*.ogg', '*.flac', '*.swp', '*.swo', '*.bmp', '*.gif', '*.ico', '*.jpg', '*.png', '*.rar', '*.zip', '*.tar', '*.tar.gz', '*.tar.xz', '*.tar.bz2', '*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx', } vim.g.gutentags_add_default_project_roots = false vim.g.gutentags_project_root = {'package.json', '.git'} vim.g.gutentags_cache_dir = vim.fn.expand('~/.cache/nvim/ctags/') vim.g.gutentags_generate_on_new = true vim.g.gutentags_generate_on_missing = true vim.g.gutentags_generate_on_write = true vim.g.gutentags_generate_on_empty_buffer = true vim.cmd([[command! -nargs=0 GutentagsClearCache call system('rm ' . g:gutentags_cache_dir . '/*')]]) vim.g.gutentags_ctags_extra_args = {'--tag-relative=yes', '--fields=+ailmnS', } require'lspconfig'.solargraph.setup{} require'lspconfig'.sorbet.setup{cmd = { 'srb', 'tc', '--lsp' ,'.'}} require'lspconfig'.gopls.setup{}
Fix sorbet lsp
Fix sorbet lsp
Lua
mit
albertoleal/dotfiles,albertoleal/dotfiles
f0f9cfc61a40b0f36af84aee4a13fb34e50b5a41
BtEvaluator/BtEvaluator.lua
BtEvaluator/BtEvaluator.lua
function widget:GetInfo() return { name = "BtEvaluator loader", desc = "BtEvaluator loader and message test to this AI.", author = "JakubStasta", date = "Sep 20, 2016", license = "BY-NC-SA", layer = 0, enabled = true, -- loaded by default? version = version, } end local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) local JSON = Utils.JSON local Sentry = Utils.Sentry local Dependency = Utils.Dependency local Debug = Utils.Debug local Logger = Debug.Logger local SensorManager = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtEvaluator/SensorManager.lua", nil, VFS.RAW_FIRST) -- BtEvaluator interface definitions local BtEvaluator = Sentry:New() local lastResponse = nil function BtEvaluator.sendMessage(messageType, messageData) local payload = "BETS " .. messageType; if(messageData)then payload = payload .. " " if(type(messageData) == "string")then payload = payload .. messageData else payload = payload .. JSON:encode(messageData) end end Logger.log("communication", payload) lastResponse = nil Spring.SendSkirmishAIMessage(Spring.GetLocalPlayerID(), payload) if(lastResponse ~= nil)then local response = lastResponse lastResponse = nil if(response.result)then if(response.data == nil)then return true else return response.data end else return nil, response.error end end end function BtEvaluator.requestNodeDefinitions() return BtEvaluator.sendMessage("REQUEST_NODE_DEFINITIONS") end function BtEvaluator.assignUnits(units, instanceId, role) return BtEvaluator.sendMessage("ASSIGN_UNITS", { units = units, instanceId = instanceId, role = role }) end function BtEvaluator.createTree(instanceId, treeDefinition) return BtEvaluator.sendMessage("CREATE_TREE", { instanceId = instanceId, root = treeDefinition.root }) end function BtEvaluator.removeTree(insId) return BtEvaluator.sendMessage("REMOVE_TREE", { instanceId = insId }) end function BtEvaluator.reportTree(insId) return BtEvaluator.sendMessage("REPORT_TREE", { instanceId = insId }) end function widget:Initialize() WG.BtEvaluator = BtEvaluator BtEvaluator.sendMessage("REINITIALIZE") Spring.SendCommands("AIControl "..Spring.GetLocalPlayerID().." BtEvaluator") end function widget:RecvSkirmishAIMessage(aiTeam, message) Logger.log("communication", "Received message from team " .. tostring(aiTeam) .. ": " .. message) -- Dont respond to other players AI if(aiTeam ~= Spring.GetLocalPlayerID()) then return end -- Check if it starts with "BETS" if(message:len() <= 4 and message:sub(1,4):upper() ~= "BETS") then return end local messageShorter = message:sub(6) local indexOfFirstSpace = string.find(messageShorter, " ") or (message:len() + 1) local messageType = messageShorter:sub(1, indexOfFirstSpace - 1):upper() -- internal messages without parameter if(messageType == "LOG") then Logger.log("BtEvaluator", messageBody) return true elseif(messageType == "INITIALIZED") then Dependency.fill(Dependency.BtEvaluator) return true elseif(messageType == "RESPONSE")then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) lastResponse = data return true else -- messages without parameter local handler = ({ -- none so far })[messageType] if(handler)then return handler:Invoke() else handler = ({ ["UPDATE_STATES"] = BtEvaluator.OnUpdateStates, ["NODE_DEFINITIONS"] = BtEvaluator.OnNodeDefinitions, ["COMMAND"] = BtEvaluator.OnCommand, })[messageType] if(handler)then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) return handler:Invoke(data) else Logger.log("communication", "Unknown message type: |", messageType, "|") end end end end
function widget:GetInfo() return { name = "BtEvaluator loader", desc = "BtEvaluator loader and message test to this AI.", author = "JakubStasta", date = "Sep 20, 2016", license = "BY-NC-SA", layer = 0, enabled = true, -- loaded by default? version = version, } end local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) local JSON = Utils.JSON local Sentry = Utils.Sentry local Dependency = Utils.Dependency local Debug = Utils.Debug local Logger = Debug.Logger local SensorManager = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtEvaluator/SensorManager.lua", nil, VFS.RAW_FIRST) -- BtEvaluator interface definitions local BtEvaluator = Sentry:New() local lastResponse = nil function BtEvaluator.sendMessage(messageType, messageData) local payload = "BETS " .. messageType; if(messageData)then payload = payload .. " " if(type(messageData) == "string")then payload = payload .. messageData else payload = payload .. JSON:encode(messageData) end end Logger.log("communication", payload) lastResponse = nil Spring.SendSkirmishAIMessage(Spring.GetLocalPlayerID(), payload) if(lastResponse ~= nil)then local response = lastResponse lastResponse = nil if(response.result)then if(response.data == nil)then return true else return response.data end else return nil, response.error end end end function BtEvaluator.requestNodeDefinitions() return BtEvaluator.sendMessage("REQUEST_NODE_DEFINITIONS") end function BtEvaluator.assignUnits(units, instanceId, role) return BtEvaluator.sendMessage("ASSIGN_UNITS", { units = units, instanceId = instanceId, role = role }) end function BtEvaluator.createTree(instanceId, treeDefinition) return BtEvaluator.sendMessage("CREATE_TREE", { instanceId = instanceId, root = treeDefinition.root }) end function BtEvaluator.removeTree(insId) return BtEvaluator.sendMessage("REMOVE_TREE", { instanceId = insId }) end function BtEvaluator.reportTree(insId) return BtEvaluator.sendMessage("REPORT_TREE", { instanceId = insId }) end function BtEvaluator.OnExpression(params) if(params.func == "RESET")then return "S" end local f, msg = loadstring("return " .. params.expression) if(not f)then return "F" end setfenv(f, SensorManager.forGroup(params.units)) local success, result = pcall(f) if(success and result)then return "S" else return "F" end end function widget:Initialize() WG.BtEvaluator = BtEvaluator BtEvaluator.sendMessage("REINITIALIZE") Spring.SendCommands("AIControl "..Spring.GetLocalPlayerID().." BtEvaluator") end function widget:RecvSkirmishAIMessage(aiTeam, message) Logger.log("communication", "Received message from team " .. tostring(aiTeam) .. ": " .. message) -- Dont respond to other players AI if(aiTeam ~= Spring.GetLocalPlayerID()) then return end -- Check if it starts with "BETS" if(message:len() <= 4 and message:sub(1,4):upper() ~= "BETS") then return end local messageShorter = message:sub(6) local indexOfFirstSpace = string.find(messageShorter, " ") or (message:len() + 1) local messageType = messageShorter:sub(1, indexOfFirstSpace - 1):upper() -- internal messages without parameter if(messageType == "LOG") then Logger.log("BtEvaluator", messageBody) return true elseif(messageType == "INITIALIZED") then Dependency.fill(Dependency.BtEvaluator) return true elseif(messageType == "RESPONSE")then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) lastResponse = data return true else -- messages without parameter local handler = ({ -- none so far })[messageType] if(handler)then return handler:Invoke() else handler = ({ ["UPDATE_STATES"] = BtEvaluator.OnUpdateStates, ["NODE_DEFINITIONS"] = BtEvaluator.OnNodeDefinitions, ["COMMAND"] = BtEvaluator.OnCommand, ["EXPRESSION"] = BtEvaluator.OnExpression })[messageType] if(handler)then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) return handler:Invoke(data) else Logger.log("communication", "Unknown message type: |", messageType, "|") end end end end
Fixed accidentally deleted expression handling.
Fixed accidentally deleted expression handling.
Lua
mit
MartinFrancu/BETS
394c6cea0bc7c7df264b8c9bdd64a4ca9716ef30
src/luacheck/options.lua
src/luacheck/options.lua
local options = {} local utils = require "luacheck.utils" local stds = require "luacheck.stds" local function boolean(x) return type(x) == "boolean" end local function number(x) return type(x) == "number" end local function array_of_strings(x) if type(x) ~= "table" then return false end for _, item in ipairs(x) do if type(item) ~= "string" then return false end end return true end local function std_or_array_of_strings(x) return stds[x] or array_of_strings(x) end options.config_options = { global = boolean, unused = boolean, redefined = boolean, unused_args = boolean, unused_values = boolean, unused_secondaries = boolean, unset = boolean, unused_globals = boolean, compat = boolean, allow_defined = boolean, allow_defined_top = boolean, module = boolean, globals = array_of_strings, new_globals = array_of_strings, std = std_or_array_of_strings, ignore = array_of_strings, enable = array_of_strings, only = array_of_strings } options.top_config_options = { limit = number, color = boolean } utils.update(options.top_config_options, options.config_options) -- Returns true if opts is valid option_set. -- Otherwise returns false and, optionally, name of the problematic option. function options.validate(option_set, opts) if opts == nil then return true end local ok, is_valid, invalid_opt = pcall(function() assert(type(opts) == "table") for option, validator in pairs(option_set) do if opts[option] ~= nil then if not validator(opts[option]) then return false, option end end end return true end) return ok and is_valid, invalid_opt end -- Option stack is an array of options with options closer to end -- overriding options closer to beginning. local function get_std(opts_stack) local std local no_compat = false -- TODO: implement and use utils.ripairs for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts.compat and not no_compat then std = "max" break elseif opts.compat == false then no_compat = true end if opts.std then std = opts.std break end end return std and (stds[std] or std) or stds._G end local function get_globals(opts_stack) local globals_lists = {} for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts.new_globals then table.insert(globals_lists, opts.new_globals) break end if opts.globals then table.insert(globals_lists, opts.globals) end end return utils.concat_arrays(globals_lists) end local function get_boolean_opt(opts_stack, option) for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts[option] ~= nil then return opts[option] end end end local function anchor_pattern(pattern, only_start) if not pattern then return end if pattern:sub(1, 1) == "^" or pattern:sub(-1) == "$" then return pattern else return "^" .. pattern .. (only_start and "" or "$") end end -- Returns {pair of normalized patterns for code and name}. -- `pattern` can be: -- string containing '/': first part matches warning code, second - variable name; -- string containing letters: matches variable name; -- otherwise: matches warning code. -- Unless anchored by user, pattern for name is anchored from both sides -- and pattern for code is only anchored at the beginning. local function normalize_pattern(pattern) local code_pattern, name_pattern local slash_pos = pattern:find("/") if slash_pos then code_pattern = pattern:sub(1, slash_pos - 1) name_pattern = pattern:sub(slash_pos + 1) elseif pattern:find("[_a-zA-Z]") then name_pattern = pattern else code_pattern = pattern end return {anchor_pattern(code_pattern, true), anchor_pattern(name_pattern)} end -- From most specific to less specific, pairs {option, pattern}. -- Applying macros in order is required to get deterministic resuls -- and get sensible results when intersecting macros are used. -- E.g. unused = false, unused_args = true should leave unused args enabled. local macros = { {"unused_globals", "13"}, {"unused_args", "21[23]"}, {"unset", "22"}, {"unused_values", "31"}, {"global", "1"}, {"unused", "[23]"}, {"redefined", "4"} } -- Returns array of rules which should be applied in order. -- A rule is a table {{pattern*}, type}. -- `pattern` is a non-normalized pattern. -- `type` can be "enable", "disable" or "only". local function get_rules(opts_stack) local rules = {} local used_macros = {} for i = #opts_stack, 1, -1 do local opts = opts_stack[i] for _, macro_info in ipairs(macros) do local option, pattern = macro_info[1], macro_info[2] if not used_macros[option] then if opts[option] ~= nil then table.insert(rules, {{pattern}, opts[option] and "enable" or "disable"}) used_macros[option] = true end end end if opts.ignore then table.insert(rules, {opts.ignore, "disable"}) end if opts.only then table.insert(rules, {opts.only, "only"}) end if opts.enable then table.insert(rules, {opts.enable, "enable"}) end end return rules end local function normalize_patterns(rules) for _, rule in ipairs(rules) do for i, pattern in ipairs(rule[1]) do rule[1][i] = normalize_pattern(pattern) end end end -- Returns normalized options. -- Normalized options have fields: -- globals: set of strings; -- unused_secondaries, module, allow_defined, allow_defined_top: booleans; -- rules: see get_rules. function options.normalize(opts_stack) local res = {} res.globals = utils.array_to_set(get_globals(opts_stack)) local std = utils.array_to_set(get_std(opts_stack)) utils.update(res.globals, std) for _, option in ipairs {"unused_secondaries", "module", "allow_defined", "allow_defined_top"} do local value = get_boolean_opt(opts_stack, option) if value == nil then res[option] = option == "unused_secondaries" -- Default is true only for unused_secondaries. else res[option] = value end end res.rules = get_rules(opts_stack) normalize_patterns(res.rules) return res end return options
local options = {} local utils = require "luacheck.utils" local stds = require "luacheck.stds" local function boolean(x) return type(x) == "boolean" end local function number(x) return type(x) == "number" end local function array_of_strings(x) if type(x) ~= "table" then return false end for _, item in ipairs(x) do if type(item) ~= "string" then return false end end return true end local function std_or_array_of_strings(x) return stds[x] or array_of_strings(x) end options.config_options = { global = boolean, unused = boolean, redefined = boolean, unused_args = boolean, unused_values = boolean, unused_secondaries = boolean, unset = boolean, unused_globals = boolean, compat = boolean, allow_defined = boolean, allow_defined_top = boolean, module = boolean, globals = array_of_strings, new_globals = array_of_strings, std = std_or_array_of_strings, ignore = array_of_strings, enable = array_of_strings, only = array_of_strings } options.top_config_options = { limit = number, color = boolean } utils.update(options.top_config_options, options.config_options) -- Returns true if opts is valid option_set. -- Otherwise returns false and, optionally, name of the problematic option. function options.validate(option_set, opts) if opts == nil then return true end local ok, is_valid, invalid_opt = pcall(function() assert(type(opts) == "table") for option, validator in pairs(option_set) do if opts[option] ~= nil then if not validator(opts[option]) then return false, option end end end return true end) return ok and is_valid, invalid_opt end -- Option stack is an array of options with options closer to end -- overriding options closer to beginning. local function get_std(opts_stack) local std local no_compat = false -- TODO: implement and use utils.ripairs for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts.compat and not no_compat then std = "max" break elseif opts.compat == false then no_compat = true end if opts.std then std = opts.std break end end return std and (stds[std] or std) or stds._G end local function get_globals(opts_stack) local globals_lists = {} for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts.new_globals then table.insert(globals_lists, opts.new_globals) break end if opts.globals then table.insert(globals_lists, opts.globals) end end return utils.concat_arrays(globals_lists) end local function get_boolean_opt(opts_stack, option) for i = #opts_stack, 1, -1 do local opts = opts_stack[i] if opts[option] ~= nil then return opts[option] end end end local function anchor_pattern(pattern, only_start) if not pattern then return end if pattern:sub(1, 1) == "^" or pattern:sub(-1) == "$" then return pattern else return "^" .. pattern .. (only_start and "" or "$") end end -- Returns {pair of normalized patterns for code and name}. -- `pattern` can be: -- string containing '/': first part matches warning code, second - variable name; -- string containing letters: matches variable name; -- otherwise: matches warning code. -- Unless anchored by user, pattern for name is anchored from both sides -- and pattern for code is only anchored at the beginning. local function normalize_pattern(pattern) local code_pattern, name_pattern local slash_pos = pattern:find("/") if slash_pos then code_pattern = pattern:sub(1, slash_pos - 1) name_pattern = pattern:sub(slash_pos + 1) elseif pattern:find("[_a-zA-Z]") then name_pattern = pattern else code_pattern = pattern end return {anchor_pattern(code_pattern, true), anchor_pattern(name_pattern)} end -- From most specific to less specific, pairs {option, pattern}. -- Applying macros in order is required to get deterministic resuls -- and get sensible results when intersecting macros are used. -- E.g. unused = false, unused_args = true should leave unused args enabled. local macros = { {"unused_globals", "13"}, {"unused_args", "21[23]"}, {"unset", "22"}, {"unused_values", "31"}, {"global", "1"}, {"unused", "[23]"}, {"redefined", "4"} } -- Returns array of rules which should be applied in order. -- A rule is a table {{pattern*}, type}. -- `pattern` is a non-normalized pattern. -- `type` can be "enable", "disable" or "only". local function get_rules(opts_stack) local rules = {} local used_macros = {} for i = #opts_stack, 1, -1 do local opts = opts_stack[i] for _, macro_info in ipairs(macros) do local option, pattern = macro_info[1], macro_info[2] if not used_macros[option] then if opts[option] ~= nil then table.insert(rules, {{pattern}, opts[option] and "enable" or "disable"}) used_macros[option] = true end end end if opts.ignore then table.insert(rules, {opts.ignore, "disable"}) end if opts.only then table.insert(rules, {opts.only, "only"}) end if opts.enable then table.insert(rules, {opts.enable, "enable"}) end end return rules end local function normalize_patterns(rules) local res = {} for i, rule in ipairs(rules) do res[i] = {{}, rule[2]} for j, pattern in ipairs(rule[1]) do res[i][1][j] = normalize_pattern(pattern) end end return res end -- Returns normalized options. -- Normalized options have fields: -- globals: set of strings; -- unused_secondaries, module, allow_defined, allow_defined_top: booleans; -- rules: see get_rules. function options.normalize(opts_stack) local res = {} res.globals = utils.array_to_set(get_globals(opts_stack)) local std = utils.array_to_set(get_std(opts_stack)) utils.update(res.globals, std) for _, option in ipairs {"unused_secondaries", "module", "allow_defined", "allow_defined_top"} do local value = get_boolean_opt(opts_stack, option) if value == nil then res[option] = option == "unused_secondaries" -- Default is true only for unused_secondaries. else res[option] = value end end res.rules = normalize_patterns(get_rules(opts_stack)) return res end return options
Fixed a bug in options.normalize
Fixed a bug in options.normalize Do not mutate options.
Lua
mit
mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,tst2005/luacheck,mpeterv/luacheck,kidaa/luacheck,xpol/luacheck,linuxmaniac/luacheck,kidaa/luacheck,xpol/luacheck,tst2005/luacheck,linuxmaniac/luacheck,adan830/luacheck,adan830/luacheck
90dcea1ba46475a1c02493bd8fe18503931fb507
vrp/lib/Tunnel.lua
vrp/lib/Tunnel.lua
local Tools = module("lib/Tools") local Debug = module("lib/Debug") -- API used in function of the side local TriggerRemoteEvent = nil local RegisterLocalEvent = nil if SERVER then TriggerRemoteEvent = TriggerClientEvent RegisterLocalEvent = RegisterServerEvent else TriggerRemoteEvent = TriggerServerEvent RegisterLocalEvent = RegisterNetEvent end -- this file describe a two way proxy between the server and the clients (request system) local Tunnel = {} -- define per dest regulator Tunnel.delays = {} -- set the base delay between Triggers for this destination in milliseconds (0 for instant trigger) function Tunnel.setDestDelay(dest, delay) Tunnel.delays[dest] = {delay, 0} end local function tunnel_resolve(itable,key) local mtable = getmetatable(itable) local iname = mtable.name local ids = mtable.tunnel_ids local callbacks = mtable.tunnel_callbacks local identifier = mtable.identifier -- generate access function local fcall = function(...) local r = async() local args = {...} local dest = nil if SERVER then dest = args[1] args = {table.unpack(args, 2, table.maxn(args))} end -- get delay data local delay_data = Tunnel.delays[dest] if delay_data == nil then delay_data = {0,0} end -- increase delay local add_delay = delay_data[1] delay_data[2] = delay_data[2]+add_delay if delay_data[2] > 0 then -- delay trigger SetTimeout(delay_data[2], function() -- remove added delay delay_data[2] = delay_data[2]-add_delay -- send request local rid = ids:gen() callbacks[rid] = r if SERVER then TriggerRemoteEvent(iname..":tunnel_req",dest,key,args,identifier,rid) else TriggerRemoteEvent(iname..":tunnel_req",key,args,identifier,rid) end end) else -- no delay -- send request local rid = ids:gen() callbacks[rid] = r if SERVER then TriggerRemoteEvent(iname..":tunnel_req",dest,key,args,identifier,rid) else TriggerRemoteEvent(iname..":tunnel_req",key,args,identifier,rid) end end return r:wait() end itable[key] = fcall -- add generated call to table (optimization) return fcall end -- bind an interface (listen to net requests) -- name: interface name -- interface: table containing functions function Tunnel.bindInterface(name,interface) -- receive request RegisterLocalEvent(name..":tunnel_req") AddEventHandler(name..":tunnel_req",function(member,args,identifier,rid) local source = source if Debug.active then Debug.pbegin("tunnelreq#"..rid.."_"..name..":"..member.." "..json.encode(Debug.safeTableCopy(args))) end local f = interface[member] local rets = {} if type(f) == "function" then -- call bound function rets = {f(table.unpack(args, 1, table.maxn(args)))} -- CancelEvent() -- cancel event doesn't seem to cancel the event for the other handlers, but if it does, uncomment this end -- send response (even if the function doesn't exist) if rid >= 0 then if SERVER then TriggerRemoteEvent(name..":"..identifier..":tunnel_res",source,rid,rets) else TriggerRemoteEvent(name..":"..identifier..":tunnel_res",rid,rets) end end if Debug.active then Debug.pend() end end) end -- get a tunnel interface to send requests -- name: interface name -- identifier: unique string to identify this tunnel interface access (if nil, will be the name of the resource) function Tunnel.getInterface(name,identifier) if not identifier then identifier = GetCurrentResourceName() end local ids = Tools.newIDGenerator() local callbacks = {} -- build interface local r = setmetatable({},{ __index = tunnel_resolve, name = name, tunnel_ids = ids, tunnel_callbacks = callbacks, identifier = identifier }) -- receive response RegisterLocalEvent(name..":"..identifier..":tunnel_res") AddEventHandler(name..":"..identifier..":tunnel_res",function(rid,args) if Debug.active then Debug.pbegin("tunnelres#"..rid.."_"..name.." "..json.encode(Debug.safeTableCopy(args))) end local callback = callbacks[rid] if callback then -- free request id ids:free(rid) callbacks[rid] = nil -- call callback(table.unpack(args, 1, table.maxn(args))) end Debug.pend() end) return r end return Tunnel
local Tools = module("lib/Tools") local Debug = module("lib/Debug") -- API used in function of the side local TriggerRemoteEvent = nil local RegisterLocalEvent = nil if SERVER then TriggerRemoteEvent = TriggerClientEvent RegisterLocalEvent = RegisterServerEvent else TriggerRemoteEvent = TriggerServerEvent RegisterLocalEvent = RegisterNetEvent end -- this file describe a two way proxy between the server and the clients (request system) local Tunnel = {} -- define per dest regulator Tunnel.delays = {} -- set the base delay between Triggers for this destination in milliseconds (0 for instant trigger) function Tunnel.setDestDelay(dest, delay) Tunnel.delays[dest] = {delay, 0} end local function tunnel_resolve(itable,key) local mtable = getmetatable(itable) local iname = mtable.name local ids = mtable.tunnel_ids local callbacks = mtable.tunnel_callbacks local identifier = mtable.identifier -- generate access function local fcall = function(...) local r = nil local args = {...} local dest = nil if SERVER then dest = args[1] args = {table.unpack(args, 2, table.maxn(args))} if dest >= 0 then -- return values not supported for multiple dests (-1) r = async() end else r = async() end -- get delay data local delay_data = nil if dest then delay_data = Tunnel.delays[dest] end if delay_data == nil then delay_data = {0,0} end -- increase delay local add_delay = delay_data[1] delay_data[2] = delay_data[2]+add_delay if delay_data[2] > 0 then -- delay trigger SetTimeout(delay_data[2], function() -- remove added delay delay_data[2] = delay_data[2]-add_delay -- send request local rid = -1 if r then rid = ids:gen() callbacks[rid] = r end if SERVER then TriggerRemoteEvent(iname..":tunnel_req",dest,key,args,identifier,rid) else TriggerRemoteEvent(iname..":tunnel_req",key,args,identifier,rid) end end) else -- no delay -- send request local rid = -1 if r then rid = ids:gen() callbacks[rid] = r end if SERVER then TriggerRemoteEvent(iname..":tunnel_req",dest,key,args,identifier,rid) else TriggerRemoteEvent(iname..":tunnel_req",key,args,identifier,rid) end end if r then return r:wait() end end itable[key] = fcall -- add generated call to table (optimization) return fcall end -- bind an interface (listen to net requests) -- name: interface name -- interface: table containing functions function Tunnel.bindInterface(name,interface) -- receive request RegisterLocalEvent(name..":tunnel_req") AddEventHandler(name..":tunnel_req",function(member,args,identifier,rid) local source = source if Debug.active then Debug.pbegin("tunnelreq#"..rid.."_"..name..":"..member.." "..json.encode(Debug.safeTableCopy(args))) end local f = interface[member] local rets = {} if type(f) == "function" then -- call bound function rets = {f(table.unpack(args, 1, table.maxn(args)))} -- CancelEvent() -- cancel event doesn't seem to cancel the event for the other handlers, but if it does, uncomment this end -- send response (even if the function doesn't exist) if rid >= 0 then if SERVER then TriggerRemoteEvent(name..":"..identifier..":tunnel_res",source,rid,rets) else TriggerRemoteEvent(name..":"..identifier..":tunnel_res",rid,rets) end end if Debug.active then Debug.pend() end end) end -- get a tunnel interface to send requests -- name: interface name -- identifier: unique string to identify this tunnel interface access (if nil, will be the name of the resource) function Tunnel.getInterface(name,identifier) if not identifier then identifier = GetCurrentResourceName() end local ids = Tools.newIDGenerator() local callbacks = {} -- build interface local r = setmetatable({},{ __index = tunnel_resolve, name = name, tunnel_ids = ids, tunnel_callbacks = callbacks, identifier = identifier }) -- receive response RegisterLocalEvent(name..":"..identifier..":tunnel_res") AddEventHandler(name..":"..identifier..":tunnel_res",function(rid,args) if Debug.active then Debug.pbegin("tunnelres#"..rid.."_"..name.." "..json.encode(Debug.safeTableCopy(args))) end local callback = callbacks[rid] if callback then -- free request id ids:free(rid) callbacks[rid] = nil -- call callback(table.unpack(args, 1, table.maxn(args))) end Debug.pend() end) return r end return Tunnel
Try to fix hang issue with Tunnel call.
Try to fix hang issue with Tunnel call.
Lua
mit
ImagicTheCat/vRP,ImagicTheCat/vRP
e092f74b974286bce9491ab751d42ad72f13509d
modules/tollpost.lua
modules/tollpost.lua
local ev = require'ev' local util = require'util' local simplehttp = util.simplehttp local json = util.json local apiurl = 'http://www.tollpost.no/XMLServer/rest/trackandtrace/%s' local duration = 60 if(not ivar2.timers) then ivar2.timers = {} end -- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local function titlecase(str) local buf = {} for word in string.gfind(str, "%S+") do local first, rest = string.sub(word, 1, 1), string.sub(word, 2) table.insert(buf, string.upper(first) .. string.lower(rest)) end return table.concat(buf, " ") end local eventHandler = function(event) if not event then return nil end local out = {} local date = event.eventTime:sub(1,10) local time = event.eventTime:sub(12) table.insert(out, date) table.insert(out, time) table.insert(out, event.eventDescription) local location = event.location if location then local city = location['displayName'] if city and city ~= '' then city = '('..titlecase(city)..')' end table.insert(out, city) end return table.concat(out, ' ') end local shipmentTrack = function(self, source, destination, pid, alias) local nick = source.nick local id = pid .. nick local runningTimer = self.timers[id] if(runningTimer) then -- cancel existing timer self:Notice(nick, "Canceling existing tracking for alias %s.", alias) self.shipmentEvents[id] = -1 runningTimer:stop(ivar2.Loop) end -- Store the eventcount in the ivar2 global -- if the eventcount increases it means new events on the shipment happened. local eventCount = self.shipmentEvents[id] if not eventCount then self.shipmentEvents[id] = -1 end local timer = ev.Timer.new( function(loop, timer, revents) simplehttp(string.format(apiurl, pid), function(data) local info = json.decode(data) local root = info['TrackingInformationResponse'] local cs = root['shipments'] if not cs[1] then if self.shipmentEvents[id] == -1 then say('%s: Found nothing for shipment %s', nick, pid) end self.shipmentEvents[id] = 0 return else cs = cs[1] end local out = {} local items = cs['items'][1] local status = string.format('\002%s\002', titlecase(items['status'])) local events = items['events'] local newEventCount = #events print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id]) if newEventCount < self.shipmentEvents[id] then -- We can never go backwards return end if newEventCount > self.shipmentEvents[id] then table.insert(out, string.format('Status: %s', status)) end for i=self.shipmentEvents[id]+1,newEventCount do print('loop:',i) local event = events[i] table.insert(out, eventHandler(event)) -- Cancel event here somehow? end if #out > 0 then say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', ')) end self.shipmentEvents[id] = newEventCount end) end, 1, duration ) self.timers[id] = timer timer:start(ivar2.Loop) end local shipmentLocate = function(self, source, destination, pid) local nick = source.nick simplehttp(string.format(apiurl, pid), function(data) local info = json.decode(data) local root = info['TrackingInformationResponse'] local cs = root['shipments'] if not cs[1] then say('%s: Found nothing for shipment %s', nick, pid) return else cs = cs[1] end local out = {} local items = cs['items'][1] local status = string.format('\002%s\002', titlecase(items['status'])) table.insert(out, string.format('Status: %s', status)) for i, event in pairs(items['events']) do table.insert(out, eventHandler(event)) end say('%s: %s', nick, table.concat(out, ', ')) end) end local shipmentHelp = function(self, source, destination) return say('For lookup: !mypack pakkeid. For tracking: !mypack pakkeid alias') end return { PRIVMSG = { ['^%pmypack (%d+) (.*)$'] = shipmentTrack, ['^%pmypack (%d+)$'] = shipmentLocate, ['^%pmypack$'] = shipmentHelp, }, }
local ev = require'ev' local util = require'util' local simplehttp = util.simplehttp local json = util.json local apiurl = 'http://www.tollpost.no/XMLServer/rest/trackandtrace/%s' local duration = 60 if(not ivar2.timers) then ivar2.timers = {} end -- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local function titlecase(str) local buf = {} for word in string.gfind(str, "%S+") do local first, rest = string.sub(word, 1, 1), string.sub(word, 2) table.insert(buf, string.upper(first) .. string.lower(rest)) end return table.concat(buf, " ") end local eventHandler = function(event) if not event then return nil end local out = {} local date = event.eventTime:sub(1,10) local time = event.eventTime:sub(12) table.insert(out, date) table.insert(out, time) table.insert(out, event.eventDescription) local location = event.location if location then local city = location['displayName'] if city and city ~= '' then city = '('..titlecase(city)..')' end table.insert(out, city) end return table.concat(out, ' ') end local shipmentTrack = function(self, source, destination, pid, alias) local nick = source.nick local id = pid .. nick local runningTimer = self.timers[id] if(runningTimer) then -- cancel existing timer self:Notice(nick, "Canceling existing tracking for alias %s.", alias) self.shipmentEvents[id] = -1 runningTimer:stop(ivar2.Loop) end -- Store the eventcount in the ivar2 global -- if the eventcount increases it means new events on the shipment happened. local eventCount = self.shipmentEvents[id] if not eventCount then self.shipmentEvents[id] = -1 end local timer = ev.Timer.new( function(loop, timer, revents) simplehttp(string.format(apiurl, pid), function(data) local info = json.decode(data) local root = info['TrackingInformationResponse'] local cs = root['shipments'] if not cs[1] then if self.shipmentEvents[id] == -1 then say('%s: Found nothing for shipment %s', nick, pid) end self.shipmentEvents[id] = 0 return else cs = cs[1] end local out = {} local items = cs['items'][1] local status = string.format('\002%s\002', titlecase(items['status'])) local events = items['events'] local newEventCount = #events print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id]) if newEventCount < self.shipmentEvents[id] then -- We can never go backwards return end if newEventCount > self.shipmentEvents[id] then table.insert(out, string.format('Status: %s', status)) end for i=self.shipmentEvents[id]+1,newEventCount do print('loop:',i) local event = events[i] table.insert(out, eventHandler(event)) -- Cancel event here somehow? end if #out > 0 then say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', ')) end self.shipmentEvents[id] = newEventCount end) end, 1, duration ) self.timers[id] = timer timer:start(ivar2.Loop) end local shipmentLocate = function(self, source, destination, pid) local nick = source.nick simplehttp(string.format(apiurl, pid), function(data) local info = json.decode(data) local root = info['TrackingInformationResponse'] local cs = root['shipments'] if not cs[1] then say('%s: Found nothing for shipment %s', nick, pid) return else cs = cs[1] end local out = {} local items = cs['items'][1] local status = string.format('\002%s\002', titlecase(items['status'])) table.insert(out, string.format('Status: %s', status)) for i, event in pairs(items['events']) do table.insert(out, eventHandler(event)) end say('%s: %s', nick, table.concat(out, ', ')) end) end local shipmentHelp = function(self, source, destination) return say('For lookup: !mypack pakkeid. For tracking: !mypack pakkeid alias') end return { PRIVMSG = { ['^%pmypack (%d+) (.*)$'] = shipmentTrack, ['^%pmypack (%d+)$'] = shipmentLocate, ['^%pmypack$'] = shipmentHelp, }, }
tollpost: Remove trailing whitespaces and fix mixed indent.
tollpost: Remove trailing whitespaces and fix mixed indent. Former-commit-id: dfcafde67a82008a90ac2044a3c01cf3960af540 [formerly 9b0a839130b657963cfc72d68f7d051fbceb9a2f] Former-commit-id: b8132d1e3c7ff1830fbc4a5e796f61bd1c823c0d
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
c833c967505440717343dc5bd580dbb286e54b3f
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
--[[ Luci statistics - statistics controller module (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$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, template("admin_statistics/index"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
--[[ Luci statistics - statistics controller module (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$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
applications/luci-statistics: fix controller (#7344)
applications/luci-statistics: fix controller (#7344)
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,thesabbir/luci,ollie27/openwrt_luci,nmav/luci,RedSnake64/openwrt-luci-packages,palmettos/test,Wedmer/luci,thess/OpenWrt-luci,nmav/luci,jlopenwrtluci/luci,rogerpueyo/luci,NeoRaider/luci,thess/OpenWrt-luci,kuoruan/lede-luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,981213/luci-1,opentechinstitute/luci,RuiChen1113/luci,schidler/ionic-luci,male-puppies/luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,taiha/luci,maxrio/luci981213,jchuang1977/luci-1,joaofvieira/luci,Hostle/openwrt-luci-multi-user,taiha/luci,MinFu/luci,urueedi/luci,jchuang1977/luci-1,artynet/luci,rogerpueyo/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,david-xiao/luci,slayerrensky/luci,cappiewu/luci,zhaoxx063/luci,Noltari/luci,wongsyrone/luci-1,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,cshore/luci,urueedi/luci,jorgifumi/luci,kuoruan/luci,bittorf/luci,teslamint/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,sujeet14108/luci,nmav/luci,palmettos/cnLuCI,Hostle/luci,sujeet14108/luci,shangjiyu/luci-with-extra,oyido/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,oyido/luci,NeoRaider/luci,aa65535/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,opentechinstitute/luci,oyido/luci,artynet/luci,forward619/luci,tcatm/luci,cappiewu/luci,openwrt-es/openwrt-luci,sujeet14108/luci,RuiChen1113/luci,remakeelectric/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,Wedmer/luci,RuiChen1113/luci,nwf/openwrt-luci,dismantl/luci-0.12,tcatm/luci,jlopenwrtluci/luci,tcatm/luci,dwmw2/luci,oyido/luci,palmettos/cnLuCI,Hostle/luci,oneru/luci,kuoruan/luci,dismantl/luci-0.12,wongsyrone/luci-1,cshore-firmware/openwrt-luci,forward619/luci,lcf258/openwrtcn,florian-shellfire/luci,bright-things/ionic-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,dwmw2/luci,MinFu/luci,nmav/luci,openwrt/luci,Wedmer/luci,kuoruan/luci,cappiewu/luci,oyido/luci,openwrt/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,Hostle/luci,harveyhu2012/luci,keyidadi/luci,tcatm/luci,opentechinstitute/luci,RuiChen1113/luci,jchuang1977/luci-1,harveyhu2012/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,remakeelectric/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,joaofvieira/luci,kuoruan/luci,obsy/luci,ff94315/luci-1,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,981213/luci-1,MinFu/luci,kuoruan/luci,dwmw2/luci,Sakura-Winkey/LuCI,Noltari/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,palmettos/test,bright-things/ionic-luci,Noltari/luci,opentechinstitute/luci,bittorf/luci,ollie27/openwrt_luci,forward619/luci,florian-shellfire/luci,urueedi/luci,nwf/openwrt-luci,harveyhu2012/luci,deepak78/new-luci,male-puppies/luci,rogerpueyo/luci,taiha/luci,artynet/luci,ff94315/luci-1,schidler/ionic-luci,fkooman/luci,maxrio/luci981213,cshore/luci,cappiewu/luci,cshore/luci,Noltari/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,slayerrensky/luci,kuoruan/luci,Hostle/luci,rogerpueyo/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,bright-things/ionic-luci,teslamint/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,fkooman/luci,remakeelectric/luci,dismantl/luci-0.12,fkooman/luci,981213/luci-1,schidler/ionic-luci,Hostle/luci,opentechinstitute/luci,urueedi/luci,deepak78/new-luci,zhaoxx063/luci,dismantl/luci-0.12,chris5560/openwrt-luci,RuiChen1113/luci,bright-things/ionic-luci,zhaoxx063/luci,kuoruan/lede-luci,cappiewu/luci,bittorf/luci,artynet/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,maxrio/luci981213,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,ollie27/openwrt_luci,zhaoxx063/luci,sujeet14108/luci,palmettos/test,slayerrensky/luci,NeoRaider/luci,cshore/luci,nmav/luci,daofeng2015/luci,marcel-sch/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,fkooman/luci,Wedmer/luci,chris5560/openwrt-luci,jlopenwrtluci/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,teslamint/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,fkooman/luci,jchuang1977/luci-1,ff94315/luci-1,teslamint/luci,aa65535/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,ollie27/openwrt_luci,wongsyrone/luci-1,Wedmer/luci,opentechinstitute/luci,deepak78/new-luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,tobiaswaldvogel/luci,ff94315/luci-1,zhaoxx063/luci,Kyklas/luci-proto-hso,oneru/luci,NeoRaider/luci,kuoruan/luci,keyidadi/luci,aa65535/luci,forward619/luci,kuoruan/lede-luci,ff94315/luci-1,taiha/luci,bittorf/luci,palmettos/test,urueedi/luci,deepak78/new-luci,david-xiao/luci,jlopenwrtluci/luci,david-xiao/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,teslamint/luci,deepak78/new-luci,NeoRaider/luci,dwmw2/luci,deepak78/new-luci,thesabbir/luci,sujeet14108/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,cshore/luci,forward619/luci,wongsyrone/luci-1,nwf/openwrt-luci,harveyhu2012/luci,artynet/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,bittorf/luci,remakeelectric/luci,daofeng2015/luci,slayerrensky/luci,wongsyrone/luci-1,aa65535/luci,oneru/luci,mumuqz/luci,Noltari/luci,Hostle/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,Noltari/luci,tcatm/luci,schidler/ionic-luci,forward619/luci,lbthomsen/openwrt-luci,cappiewu/luci,lcf258/openwrtcn,nmav/luci,urueedi/luci,nmav/luci,lbthomsen/openwrt-luci,artynet/luci,deepak78/new-luci,chris5560/openwrt-luci,joaofvieira/luci,palmettos/cnLuCI,david-xiao/luci,florian-shellfire/luci,taiha/luci,oyido/luci,joaofvieira/luci,opentechinstitute/luci,thess/OpenWrt-luci,cshore/luci,lbthomsen/openwrt-luci,deepak78/new-luci,nwf/openwrt-luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,hnyman/luci,dismantl/luci-0.12,LuttyYang/luci,joaofvieira/luci,kuoruan/lede-luci,cshore/luci,RedSnake64/openwrt-luci-packages,bittorf/luci,teslamint/luci,thess/OpenWrt-luci,sujeet14108/luci,maxrio/luci981213,schidler/ionic-luci,daofeng2015/luci,chris5560/openwrt-luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,Hostle/openwrt-luci-multi-user,MinFu/luci,wongsyrone/luci-1,hnyman/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,keyidadi/luci,joaofvieira/luci,thess/OpenWrt-luci,remakeelectric/luci,bittorf/luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,palmettos/test,cshore-firmware/openwrt-luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,male-puppies/luci,thesabbir/luci,male-puppies/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,wongsyrone/luci-1,tcatm/luci,jchuang1977/luci-1,mumuqz/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,981213/luci-1,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,tobiaswaldvogel/luci,mumuqz/luci,mumuqz/luci,daofeng2015/luci,rogerpueyo/luci,obsy/luci,jchuang1977/luci-1,hnyman/luci,marcel-sch/luci,artynet/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,Hostle/luci,artynet/luci,openwrt-es/openwrt-luci,marcel-sch/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,tobiaswaldvogel/luci,slayerrensky/luci,obsy/luci,MinFu/luci,tobiaswaldvogel/luci,ff94315/luci-1,florian-shellfire/luci,marcel-sch/luci,openwrt/luci,david-xiao/luci,ff94315/luci-1,openwrt/luci,openwrt/luci,LuttyYang/luci,shangjiyu/luci-with-extra,aa65535/luci,dwmw2/luci,zhaoxx063/luci,openwrt/luci,nwf/openwrt-luci,Wedmer/luci,aa65535/luci,taiha/luci,dismantl/luci-0.12,thesabbir/luci,keyidadi/luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,db260179/openwrt-bpi-r1-luci,oneru/luci,MinFu/luci,florian-shellfire/luci,slayerrensky/luci,obsy/luci,rogerpueyo/luci,dwmw2/luci,thesabbir/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,hnyman/luci,marcel-sch/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,obsy/luci,kuoruan/lede-luci,LuttyYang/luci,Hostle/luci,forward619/luci,palmettos/cnLuCI,Kyklas/luci-proto-hso,ff94315/luci-1,MinFu/luci,rogerpueyo/luci,teslamint/luci,obsy/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,hnyman/luci,obsy/luci,oneru/luci,palmettos/test,rogerpueyo/luci,thess/OpenWrt-luci,jorgifumi/luci,ollie27/openwrt_luci,taiha/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,LuttyYang/luci,LuttyYang/luci,harveyhu2012/luci,jorgifumi/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,keyidadi/luci,thesabbir/luci,lcf258/openwrtcn,thesabbir/luci,palmettos/cnLuCI,bright-things/ionic-luci,cappiewu/luci,bittorf/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,urueedi/luci,palmettos/test,cshore/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,male-puppies/luci,david-xiao/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,openwrt/luci,jchuang1977/luci-1,oneru/luci,Wedmer/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,teslamint/luci,RedSnake64/openwrt-luci-packages,oyido/luci,RuiChen1113/luci,nmav/luci,aa65535/luci,NeoRaider/luci,joaofvieira/luci,oneru/luci,MinFu/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,taiha/luci,lcf258/openwrtcn,bright-things/ionic-luci,slayerrensky/luci,keyidadi/luci,david-xiao/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,tcatm/luci,kuoruan/lede-luci,jorgifumi/luci,keyidadi/luci,jlopenwrtluci/luci,kuoruan/luci,schidler/ionic-luci,forward619/luci,daofeng2015/luci,david-xiao/luci,male-puppies/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,remakeelectric/luci,NeoRaider/luci,RuiChen1113/luci,marcel-sch/luci,RuiChen1113/luci,sujeet14108/luci,Kyklas/luci-proto-hso,LuttyYang/luci,male-puppies/luci,artynet/luci,openwrt-es/openwrt-luci,maxrio/luci981213,florian-shellfire/luci,remakeelectric/luci,daofeng2015/luci,lcf258/openwrtcn,hnyman/luci,palmettos/test,LuttyYang/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,jorgifumi/luci,Noltari/luci,NeoRaider/luci,marcel-sch/luci,slayerrensky/luci,fkooman/luci,maxrio/luci981213,openwrt-es/openwrt-luci,hnyman/luci
465401e3aa14123b234ff6ace7a77949058c46b1
Peripherals/FDD/init.lua
Peripherals/FDD/init.lua
local perpath = select(1,...) --The path to the FDD folder local bit = require("bit") local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift local function exe(ok,err,...) if ok then return err,... else return error(err or "NULL") end end return function(config) local GPUKit = config.GPUKit or error("The FDD peripheral requires the GPUKit") local RAM = config.RAM or error("The FDD peripheral requires the RAM peripheral") local FIMG --The floppy disk image local DiskSize = config.DiskSize or 64*1024 --The floppy disk size local FRAMAddress = config.FRAMAddress or 0 --The floppy ram start address --The color palette local ColorSet = {} for i=0,15 do local r,g,b,a = unpack(GPUKit._ColorSet[i]) r,g,b,a = band(r,252), band(g,252), band(b,252), 252 ColorSet[i] = {r,g,b,a} ColorSet[r*10^9 + g*10^6 + b*10^3 + a] = i end --The label image local LabelImage = GPUKit.LabelImage local LabelX, LabelY, LabelW, LabelH = 32,120, GPUKit._LIKO_W, GPUKit._LIKO_H --DiskCleanupMapper local function _CleanUpDisk(x,y,r,g,b,a) return band(r,252), band(g,252), band(b,252), band(a,252) end --DiskWriteMapper local WritePos = 0 local function _WriteDisk(x,y,r,g,b,a) local byte = exe(RAM.peek(FRAMAddress+WritePos)) r = bor(r, band( rshift(byte ,6), 3) ) g = bor(g, band( rshift(byte ,4), 3) ) b = bor(b, band( rshift(byte ,2), 3) ) a = bor(a, band(byte,3)) WritePos = (WritePos + 1) % (DiskSize) return r, g, b, a end --DiskReadMapper local ReadPos = 0 local function _ReadDisk(x,y,r,g,b,a) local r2 = lshift( band(r, 3), 6) local g2 = lshift( band(g, 3), 4) local b2 = lshift( band(b, 3), 2) local a2 = band(a, 3) local byte = bor(r2,g2,b2,a2) RAM.poke(FRAMAddress+ReadPos,byte) ReadPos = (ReadPos + 1) % (DiskSize) return r, g, b, a end --LabelDrawMapper local function _DrawLabel(x,y,r,g,b,a) FIMG:setPixel(LabelX+x,LabelY+y,unpack(ColorSet[r])) return r,g,b,a end --LabelScanMapper local function _ScanLabel(x,y,r,g,b,a) local r,g,b,a = band(r,252), band(g,252), band(b,252), band(a,252) local code = r*10^9 + g*10^6 + b*10^3 + a local id = ColorSet[code] or 0 LabelImage:setPixel(x,y,id,0,0,255) end --The API starts here-- local fapi, yfapi = {}, {} --Create a new floppy disk and mount it --tname -> template name, without the .png extension function fapi.newDisk(tname) local tname = tname or "Disk" if type(tname) ~= "string" then return error("Disk template name must be a string or a nil, provided: "..type(tname)) end if not love.filesystem.exists(perpath..tname..".png") then return error("Disk template '"..tname.."' doesn't exist !") end FIMG = love.image.newImageData(perpath..tname..".png") end function fapi.exportDisk() --Clean up any already existing data on the disk. FIMG:mapPixel(_CleanUpDisk) --Write the label image LabelImage:mapPixel(_DrawLabel) --Write new data FIMG:mapPixel(_WriteDisk) return FIMG:encode("png"):getString() end function fapi.importDisk(data) if type(data) ~= "string" then return error("Data must be a string, provided: "..type(data)) end FIMG = love.image.newImageData(love.filesystem.newFileData(data,"image.png")) --Scan the label image for y=LabelY,LabelY+LabelH-1 do for x=LabelX,LabelX+LabelW-1 do _ScanLabel(x-LabelX,y-LabelY,FIMG:getPixel(x,y)) end end --Read the data FIMG:mapPixel(_ReadDisk) end --Initialize with the default disk fapi.newDisk() return fapi end
local perpath = select(1,...) --The path to the FDD folder local bit = require("bit") local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift return function(config) local GPUKit = config.GPUKit or error("The FDD peripheral requires the GPUKit") local RAM = config.RAM or error("The FDD peripheral requires the RAM peripheral") local FIMG --The floppy disk image local DiskSize = config.DiskSize or 64*1024 --The floppy disk size local FRAMAddress = config.FRAMAddress or 0 --The floppy ram start address --The color palette local ColorSet = {} for i=0,15 do local r,g,b,a = unpack(GPUKit._ColorSet[i]) r,g,b,a = band(r,252), band(g,252), band(b,252), 252 ColorSet[i] = {r,g,b,a} ColorSet[r*10^9 + g*10^6 + b*10^3 + a] = i end --The label image local LabelImage = GPUKit.LabelImage local LabelX, LabelY, LabelW, LabelH = 32,120, GPUKit._LIKO_W, GPUKit._LIKO_H --DiskCleanupMapper local function _CleanUpDisk(x,y,r,g,b,a) return band(r,252), band(g,252), band(b,252), band(a,252) end --DiskWriteMapper local WritePos = 0 local function _WriteDisk(x,y,r,g,b,a) local byte = RAM.peek(FRAMAddress+WritePos) r = bor(r, band( rshift(byte ,6), 3) ) g = bor(g, band( rshift(byte ,4), 3) ) b = bor(b, band( rshift(byte ,2), 3) ) a = bor(a, band(byte,3)) WritePos = (WritePos + 1) % (DiskSize) return r, g, b, a end --DiskReadMapper local ReadPos = 0 local function _ReadDisk(x,y,r,g,b,a) local r2 = lshift( band(r, 3), 6) local g2 = lshift( band(g, 3), 4) local b2 = lshift( band(b, 3), 2) local a2 = band(a, 3) local byte = bor(r2,g2,b2,a2) RAM.poke(FRAMAddress+ReadPos,byte) ReadPos = (ReadPos + 1) % (DiskSize) return r, g, b, a end --LabelDrawMapper local function _DrawLabel(x,y,r,g,b,a) FIMG:setPixel(LabelX+x,LabelY+y,unpack(ColorSet[r])) return r,g,b,a end --LabelScanMapper local function _ScanLabel(x,y,r,g,b,a) local r,g,b,a = band(r,252), band(g,252), band(b,252), band(a,252) local code = r*10^9 + g*10^6 + b*10^3 + a local id = ColorSet[code] or 0 LabelImage:setPixel(x,y,id,0,0,255) end --The API starts here-- local fapi, yfapi = {}, {} --Create a new floppy disk and mount it --tname -> template name, without the .png extension function fapi.newDisk(tname) local tname = tname or "Disk" if type(tname) ~= "string" then return error("Disk template name must be a string or a nil, provided: "..type(tname)) end if not love.filesystem.exists(perpath..tname..".png") then return error("Disk template '"..tname.."' doesn't exist !") end FIMG = love.image.newImageData(perpath..tname..".png") end function fapi.exportDisk() --Clean up any already existing data on the disk. FIMG:mapPixel(_CleanUpDisk) --Write the label image LabelImage:mapPixel(_DrawLabel) --Write new data FIMG:mapPixel(_WriteDisk) return FIMG:encode("png"):getString() end function fapi.importDisk(data) if type(data) ~= "string" then return error("Data must be a string, provided: "..type(data)) end FIMG = love.image.newImageData(love.filesystem.newFileData(data,"image.png")) --Scan the label image for y=LabelY,LabelY+LabelH-1 do for x=LabelX,LabelX+LabelW-1 do _ScanLabel(x-LabelX,y-LabelY,FIMG:getPixel(x,y)) end end --Read the data FIMG:mapPixel(_ReadDisk) end --Initialize with the default disk fapi.newDisk() return fapi end
Crash fix
Crash fix Former-commit-id: 7284a92d3f5953daca34a594a37c7af4825a20f4
Lua
mit
RamiLego4Game/LIKO-12
67537db200c21a29f80ba831dac91469d913b65c
webpaste.lua
webpaste.lua
args = {} settings = args[1] return doctype()( tag"head"( tag"title" "CPaste WebPaste", tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](), tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](), tag"script"([[ $(document).ready(function() { $('#submit').click(function() { var pasteType = $(".pasteType:checked").val(); var sentType = "plain"; if (pasteType == "Normal") sentType = "plain"; if (pasteType == "Raw") sentType = "raw"; if (pasteType == "HTML") sentType = "html"; $.ajax({ data: { c: $('textarea').val(), type: sentType }, type: "POST", url: $('#submit').attr('action'), success: function(response) { $('#resultholder').css({ display: "block" }); $('#result').html(response); $('#result').attr("href", response); console.log( response ) } }); return false }); }); ]]), tag"style"[{type="text/css"}]([[ html, body, form { overflow: hidden; margin: 0px; width: 100%; height: 100%; } button { padding: 5px; background-color: #111; border: 2px solid #dcdcdc; color: #dcdcdc; text-decoration: none; position: absolute; left: 3px; bottom: 3px; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } button:hover { background-color: #010101; } pasteType { padding: 5px; background-color: #010101; color: #dcdcdc; position: absolute; bottom: 3px; left: 60px; } textarea { background-color: #010101; border: 0px; color: #fff; width: 100%; height: 100%; resize: none; } div#resultholder { padding: 5px; background-color: #010101; border: 2px solid #dcdcdc; position: fixed; left: 50%; top: 50%; -webkit-transform: translate( -50%, -50% ); -moz-transform: translate( -50%, -50% ); -ms-transform: translate( -50%, -50% ); transform: translate( -50%, -50% ); display: none; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } a#result { color: #dcdcdc; } ]]) ), tag"body"( tag"textarea"[{name="c", placeholder="Hello World!"}](), tag"button"[{id="submit",action=ret.url}]("Paste!"), tag"input"[{type="radio",class="pasteType",name="pasteType"}]("Normal"), tag"input"[{type="radio",class="pasteType",name="pasteType"}]("Raw"), tag"input"[{type="radio",class="pasteType",name="pasteType"}]("HTML"), tag"div"[{id="resultholder"}]( tag"a"[{id="result"}] ) ) ):render()
args = {} settings = args[1] return doctype()( tag"head"( tag"title" "CPaste WebPaste", tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](), tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](), tag"script"([[ $(document).ready(function() { $('#submit').click(function() { var pasteType = $(".pasteType:checked").val(); var sentType = "plain"; if (pasteType == "Normal") sentType = "plain"; if (pasteType == "Raw") sentType = "raw"; if (pasteType == "HTML") sentType = "html"; $.ajax({ data: { c: $('textarea').val(), type: sentType }, type: "POST", url: $('#submit').attr('action'), success: function(response) { $('#resultholder').css({ display: "block" }); $('#result').html(response); $('#result').attr("href", response); console.log( response ) } }); return false }); }); ]]), tag"style"[{type="text/css"}]([[ html, body, form { overflow: hidden; margin: 0px; width: 100%; height: 100%; } button { padding: 5px; background-color: #111; border: 2px solid #dcdcdc; color: #dcdcdc; text-decoration: none; position: absolute; left: 3px; bottom: 3px; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } button:hover { background-color: #010101; } div.pasteTypeHolder { padding: 5px; background-color: #010101; color: #dcdcdc; position: absolute; bottom: 3px; left: 60px; } textarea { background-color: #010101; border: 0px; color: #fff; width: 100%; height: 100%; resize: none; } div#resultholder { padding: 5px; background-color: #010101; border: 2px solid #dcdcdc; position: fixed; left: 50%; top: 50%; -webkit-transform: translate( -50%, -50% ); -moz-transform: translate( -50%, -50% ); -ms-transform: translate( -50%, -50% ); transform: translate( -50%, -50% ); display: none; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } a#result { color: #dcdcdc; } ]]) ), tag"body"( tag"textarea"[{name="c", placeholder="Hello World!"}](), tag"button"[{id="submit",action=ret.url}]("Paste!"), tag"div"[{class="pasteTypeHolder"}]( tag"input"[{type="radio",class="pasteType",name="pasteType"}]("Normal"), tag"input"[{type="radio",class="pasteType",name="pasteType"}]("Raw"), tag"input"[{type="radio",class="pasteType",name="pasteType"}]("HTML") ), tag"div"[{id="resultholder"}]( tag"a"[{id="result"}] ) ) ):render()
I think I fixed it
I think I fixed it
Lua
mit
carbonsrv/cpaste,vifino/cpaste
5c5380ca90496e8488e06c13ba3cdcb530b7aa40
languages/unicode.lua
languages/unicode.lua
require("char-def") local chardata = characters.data icu = require("justenoughicu") SILE.nodeMakers.base = std.object { makeToken = function(self) if #self.contents>0 then coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options)) SU.debug("tokenizer", "Token: "..self.token) self.contents = {} ; self.token = "" ; self.lastnode = "nnode" end end, makeLetterSpaceGlue = function(self) if self.lastnode ~= "glue" then if SILE.settings.get("document.letterspaceglue") then local w = SILE.settings.get("document.letterspaceglue").width coroutine.yield(SILE.nodefactory.newKern({ width = w })) end end self.lastnode = "glue" end, addToken = function (self, char, item) self.token = self.token .. char self.contents[#self.contents+1] = item end, makeGlue = function(self,item) if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item)) end self.lastnode = "glue" end, makePenalty = function (self,p) if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) ) end self.lastnode = "penalty" end, init = function (self) self.contents = {} self.token = "" self.lastnode = "" end, iterator = function (self,items) SU.error("Abstract function nodemaker:iterator called", true) end } SILE.nodeMakers.unicode = SILE.nodeMakers.base { isWordType = { cm = true }, isSpaceType = { sp = true }, isBreakingType = { ba = true, zw = true }, dealWith = function (self, item) local char = item.text local cp = SU.codepoint(char) local thistype = chardata[cp] and chardata[cp].linebreak if chardata[cp] and self.isSpaceType[thistype] then self:makeToken() self:makeGlue(item) elseif chardata[cp] and self.isBreakingType[thistype] then self:addToken(char,item) self:makeToken() self:makePenalty(0) elseif lasttype and (thistype and thistype ~= lasttype and not self.isWordType[thistype]) then self:makeToken() self:addToken(char,item) else if SILE.settings.get("document.letterspaceglue") then self:makeToken() self:makeLetterSpaceGlue() end self:addToken(char,item) end if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end end, iterator = function (self, items) local fulltext = "" local ics = SILE.settings.get("document.letterspaceglue") for i = 1,#items do item = items[i] fulltext = fulltext .. items[i].text end local chunks = {icu.breakpoints(fulltext, self.options.language)} self:init() table.remove(chunks,1) return coroutine.wrap(function() -- Special-case initial glue local i = 1 while i <= #items do item = items[i] local char = item.text local cp = SU.codepoint(char) local thistype = chardata[cp] and chardata[cp].linebreak if thistype == "sp" then self:makeGlue(item) else break end i = i + 1 end -- And now onto the real thing for i = i,#items do item = items[i] local char = items[i].text local cp = SU.codepoint(char) if chunks[1] and (items[i].index >= chunks[1].index) then -- There's a break here local thistype = chardata[cp] and chardata[cp].linebreak local bp = chunks[1] while chunks[1] and items[i].index >= chunks[1].index do table.remove(chunks,1) end if bp.type == "word" then if chardata[cp] and thistype == "sp" then -- Spacing word break self:makeToken() self:makeGlue(item) else -- a word break which isn't a space self:makeToken() self:addToken(char,item) end elseif bp.type == "line" then if chardata[cp] and thistype == "sp" then self:makeToken() self:makeGlue(item) else -- Line break self:makeToken() self:makePenalty(bp.subtype == "soft" and 0 or -1000) self:addToken(char,item) end end else local thistype = chardata[cp] and chardata[cp].linebreak if ics then self:makeToken() self:makeLetterSpaceGlue() end if chardata[cp] and thistype == "sp" then self:makeToken() self:makeGlue(item) else self:addToken(char,item) end end end if ics then self:makeLetterSpaceGlue() end self:makeToken() end) end }
require("char-def") local chardata = characters.data icu = require("justenoughicu") SILE.nodeMakers.base = std.object { makeToken = function(self) if #self.contents>0 then coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options)) SU.debug("tokenizer", "Token: "..self.token) self.contents = {} ; self.token = "" ; self.lastnode = "nnode" end end, makeLetterSpaceGlue = function(self) if self.lastnode ~= "glue" then if SILE.settings.get("document.letterspaceglue") then local w = SILE.settings.get("document.letterspaceglue").width coroutine.yield(SILE.nodefactory.newKern({ width = w })) end end self.lastnode = "glue" end, addToken = function (self, char, item) self.token = self.token .. char self.contents[#self.contents+1] = item end, makeGlue = function(self,item) if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item)) end self.lastnode = "glue" end, makePenalty = function (self,p) if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) ) end self.lastnode = "penalty" end, init = function (self) self.contents = {} self.token = "" self.lastnode = "" self.lasttype = false end, iterator = function (self,items) SU.error("Abstract function nodemaker:iterator called", true) end, charData = function(self, char) local cp = SU.codepoint(char) if not chardata[cp] then return {} end return chardata[cp] end, isSpace = function(self, char) return self.isSpaceType[self:charData(char).linebreak] end, isBreaking = function(self, char) return self.isBreakingType[self:charData(char).linebreak] end } SILE.nodeMakers.unicode = SILE.nodeMakers.base { isWordType = { cm = true }, isSpaceType = { sp = true }, isBreakingType = { ba = true, zw = true }, dealWith = function (self, item) local char = item.text local cp = SU.codepoint(char) local thistype = chardata[cp] and chardata[cp].linebreak if self:isSpace(item.text) then self:makeToken() self:makeGlue(item) elseif self:isBreaking(item.text) then self:addToken(char,item) self:makeToken() self:makePenalty(0) elseif self.lasttype and (self.thistype and thistype ~= lasttype and not self.isWordType[thistype]) then self:makeToken() self:addToken(char,item) else if SILE.settings.get("document.letterspaceglue") then self:makeToken() self:makeLetterSpaceGlue() end self:addToken(char,item) end if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end self.lasttype = thistype end, handleInitialGlue = function(self, items) local i = 1 while i <= #items do item = items[i] local char = item.text if self:isSpace(item.text) then self:makeGlue(item) else break end i = i + 1 end return i,items end, letterspace = function() if not SILE.settings.get("document.letterspaceglue") then return end if self.token then self:makeToken() end self:makeLetterSpaceGlue() end, isICUBreakHere = function(self, chunks, item) return chunks[1] and (item.index >= chunks[1].index) end, handleICUBreak = function(self, chunks, item) -- The ICU library has told us there is a breakpoint at -- this index. We need to... local bp = chunks[1] -- ... remove this breakpoint (and any out of order ones) -- from the ICU breakpoints array so that chunks[1] is -- the next index point for comparison against the string... while chunks[1] and item.index >= chunks[1].index do table.remove(chunks,1) end -- ...decide which kind of breakpoint we have here and -- handle it appropriately. if bp.type == "word" then self:handleWordBreak(item) elseif bp.type == "line" then self:handleLineBreak(item, bp.subtype) end return chunks end, handleWordBreak = function(self, item) self:makeToken() if self:isSpace(item.text) then -- Spacing word break self:makeGlue(item) else -- a word break which isn't a space self:addToken(item.text,item) end end, handleLineBreak = function(self, item, subtype) -- Because we are in charge of paragraphing, we -- will override space-type line breaks, and treat -- them just as ordinary word spaces. if self:isSpace(item.text) then self:handleWordBreak(item) return end -- But explicit line breaks we will turn into -- soft and hard breaks. self:makeToken() self:makePenalty(subtype == "soft" and 0 or -1000) self:addToken(item.text,item) end, iterator = function (self, items) local fulltext = "" for i = 1,#items do item = items[i] fulltext = fulltext .. items[i].text end local chunks = {icu.breakpoints(fulltext, self.options.language)} self:init() table.remove(chunks,1) return coroutine.wrap(function() local i i, items = self:handleInitialGlue(items) for i = i,#items do item = items[i] if self:isICUBreakHere(chunks, item) then chunks = self:handleICUBreak(chunks, item) else self:dealWith(item) end end self:makeToken() end) end }
refactor(languages): Tidy up ICU-based shaper
refactor(languages): Tidy up ICU-based shaper The best way to solve the French bug is to create a French-specific nodemaker. But currently writing a nodemaker involves copying a lot of boilerplate code. Some of this is also confusing because there is a lot of overlap between the ICU nodemaker (which asks ICU about breakpoints) and the “general Unicode” nodemaker (the `dealWith` method, which deals with tokens in isolation). Hopefully this refactoring will help with the mess. The next stage is tests for and refactoring of languages which use their own nodemakers, and then we can get on to French.
Lua
mit
alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile,simoncozens/sile
9406f3223335e6affe6214d904ade29584b721ff
testbed/units.lua
testbed/units.lua
require "tundra.syntax.glob" -- Used to generate the moc cpp files as needed for .h that uses Q_OBJECT DefRule { Name = "MocGeneration", Pass = "GenerateSources", Command = "$(QT5)/bin/moc $(<) -o $(@)", Blueprint = { Source = { Required = true, Type = "string", Help = "Input filename", }, OutName = { Required = true, Type = "string", Help = "Output filename", }, }, Setup = function (env, data) return { InputFiles = { data.Source }, OutputFiles = { "$(OBJECTDIR)/_generated/" .. data.OutName }, } end, } -- Example 6502 emulator Program { Name = "Fake6502", Env = { CCOPTS = { { "-Wno-conversion", "-Wno-pedantic"; Config = "macosx-*-*" }, }, }, Sources = { Glob { Dir = "examples/Fake6502", Extensions = { ".c", ".cpp", ".m" }, }, }, } -- Core Lib StaticLibrary { Name = "core", Env = { CXXOPTS = { { "-Wno-global-constructors", "-Wno-exit-time-destructors" ; Config = "macosx-clang-*" }, }, CPPPATH = { "src/frontend", "API" } }, Sources = { Glob { Dir = "src/frontend/core", Extensions = { ".c", ".cpp", ".m" }, }, }, } ---------- Plugins ----------------- SharedLibrary { Name = "LLDBPlugin", Env = { CPPPATH = { "API", "plugins/lldb", "plugins/lldb/Frameworks/LLDB.Framework/Headers", }, CXXOPTS = { { "-Wno-padded", "-Wno-documentation", "-Wno-unused-parameter", "-Wno-missing-prototypes", "-Wno-unused-member-function", "-Wno-c++98-compat-pedantic" ; Config = "macosx-clang-*" }, }, SHLIBOPTS = { { "-Fplugins/lldb/Frameworks", "-lstdc++"; Config = "macosx-clang-*" }, }, CXXCOM = { "-std=c++11", "-stdlib=libc++"; Config = "macosx-clang-*" }, }, Sources = { Glob { Dir = "plugins/lldb", Extensions = { ".c", ".cpp", ".m" }, }, }, Frameworks = { "LLDB" }, } ------------------------------------ Program { Name = "prodbg-qt5", Env = { CPPPATH = { ".", "API", "src/frontend", "$(QT5)/include/QtWidgets", "$(QT5)/include/QtGui", "$(QT5)/include/QtCore", "$(QT5)/include", }, PROGOPTS = { { "/SUBSYSTEM:WINDOWS", "/DEBUG"; Config = { "win32-*-*", "win64-*-*" } }, }, CPPDEFS = { { "PRODBG_MAC", Config = "macosx-*-*" }, { "PRODBG_WIN"; Config = { "win32-*-*", "win64-*-*" } }, }, CXXOPTS = { { "-Wno-padded", "-Wno-global-constructors", "-Wno-long-long", "-Wno-unreachable-code", "-Wno-float-equal", "-Wno-disabled-macro-expansion", "-Wno-conversion", "-Wno-weak-vtables", "-Wno-sign-conversion" ; Config = "macosx-clang-*" }, }, PROGCOM = { -- hacky hacky { "-F$(QT5)/lib", "-lstdc++", "-rpath tundra-output$(SEP)macosx-clang-debug-default"; Config = "macosx-clang-*" }, }, }, Sources = { FGlob { Dir = "src/frontend/Qt5", Extensions = { ".c", ".cpp", ".m" }, Filters = { { Pattern = "macosx"; Config = "macosx-*-*" }, { Pattern = "windows"; Config = { "win32-*-*", "win64-*-*" } }, }, }, MocGeneration { Source = "src/frontend/Qt5/Qt5CodeEditor.h", OutName = "Qt5CodeEditor_moc.cpp" }, MocGeneration { Source = "src/frontend/Qt5/Qt5MainWindow.h", OutName = "Qt5MainWindow_moc.cpp" }, }, Depends = { "core" }, Libs = { { "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = "win32-*-*" } }, Frameworks = { "Cocoa", "QtWidgets", "QtGui", "QtCore", "QtConcurrent" }, } Default "LLDBPlugin" Default "Fake6502" Default "prodbg-qt5"
require "tundra.syntax.glob" -- Used to generate the moc cpp files as needed for .h that uses Q_OBJECT DefRule { Name = "MocGeneration", Pass = "GenerateSources", Command = "$(QT5)/bin/moc $(<) -o $(@)", Blueprint = { Source = { Required = true, Type = "string", Help = "Input filename", }, OutName = { Required = true, Type = "string", Help = "Output filename", }, }, Setup = function (env, data) return { InputFiles = { data.Source }, OutputFiles = { "$(OBJECTDIR)/_generated/" .. data.OutName }, } end, } -- Example 6502 emulator Program { Name = "Fake6502", Env = { CCOPTS = { { "-Wno-conversion", "-Wno-pedantic"; Config = "macosx-*-*" }, }, }, Sources = { Glob { Dir = "examples/Fake6502", Extensions = { ".c", ".cpp", ".m" }, }, }, } -- Core Lib StaticLibrary { Name = "core", Env = { CXXOPTS = { { "-Wno-global-constructors", "-Wno-exit-time-destructors" ; Config = "macosx-clang-*" }, }, CPPPATH = { "src/frontend", "API" } }, Sources = { Glob { Dir = "src/frontend/core", Extensions = { ".c", ".cpp", ".m" }, }, }, } ---------- Plugins ----------------- SharedLibrary { Name = "LLDBPlugin", Env = { CPPPATH = { "API", "plugins/lldb", "plugins/lldb/Frameworks/LLDB.Framework/Headers", }, CXXOPTS = { { "-std=c++11", "-Wno-padded", --"-Wno-documentation", "-Wno-unused-parameter", "-Wno-missing-prototypes", "-Wno-unused-member-function", "-Wno-c++98-compat-pedantic" ; Config = "macosx-clang-*" }, }, SHLIBOPTS = { { "-Fplugins/lldb/Frameworks", "-lstdc++"; Config = "macosx-clang-*" }, }, CXXCOM = { "-stdlib=libc++"; Config = "macosx-clang-*" }, }, Sources = { Glob { Dir = "plugins/lldb", Extensions = { ".c", ".cpp", ".m" }, }, }, Frameworks = { "LLDB" }, } ------------------------------------ Program { Name = "prodbg-qt5", Env = { CPPPATH = { ".", "API", "src/frontend", "$(QT5)/include/QtWidgets", "$(QT5)/include/QtGui", "$(QT5)/include/QtCore", "$(QT5)/include", }, PROGOPTS = { { "/SUBSYSTEM:WINDOWS", "/DEBUG"; Config = { "win32-*-*", "win64-*-*" } }, }, CPPDEFS = { { "PRODBG_MAC", Config = "macosx-*-*" }, { "PRODBG_WIN"; Config = { "win32-*-*", "win64-*-*" } }, }, CXXOPTS = { { --"-mmacosx-version-min=10.7", "-std=gnu0x", "-std=c++11", "-stdlib=libc++", "-Wno-padded", "-Wno-c++98-compat", "-Wno-c++98-compat-pedantic", "-Wno-global-constructors", "-Wno-long-long", "-Wno-unreachable-code", "-Wno-float-equal", "-Wno-disabled-macro-expansion", "-Wno-conversion", "-Wno-weak-vtables", "-Wno-sign-conversion" ; Config = "macosx-clang-*" }, }, PROGCOM = { -- hacky hacky { "-F$(QT5)/lib", "-lstdc++", "-rpath tundra-output$(SEP)macosx-clang-debug-default"; Config = "macosx-clang-*" }, }, }, Sources = { FGlob { Dir = "src/frontend/Qt5", Extensions = { ".c", ".cpp", ".m" }, Filters = { { Pattern = "macosx"; Config = "macosx-*-*" }, { Pattern = "windows"; Config = { "win32-*-*", "win64-*-*" } }, }, }, MocGeneration { Source = "src/frontend/Qt5/Qt5CodeEditor.h", OutName = "Qt5CodeEditor_moc.cpp" }, MocGeneration { Source = "src/frontend/Qt5/Qt5MainWindow.h", OutName = "Qt5MainWindow_moc.cpp" }, }, Depends = { "core" }, Libs = { { "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = "win32-*-*" } }, Frameworks = { "Cocoa", "QtWidgets", "QtGui", "QtCore", "QtConcurrent" }, } Default "LLDBPlugin" Default "Fake6502" Default "prodbg-qt5"
Fixed so Qt5 code can use c++11
Fixed so Qt5 code can use c++11
Lua
mit
RobertoMalatesta/ProDBG,ashemedai/ProDBG,emoon/ProDBG,v3n/ProDBG,emoon/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,v3n/ProDBG,kondrak/ProDBG,emoon/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,emoon/ProDBG,v3n/ProDBG,kondrak/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,kondrak/ProDBG
f124c40f536fb1f0aa91227e9e92283164d98b6e
chooseAP.lua
chooseAP.lua
-- works using least memory if compiled, otherwise you may -- run out of memory and the module will randomly restart and -- drop connections local SSID = nil local pass = nil local otherSSID = nil local errMsg = nil local savedNetwork = false local SSIDs = {} -- lookup table for wifi.sta.status() local statusTable = {} -- statusTable[0] = "neither connected nor connecting" -- statusTable[1] = "still connecting" statusTable["2"] = "wrong password" statusTable["3"] = "didn\'t find the network you specified" statusTable["4"] = "failed to connect" -- statusTable[5] = "successfully connected" collectgarbage() wifi.setmode(wifi.STATIONAP) print('wifi status: '..wifi.sta.status()) print(node.heap()) -- opens saved list of nearby networks and puts into SSIDs table file.open('networkList','r') local counter = 0 local line = "" while (true) do line = file.readline() if line == nil then break end counter = counter + 1 SSIDs[counter] = line end print(node.heap()) -- start server running on ESP-8266, usually is IP 192.168.4.1 local cfg = {} cfg.ssid = "myfi" cfg.pwd = "mystical" wifi.ap.config(cfg) cfg = nil local srv=net.createServer(net.TCP,30) print('connect to this ip on your computer/phone: '..wifi.ap.getip()) srv:listen(80,function(conn) conn:on("receive", function(client,request) local connecting = false local _, _, SSID, pass = string.find(request, "SSID=(.+)%%0D%%0A&otherSSID=&password=(.*)"); print(node.heap()) if (pass~=nil and pass~="") then if (string.len(pass)<8) then local pass = nil errMsg = "<center><h2 style=\"color:red\">Whoops! Password must be at least 8 characters.<\h2><\center>" end end if (SSID==nil) then _, _, SSID, pass = string.find(request, "SSID=&otherSSID=(.+)%%0D%%0A&password=(.*)"); end print(request) local buf = ""; -- if password for network is nothing, any password should work if (SSID~=nil) then if (pass == "") then pass = "aaaaaaaa" end print(SSID..', '..pass) wifi.sta.config(tostring(SSID),tostring(pass)) wifi.sta.connect() connecting = true end -- if found SSID in the POST from the client, try connecting if (SSID~=nil) then local connectStatus = wifi.sta.status() print(connectStatus) sendHeader() tmr.alarm(5,500,0,function() buf = buf.."<h2 style=\"color:DarkGreen\">Connecting to "..tostring(SSID).."!</h2><br><h2>Please hold tight, we'll be back to you shortly.</h2>" client:send(buf) client:close() buf = "" end) tmr.alarm(1,1000,1, function() connectStatus = wifi.sta.status() print("connecting") if (connectStatus ~= 1) then print("connectStatus = "..tostring(connectStatus)) buf = buf.."<br><center>" if (connectStatus == 5) then sendHeader() buf = buf.."<h2 style=\"color:DarkGreen\">Successfully connected to "..tostring(SSID).."!</h2><br><h2>Added to network list.</h2><br><h2>Resetting module and connecting to the mystical network...</h1>" file.open("networks","a+") file.writeline(tostring(SSID)) file.writeline(tostring(pass)) file.close() savedNetwork = true else sendHeader() buf = buf.."<h2 style=\"color:red\">Whoops! Could not connect to "..tostring(SSID)..". "..statusTable[tostring(connectStatus)].."</h2><br>" end buf = buf.."</center>" client:send(buf) client:close() collectgarbage() tmr.stop(1) end end) end -- TO-DO: need to add the functionality for this button buf = buf.."<br><br><br><form method=\"GET\"><input type=\"submit\" value=\"edit saved network info\"></form></html>" if(not connecting) then sendHeader() sendForm() client:send(buf) buf = "" client:close() collectgarbage() end if(savedNetwork) then tmr.alarm(2,15000,0,function() srv:close() node.restart() end ) end end) end) function sendHeader() -- write header to client -- had to chunk up sending of webpage, to deal with low amounts of memory on ESP-8266 devices...surely a more elegant way to do it buf = buf.."<!DOCTYPE html><html><head><style>h2{font-size:500%; font-family:helvetica} p{font-size:200%; font-family:helvetica}</style></head><div style = \"width:80%; margin: 0 auto\">" client:send(buf) buf = "" end function sendForm() -- send top of form to client buf = buf.."<h1>choose a network to join</h1>"; buf = buf.."<form align = \"left\" method=\"POST\" autocomplete=\"off\">"; buf = buf.."<p><u><b>1. choose network:</u></b><br>" client:send(buf) buf = "" -- send network names one at a time; if there are lots of networks the ESP can run out of memory for i,network in pairs(SSIDs) do buf = "<input type=\"radio\" name=\"SSID\" value=\""..network.."\">"..network.."<br>" client:send(buf) buf = "" end buf = buf.."other: <input type=\"text\" name=\"otherSSID\"><br><br>"; buf = buf.."<u><b>2. enter password:</u></b><br><input type=\"text\" name=\"password\"><br><br>"; buf = buf.."<input type=\"submit\" value=\"Submit\">"; buf = buf.."</p></form></div>"; client:send(buf) buf = "" -- add warning about password<8 characters if needed if (errMsg~=nil) then buf = buf.."<br><br>"..errMsg errMsg = nil end end
-- works using least memory if compiled, otherwise you may -- run out of memory and the module will randomly restart and -- drop connections local SSID = nil local pass = nil local otherSSID = nil local errMsg = nil local savedNetwork = false local SSIDs = {} -- lookup table for wifi.sta.status() local statusTable = {} -- statusTable[0] = "neither connected nor connecting" -- statusTable[1] = "still connecting" statusTable["2"] = "wrong password" statusTable["3"] = "didn\'t find the network you specified" statusTable["4"] = "failed to connect" -- statusTable[5] = "successfully connected" collectgarbage() wifi.setmode(wifi.STATIONAP) print('wifi status: '..wifi.sta.status()) print(node.heap()) -- opens saved list of nearby networks and puts into SSIDs table file.open('networkList','r') local counter = 0 local line = "" while (true) do line = file.readline() if line == nil then break end counter = counter + 1 SSIDs[counter] = line end print(node.heap()) -- start server running on ESP-8266, usually is IP 192.168.4.1 local cfg = {} cfg.ssid = "myfi" cfg.pwd = "mystical" wifi.ap.config(cfg) cfg = nil local srv=net.createServer(net.TCP,30) print('connect to this ip on your computer/phone: '..wifi.ap.getip()) srv:listen(80,function(conn) conn:on("receive", function(client,request) local connecting = false local _, _, SSID, pass = string.find(request, "SSID=(.+)%%0D%%0A&otherSSID=&password=(.*)"); print(node.heap()) if (pass~=nil and pass~="") then if (string.len(pass)<8) then local pass = nil errMsg = "<center><h2 style=\"color:red\">Whoops! Password must be at least 8 characters.<\h2><\center>" else errMsg = nil end end if (SSID==nil) then _, _, SSID, pass = string.find(request, "SSID=&otherSSID=(.+)%%0D%%0A&password=(.*)"); end print(request) local buf = ""; -- if password for network is nothing, any password should work if (SSID~=nil) then if (pass == "") then pass = "aaaaaaaa" end print(SSID..', '..pass) wifi.sta.config(tostring(SSID),tostring(pass)) wifi.sta.connect() connecting = true end -- if found SSID in the POST from the client, try connecting if (SSID~=nil) then local connectStatus = wifi.sta.status() print(connectStatus) sendHeader() tmr.alarm(5,500,0,function() buf = buf.."<h2 style=\"color:DarkGreen\">Connecting to "..tostring(SSID).."!</h2><br><h2>Please hold tight, we'll be back to you shortly.</h2>" client:send(buf) client:close() buf = "" end) tmr.alarm(1,1000,1, function() connectStatus = wifi.sta.status() print("connecting") if (connectStatus ~= 1) then print("connectStatus = "..tostring(connectStatus)) buf = buf.."<br><center>" if (connectStatus == 5) then sendHeader() buf = buf.."<h2 style=\"color:DarkGreen\">Successfully connected to "..tostring(SSID).."!</h2><br><h2>Added to network list.</h2><br><h2>Resetting module and connecting to the mystical network...</h1>" file.open("networks","a+") file.writeline(tostring(SSID)) file.writeline(tostring(pass)) file.close() savedNetwork = true else sendHeader() buf = buf.."<h2 style=\"color:red\">Whoops! Could not connect to "..tostring(SSID)..". "..statusTable[tostring(connectStatus)].."</h2><br>" end buf = buf.."</center>" client:send(buf) client:close() collectgarbage() tmr.stop(1) end end) end -- TO-DO: need to add the functionality for this button buf = buf.."<br><br><br><form method=\"GET\"><input type=\"submit\" value=\"edit saved network info\"></form></html>" if(not connecting) then sendHeader() sendForm(errMsg) client:send(buf) buf = "" client:close() collectgarbage() end if(savedNetwork) then tmr.alarm(2,15000,0,function() srv:close() node.restart() end ) end end) end) function sendHeader() -- write header to client -- had to chunk up sending of webpage, to deal with low amounts of memory on ESP-8266 devices...surely a more elegant way to do it buf = "" buf = buf.."<!DOCTYPE html><html><head><style>h2{font-size:500%; font-family:helvetica} p{font-size:200%; font-family:helvetica}</style></head><div style = \"width:80%; margin: 0 auto\">" client:send(buf) buf = "" end function sendForm(errMsg) buf = "" -- send top of form to client buf = buf.."<h1>choose a network to join</h1>"; buf = buf.."<form align = \"left\" method=\"POST\" autocomplete=\"off\">"; buf = buf.."<p><u><b>1. choose network:</u></b><br>" client:send(buf) buf = "" -- send network names one at a time; if there are lots of networks the ESP can run out of memory for i,network in pairs(SSIDs) do buf = "<input type=\"radio\" name=\"SSID\" value=\""..network.."\">"..network.."<br>" client:send(buf) buf = "" end buf = buf.."other: <input type=\"text\" name=\"otherSSID\"><br><br>"; buf = buf.."<u><b>2. enter password:</u></b><br><input type=\"text\" name=\"password\"><br><br>"; buf = buf.."<input type=\"submit\" value=\"Submit\">"; buf = buf.."</p></form></div>"; client:send(buf) buf = "" -- add warning about password<8 characters if needed if (errMsg~=nil) then buf = buf.."<br><br>"..errMsg errMsg = nil end end
fixed local var problems
fixed local var problems
Lua
mit
wordsforthewise/ESP-8266_network-connect
f1310cc6adeae7cec04acfee7c65f606a347d8ca
src/lua/Parallel.lua
src/lua/Parallel.lua
local zmq = require "lzmq" local zloop = require "lzmq.loop" local zthreads = require "lzmq.threads" local mp = require "cmsgpack" local zassert = zmq.assert local ENDPOINT = "inproc://main" local THREAD_STARTER = [[ local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[ local zmq = require "lzmq" local zthreads = require "lzmq.threads" local mp = require "cmsgpack" local zassert = zmq.assert function FOR(do_work) local ctx = zthreads.get_parent_ctx() local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT} if not s then return end s:sendx(0, 'READY') while not s:closed() do local tid, cmd, args = s:recvx() if not tid then if cmd and (cmd:no() == zmq.errors.ETERM) then break end zassert(nil, cmd) end assert(tid and cmd) if cmd == 'END' then break end assert(cmd == 'TASK', "invalid command " .. tostring(cmd)) assert(args, "invalid args in command") local res, err = mp.pack( do_work(mp.unpack(args)) ) s:sendx(tid, 'RESP', res) end ctx:destroy() end ]] local function pcall_ret_pack(ok, ...) if ok then return mp.pack(ok, ...) end return nil, ... end local function pcall_ret(ok, ...) if ok then return pcall_ret_pack(...) end return nil, ... end local function ppcall(...) return pcall_ret(pcall(...)) end local function thread_alive(self) local ok, err = self:join(0) if ok then return false end if err == 'timeout' then return true end return nil, err end local function parallel_for_impl(code, src, snk, N, cache_size) N = N or 4 -- @fixme do not change global state in zthreads library zthreads.set_bootstrap_prelude(THREAD_STARTER) local src_err, snk_err local cache = {} -- заранее рассчитанные данные для заданий local threads = {} -- рабочие потоки local MAX_CACHE = cache_size or N local function call_src() if src and not src_err then local args, err = ppcall(src) if args then return args end if err then src_err = err return nil, err end src = nil end end local function next_src() local args = table.remove(cache, 1) if args then return args end return call_src() end local function cache_src() if #cache >= MAX_CACHE then return end for i = #cache, MAX_CACHE do local args = call_src() if args then cache[#cache + 1] = args else break end end end local loop = zloop.new() local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT} zassert(skt, err) loop:add_socket(skt, function(skt) local identity, tid, cmd, args = skt:recvx() zassert(tid, cmd) if cmd ~= 'READY' then assert(cmd == 'RESP') if not snk_err then if snk then local ok, err = ppcall(snk, mp.unpack(args)) if not ok and err then snk_err = err end end else skt:sendx(identity, tid, 'END') return end end if #cache == 0 then cache_src() end local args, err = next_src() if args ~= nil then skt:sendx(identity, tid, 'TASK', args) return end skt:sendx(identity, tid, 'END') end) -- watchdog loop:add_interval(1000, function() for _, thread in ipairs(threads) do if thread_alive(thread) then return end end loop:interrupt() end) loop:add_interval(100, function(ev) cache_src() end) local err for i = 1, N do local thread thread, err = zthreads.run(loop:context(), code, i) if thread and thread:start(true, true) then threads[#threads + 1] = thread end end if #threads == 0 then return nil, err end loop:start() loop:destroy() for _, t in ipairs(threads) do t:join() end if src_err or snk_err then return nil, src_err or snk_err end return true end --- -- @tparam[number] be begin index -- @tparam[number] en end index -- @tparam[number?] step step -- @tparam[string] code -- @tparam[callable?] snk sink -- @tparam[number?] N thread count -- @tparam[number?] C cache size local function For(be, en, step, code, snk, N, C) if type(step) ~= 'number' then -- no step step, code, snk, N, C = 1, step, code, snk, N end if type(snk) == 'number' then -- no sink N, C = snk, N end assert(type(be) == "number") assert(type(en) == "number") assert(type(step) == "number") assert(type(code) == "string") local src = function() if be > en then return end local n = be be = be + step return n end return parallel_for_impl(code, src, snk, N, C) end --- -- @tparam[string] code -- @tparam[callable?] snk sink -- @tparam[number?] N thread count -- @tparam[number?] C cache size local function ForEach(it, code, snk, N, C) local src = it if type(it) == 'table' then local k, v src = function() k, v = next(it, k) return k, v end end if type(snk) == 'number' then -- no sink snk, N, C = nil, snk, N end assert(type(src) == "function") assert(type(code) == "string") return parallel_for_impl(code, src, snk, N, C) end local function Invoke(N, ...) local code = string.dump(function() FOR(function(_,src) if src:sub(1,1) == '@' then dofile(src:sub(2)) else assert((loadstring or load)(src))() end end) end) if type(N) == 'number' then return ForEach({...}, code, N) end return ForEach({N, ...}, code) end local Parallel = {} do Parallel.__index = Parallel function Parallel:new(N) local o = setmetatable({ thread_count = N or 4; }, self) o.cache_size = o.thread_count * 2 return o end function Parallel:For(be, en, step, code, snk) return For(be, en, step, code, snk, self.thread_count, self.cache_size) end function Parallel:ForEach(src, code, snk) return ForEach(src, code, snk, self.thread_count, self.cache_size) end function Parallel:Invoke(...) return Invoke(self.thread_count, ...) end end return { For = For; ForEach = ForEach; Invoke = Invoke; New = function(...) return Parallel:new(...) end }
local zmq = require "lzmq" local zloop = require "lzmq.loop" local zthreads = require "lzmq.threads" local mp = require "cmsgpack" local zassert = zmq.assert local ENDPOINT = "inproc://main" local THREAD_STARTER = [[ local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[ local zmq = require "lzmq" local zthreads = require "lzmq.threads" local mp = require "cmsgpack" local zassert = zmq.assert function FOR(do_work) local ctx = zthreads.get_parent_ctx() local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT, linger = 0} if not s then return end s:sendx(0, 'READY') while not s:closed() do local tid, cmd, args = s:recvx() if not tid then if cmd and (cmd:no() == zmq.errors.ETERM) then break end zassert(nil, cmd) end assert(tid and cmd) if cmd == 'END' then break end assert(cmd == 'TASK', "invalid command " .. tostring(cmd)) assert(args, "invalid args in command") local res, err = mp.pack( do_work(mp.unpack(args)) ) s:sendx(tid, 'RESP', res) end ctx:destroy() end ]] local function pcall_ret_pack(ok, ...) if ok then return mp.pack(ok, ...) end return nil, ... end local function pcall_ret(ok, ...) if ok then return pcall_ret_pack(...) end return nil, ... end local function ppcall(...) return pcall_ret(pcall(...)) end local function thread_alive(self) local ok, err = self:join(0) if ok then return false end if err == 'timeout' then return true end return nil, err end local function parallel_for_impl(code, src, snk, N, cache_size) N = N or 4 -- @fixme do not change global state in zthreads library zthreads.set_bootstrap_prelude(THREAD_STARTER) local src_err, snk_err local cache = {} -- заранее рассчитанные данные для заданий local threads = {} -- рабочие потоки local reqs = 0 local MAX_CACHE = cache_size or N local function call_src() if src and not src_err then local args, err = ppcall(src) if args then return args end if err then src_err = err return nil, err end src = nil end end local function next_src() local args = table.remove(cache, 1) if args then return args end return call_src() end local function cache_src() if #cache >= MAX_CACHE then return end for i = #cache, MAX_CACHE do local args = call_src() if args then cache[#cache + 1] = args else break end end end local loop = zloop.new() local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT, linger = 0} zassert(skt, err) loop:add_socket(skt, function(skt) local identity, tid, cmd, args = skt:recvx() zassert(tid, cmd) if cmd ~= 'READY' then assert(cmd == 'RESP') assert(reqs > 0) reqs = reqs - 1 if not snk_err then if snk then local ok, err = ppcall(snk, mp.unpack(args)) if not ok and err then snk_err = err end end else skt:sendx(identity, tid, 'END') return end end if #cache == 0 then cache_src() end local args, err = next_src() if args ~= nil then skt:sendx(identity, tid, 'TASK', args) reqs = reqs + 1 return end skt:sendx(identity, tid, 'END') if reqs == 0 then loop:interrupt() end end) -- watchdog loop:add_interval(1000, function() for _, thread in ipairs(threads) do if thread_alive(thread) then return end end loop:interrupt() end) loop:add_interval(100, function(ev) cache_src() end) local err for i = 1, N do local thread thread, err = zthreads.run(loop:context(), code, i) if thread and thread:start(true, true) then threads[#threads + 1] = thread end end if #threads == 0 then return nil, err end loop:start() loop:destroy() for _, t in ipairs(threads) do t:join() end if src_err or snk_err then return nil, src_err or snk_err end return true end --- -- @tparam[number] be begin index -- @tparam[number] en end index -- @tparam[number?] step step -- @tparam[string] code -- @tparam[callable?] snk sink -- @tparam[number?] N thread count -- @tparam[number?] C cache size local function For(be, en, step, code, snk, N, C) if type(step) ~= 'number' then -- no step step, code, snk, N, C = 1, step, code, snk, N end if type(snk) == 'number' then -- no sink N, C = snk, N end assert(type(be) == "number") assert(type(en) == "number") assert(type(step) == "number") assert(type(code) == "string") local src = function() if be > en then return end local n = be be = be + step return n end return parallel_for_impl(code, src, snk, N, C) end --- -- @tparam[string] code -- @tparam[callable?] snk sink -- @tparam[number?] N thread count -- @tparam[number?] C cache size local function ForEach(it, code, snk, N, C) local src = it if type(it) == 'table' then local k, v src = function() k, v = next(it, k) return k, v end end if type(snk) == 'number' then -- no sink snk, N, C = nil, snk, N end assert(type(src) == "function") assert(type(code) == "string") return parallel_for_impl(code, src, snk, N, C) end local function Invoke(N, ...) local code = string.dump(function() FOR(function(_,src) if src:sub(1,1) == '@' then dofile(src:sub(2)) else assert((loadstring or load)(src))() end end) end) if type(N) == 'number' then return ForEach({...}, code, N) end return ForEach({N, ...}, code) end local Parallel = {} do Parallel.__index = Parallel function Parallel:new(N) local o = setmetatable({ thread_count = N or 4; }, self) o.cache_size = o.thread_count * 2 return o end function Parallel:For(be, en, step, code, snk) return For(be, en, step, code, snk, self.thread_count, self.cache_size) end function Parallel:ForEach(src, code, snk) return ForEach(src, code, snk, self.thread_count, self.cache_size) end function Parallel:Invoke(...) return Invoke(self.thread_count, ...) end end return { For = For; ForEach = ForEach; Invoke = Invoke; New = function(...) return Parallel:new(...) end }
Fix. Manually interrupt loop when job is done.
Fix. Manually interrupt loop when job is done.
Lua
mit
kidaa/lua-Parallel,moteus/lua-Parallel
f709e2888e1727184621d314a80442544f14242f
kong/plugins/zipkin/schema.lua
kong/plugins/zipkin/schema.lua
local typedefs = require "kong.db.schema.typedefs" return { name = "zipkin", fields = { { run_on = typedefs.run_on { default = "all" } }, { config = { type = "record", fields = { { http_endpoint = typedefs.url{ required = true } }, { sample_ratio = { type = "number", default = 0.001, between = { 0, 1 } } }, { default_service_name = { type = "string", default = nil } }, { include_credential = { type = "boolean", required = true, default = true } }, }, }, }, }, }
local typedefs = require "kong.db.schema.typedefs" return { name = "zipkin", fields = { { config = { type = "record", fields = { { http_endpoint = typedefs.url{ required = true } }, { sample_ratio = { type = "number", default = 0.001, between = { 0, 1 } } }, { default_service_name = { type = "string", default = nil } }, { include_credential = { type = "boolean", required = true, default = true } }, }, }, }, }, }
fix(zipkin) remove `run_on` field from plugin schema (#54)
fix(zipkin) remove `run_on` field from plugin schema (#54) It is no longer needed as service mesh support is removed from Kong
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
80cd614a4e12ca8269971939a4ce80fe64ad78cf
lib/resty/mongol/object_id.lua
lib/resty/mongol/object_id.lua
local mod_name = (...):match ( "^(.*)%..-$" ) local setmetatable = setmetatable local strbyte = string.byte local strformat = string.format local t_insert = table.insert local t_concat = table.concat local hasposix , posix = pcall ( require , "posix" ) local ll = require ( mod_name .. ".ll" ) local num_to_le_uint = ll.num_to_le_uint local num_to_be_uint = ll.num_to_be_uint local function _tostring(ob) local t = {} for i = 1 , 12 do t_insert(t, strformat("%02x", strbyte(ob.id, i, i))) end return t_concat(t) end local function _get_ts(ob) return ll.be_uint_to_num(ob.id, 1, 4) end local function _get_hostname(ob) local t = {} for i = 5, 7 do t_insert(t, strformat("%02x", strbyte(ob.id, i, i))) end return t_concat(t) end local function _get_pid(ob) return ll.be_uint_to_num(ob.id, 8, 9) end local function _get_inc(ob) return ll.be_uint_to_num(ob.id, 10, 12) end local object_id_mt = { __tostring = _tostring; __eq = function ( a , b ) return a.id == b.id end ; } local function get_os_machineid() local machineid if hasposix then machineid = posix.uname("%n") else machineid = assert(io.popen("uname -n")):read("*l") end machineid = ngx.md5_bin(machineid):sub(1, 3) return machineid end local pid = 0 local function get_os_pid() if pid ~= 0 then return pid end if hasposix then pid = posix.getpid().pid else --pid = assert ( tonumber ( assert ( io.popen ( "ps -o ppid= -p $$") ):read ( "*a" ) ) ) local p = io.popen("ps -o ppid= -p $$"):read("*a") if not p then ngx.log(ngx.ERR, "get pid failed") p = io.popen("ps -o ppid= -p $$"):read("*a") end pid = assert(tonumber(p)) end pid = num_to_le_uint(pid, 2) return pid end local inc = 0 local function generate_id ( ) inc = inc + 1 -- "A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON" return num_to_be_uint ( os.time ( ) , 4 ) .. get_os_machineid() .. get_os_pid() .. num_to_be_uint ( inc , 3 ) end local function new_object_id(str) if str then assert(#str == 12) else str = generate_id() end return setmetatable({id = str, tostring = _tostring, get_ts = _get_ts, get_pid = _get_pid, get_hostname = _get_hostname, get_inc = _get_inc, } , object_id_mt) end return { new = new_object_id ; metatable = object_id_mt ; }
local mod_name = (...):match ( "^(.*)%..-$" ) local setmetatable = setmetatable local strbyte = string.byte local strformat = string.format local t_insert = table.insert local t_concat = table.concat local hasposix , posix = pcall ( require , "posix" ) local ll = require ( mod_name .. ".ll" ) local num_to_le_uint = ll.num_to_le_uint local num_to_be_uint = ll.num_to_be_uint local function _tostring(ob) local t = {} for i = 1 , 12 do t_insert(t, strformat("%02x", strbyte(ob.id, i, i))) end return t_concat(t) end local function _get_ts(ob) return ll.be_uint_to_num(ob.id, 1, 4) end local function _get_hostname(ob) local t = {} for i = 5, 7 do t_insert(t, strformat("%02x", strbyte(ob.id, i, i))) end return t_concat(t) end local function _get_pid(ob) return ll.be_uint_to_num(ob.id, 8, 9) end local function _get_inc(ob) return ll.be_uint_to_num(ob.id, 10, 12) end local object_id_mt = { __tostring = _tostring; __eq = function ( a , b ) return a.id == b.id end ; } local function get_os_machineid() local machineid if hasposix then machineid = posix.uname("%n") else machineid = assert(io.popen("uname -n")):read("*l") end machineid = ngx.md5_bin(machineid):sub(1, 3) return machineid end local pid = 0 local function get_os_pid() if pid ~= 0 then return pid end pid = ngx.var.pid pid = num_to_le_uint(pid, 2) return pid end local inc = 0 local function generate_id ( ) inc = inc + 1 -- "A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON" return num_to_be_uint ( os.time ( ) , 4 ) .. get_os_machineid() .. get_os_pid() .. num_to_be_uint ( inc , 3 ) end local function new_object_id(str) if str then assert(#str == 12) else str = generate_id() end return setmetatable({id = str, tostring = _tostring, get_ts = _get_ts, get_pid = _get_pid, get_hostname = _get_hostname, get_inc = _get_inc, } , object_id_mt) end return { new = new_object_id ; metatable = object_id_mt ; }
bugfix: pid generated failed, so replaced with nginx var
bugfix: pid generated failed, so replaced with nginx var
Lua
mit
Olivine-Labs/resty-mongol
7be008936eab8e17bdc4de1811411071821eb294
mods/flowers/init.lua
mods/flowers/init.lua
-- Minetest 0.4 mod: default -- See README.txt for licensing and other information. -- Namespace for functions flowers = {} -- Map Generation dofile(minetest.get_modpath("flowers") .. "/mapgen.lua") -- -- Flowers -- -- Aliases for original flowers mod minetest.register_alias("flowers:flower_rose", "flowers:rose") minetest.register_alias("flowers:flower_tulip", "flowers:tulip") minetest.register_alias("flowers:flower_dandelion_yellow", "flowers:dandelion_yellow") minetest.register_alias("flowers:flower_geranium", "flowers:geranium") minetest.register_alias("flowers:flower_viola", "flowers:viola") minetest.register_alias("flowers:flower_dandelion_white", "flowers:dandelion_white") -- Flower registration local function add_simple_flower(name, desc, box, f_groups) -- Common flowers' groups f_groups.snappy = 3 f_groups.flower = 1 f_groups.flora = 1 f_groups.attached_node = 1 minetest.register_node("flowers:" .. name, { description = desc, drawtype = "plantlike", waving = 1, tiles = {"flowers_" .. name .. ".png"}, inventory_image = "flowers_" .. name .. ".png", wield_image = "flowers_" .. name .. ".png", sunlight_propagates = true, paramtype = "light", walkable = false, buildable_to = true, stack_max = 99, groups = f_groups, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = box } }) end flowers.datas = { {"rose", "Rose", {-0.15, -0.5, -0.15, 0.15, 0.3, 0.15}, {color_red = 1}}, {"tulip", "Orange Tulip", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_orange = 1}}, {"dandelion_yellow", "Yellow Dandelion", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_yellow = 1}}, {"geranium", "Blue Geranium", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_blue = 1}}, {"viola", "Viola", {-0.5, -0.5, -0.5, 0.5, -0.2, 0.5}, {color_violet = 1}}, {"dandelion_white", "White dandelion", {-0.5, -0.5, -0.5, 0.5, -0.2, 0.5}, {color_white = 1}} } for _,item in pairs(flowers.datas) do add_simple_flower(unpack(item)) end -- Flower spread minetest.register_abm({ nodenames = {"group:flora"}, neighbors = {"default:dirt_with_grass", "default:desert_sand"}, interval = 13, chance = 96, action = function(pos, node) pos.y = pos.y - 1 local under = minetest.get_node(pos) pos.y = pos.y + 1 if under.name == "default:desert_sand" then minetest.set_node(pos, {name = "default:dry_shrub"}) elseif under.name ~= "default:dirt_with_grass" then return end local light = minetest.get_node_light(pos) if not light or light < 13 then return end local pos0 = {x = pos.x - 4, y = pos.y - 4, z = pos.z - 4} local pos1 = {x = pos.x + 4, y = pos.y + 4, z = pos.z + 4} if #minetest.find_nodes_in_area(pos0, pos1, "group:flora_block") > 0 then return end local flowers = minetest.find_nodes_in_area(pos0, pos1, "group:flora") if #flowers > 3 then return end local seedling = minetest.find_nodes_in_area(pos0, pos1, "default:dirt_with_grass") if #seedling > 0 then seedling = seedling[math.random(#seedling)] seedling.y = seedling.y + 1 light = minetest.get_node_light(seedling) if not light or light < 13 then return end if minetest.get_node(seedling).name == "air" then minetest.set_node(seedling, {name = node.name}) end end end, }) -- -- Mushrooms -- minetest.register_node("flowers:mushroom_red", { description = "Red Mushroom", tiles = {"flowers_mushroom_red.png"}, inventory_image = "flowers_mushroom_red.png", wield_image = "flowers_mushroom_red.png", drawtype = "plantlike", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, attached_node = 1}, sounds = default.node_sound_leaves_defaults(), on_use = minetest.item_eat(-5), selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3} } }) minetest.register_node("flowers:mushroom_brown", { description = "Brown Mushroom", tiles = {"flowers_mushroom_brown.png"}, inventory_image = "flowers_mushroom_brown.png", wield_image = "flowers_mushroom_brown.png", drawtype = "plantlike", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, attached_node = 1}, sounds = default.node_sound_leaves_defaults(), on_use = minetest.item_eat(1), selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3} } }) -- mushroom spread and death minetest.register_abm({ nodenames = {"flowers:mushroom_brown", "flowers:mushroom_red"}, interval = 11, chance = 50, action = function(pos, node) if minetest.get_node_light(pos, nil) == 15 then minetest.remove_node(pos) end local random = { x = pos.x + math.random(-2,2), y = pos.y + math.random(-1,1), z = pos.z + math.random(-2,2) } local random_node = minetest.get_node_or_nil(random) if not random_node then return end if random_node.name ~= "air" then return end local node_under = minetest.get_node_or_nil({x = random.x, y = random.y - 1, z = random.z}) if not node_under then return end if minetest.get_item_group(node_under.name, "soil") ~= 0 and minetest.get_node_light(pos, nil) <= 9 and minetest.get_node_light(random, nil) <= 9 then minetest.set_node(random, {name = node.name}) end end }) -- these old mushroom related nodes can be simplified now minetest.register_alias("flowers:mushroom_spores_brown", "flowers:mushroom_brown") minetest.register_alias("flowers:mushroom_spores_red", "flowers:mushroom_red") minetest.register_alias("flowers:mushroom_fertile_brown", "flowers:mushroom_brown") minetest.register_alias("flowers:mushroom_fertile_red", "flowers:mushroom_red") -- -- Waterlily -- minetest.register_node("flowers:waterlily", { description = "Waterlily", drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", tiles = {"flowers_waterlily.png"}, inventory_image = "flowers_waterlily.png", wield_image = "flowers_waterlily.png", liquids_pointable = true, walkable = false, buildable_to = true, sunlight_propagates = true, groups = {snappy = 3, flower = 1}, sounds = default.node_sound_leaves_defaults(), node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.46875, 0.5} }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.5} }, on_place = function(_, _, pointed_thing) local pos = pointed_thing.above local node = minetest.get_node(pointed_thing.under).name local def = minetest.registered_nodes[node] if def and def.liquidtype == "source" and minetest.get_item_group(node, "water") > 0 then minetest.set_node(pos, {name = "flowers:waterlily", param2 = math.random(0, 3)}) end end })
-- Minetest 0.4 mod: default -- See README.txt for licensing and other information. -- Namespace for functions flowers = {} -- Map Generation dofile(minetest.get_modpath("flowers") .. "/mapgen.lua") -- -- Flowers -- -- Aliases for original flowers mod minetest.register_alias("flowers:flower_rose", "flowers:rose") minetest.register_alias("flowers:flower_tulip", "flowers:tulip") minetest.register_alias("flowers:flower_dandelion_yellow", "flowers:dandelion_yellow") minetest.register_alias("flowers:flower_geranium", "flowers:geranium") minetest.register_alias("flowers:flower_viola", "flowers:viola") minetest.register_alias("flowers:flower_dandelion_white", "flowers:dandelion_white") -- Flower registration local function add_simple_flower(name, desc, box, f_groups) -- Common flowers' groups f_groups.snappy = 3 f_groups.flower = 1 f_groups.flora = 1 f_groups.attached_node = 1 minetest.register_node("flowers:" .. name, { description = desc, drawtype = "plantlike", waving = 1, tiles = {"flowers_" .. name .. ".png"}, inventory_image = "flowers_" .. name .. ".png", wield_image = "flowers_" .. name .. ".png", sunlight_propagates = true, paramtype = "light", walkable = false, buildable_to = true, stack_max = 99, groups = f_groups, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = box } }) end flowers.datas = { {"rose", "Rose", {-0.15, -0.5, -0.15, 0.15, 0.3, 0.15}, {color_red = 1}}, {"tulip", "Orange Tulip", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_orange = 1}}, {"dandelion_yellow", "Yellow Dandelion", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_yellow = 1}}, {"geranium", "Blue Geranium", {-0.15, -0.5, -0.15, 0.15, 0.2, 0.15}, {color_blue = 1}}, {"viola", "Viola", {-0.5, -0.5, -0.5, 0.5, -0.2, 0.5}, {color_violet = 1}}, {"dandelion_white", "White dandelion", {-0.5, -0.5, -0.5, 0.5, -0.2, 0.5}, {color_white = 1}} } for _,item in pairs(flowers.datas) do add_simple_flower(unpack(item)) end -- Flower spread minetest.register_abm({ nodenames = {"group:flora"}, neighbors = {"default:dirt_with_grass", "default:desert_sand"}, interval = 13, chance = 96, action = function(pos, node) pos.y = pos.y - 1 local under = minetest.get_node(pos) pos.y = pos.y + 1 if under.name == "default:desert_sand" then minetest.set_node(pos, {name = "default:dry_shrub"}) elseif under.name ~= "default:dirt_with_grass" then return end local light = minetest.get_node_light(pos) if not light or light < 13 then return end local pos0 = {x = pos.x - 4, y = pos.y - 4, z = pos.z - 4} local pos1 = {x = pos.x + 4, y = pos.y + 4, z = pos.z + 4} if #minetest.find_nodes_in_area(pos0, pos1, "group:flora_block") > 0 then return end local flowers = minetest.find_nodes_in_area(pos0, pos1, "group:flora") if #flowers > 3 then return end local seedling = minetest.find_nodes_in_area(pos0, pos1, "default:dirt_with_grass") if #seedling > 0 then seedling = seedling[math.random(#seedling)] seedling.y = seedling.y + 1 light = minetest.get_node_light(seedling) if not light or light < 13 then return end if minetest.get_node(seedling).name == "air" then minetest.set_node(seedling, {name = node.name}) end end end, }) -- -- Mushrooms -- minetest.register_node("flowers:mushroom_red", { description = "Red Mushroom", tiles = {"flowers_mushroom_red.png"}, inventory_image = "flowers_mushroom_red.png", wield_image = "flowers_mushroom_red.png", drawtype = "plantlike", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, attached_node = 1}, sounds = default.node_sound_leaves_defaults(), on_use = minetest.item_eat(-5), selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3} } }) minetest.register_node("flowers:mushroom_brown", { description = "Brown Mushroom", tiles = {"flowers_mushroom_brown.png"}, inventory_image = "flowers_mushroom_brown.png", wield_image = "flowers_mushroom_brown.png", drawtype = "plantlike", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, attached_node = 1}, sounds = default.node_sound_leaves_defaults(), on_use = minetest.item_eat(1), selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3} } }) -- mushroom spread and death minetest.register_abm({ nodenames = {"flowers:mushroom_brown", "flowers:mushroom_red"}, interval = 11, chance = 50, action = function(pos, node) if minetest.get_node_light(pos, nil) == 15 then minetest.remove_node(pos) end local random = { x = pos.x + math.random(-2,2), y = pos.y + math.random(-1,1), z = pos.z + math.random(-2,2) } local random_node = minetest.get_node_or_nil(random) if not random_node then return end if random_node.name ~= "air" then return end local node_under = minetest.get_node_or_nil({x = random.x, y = random.y - 1, z = random.z}) if not node_under then return end if minetest.get_item_group(node_under.name, "soil") ~= 0 and minetest.get_node_light(pos, nil) <= 9 and minetest.get_node_light(random, nil) <= 9 then minetest.set_node(random, {name = node.name}) end end }) -- these old mushroom related nodes can be simplified now minetest.register_alias("flowers:mushroom_spores_brown", "flowers:mushroom_brown") minetest.register_alias("flowers:mushroom_spores_red", "flowers:mushroom_red") minetest.register_alias("flowers:mushroom_fertile_brown", "flowers:mushroom_brown") minetest.register_alias("flowers:mushroom_fertile_red", "flowers:mushroom_red") -- -- Waterlily -- minetest.register_node("flowers:waterlily", { description = "Waterlily", drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", tiles = {"flowers_waterlily.png"}, inventory_image = "flowers_waterlily.png", wield_image = "flowers_waterlily.png", liquids_pointable = true, walkable = false, buildable_to = true, sunlight_propagates = true, groups = {snappy = 3, flower = 1}, sounds = default.node_sound_leaves_defaults(), node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.46875, 0.5} }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.5} }, on_place = function(itemstack, _, pointed_thing) local pos = pointed_thing.above local node = minetest.get_node(pointed_thing.under).name local def = minetest.registered_nodes[node] if def and def.liquidtype == "source" and minetest.get_item_group(node, "water") > 0 then minetest.set_node(pos, {name = "flowers:waterlily", param2 = math.random(0, 3)}) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() return itemstack end end end })
Flowers: Fix itemstack when waterlily is placed
Flowers: Fix itemstack when waterlily is placed
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
ce92066de90d7803a950400ff7cde1e1545fdf9b
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
--[[ Luci statistics - statistics controller module (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$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, template("admin_statistics/index"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
--[[ Luci statistics - statistics controller module (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$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
applications/luci-statistics: fix controller (#7344)
applications/luci-statistics: fix controller (#7344)
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
16bf7363e707013d8d636c2d891cd5138e6aca53
game/scripts/vscripts/heroes/hero_sara/evolution.lua
game/scripts/vscripts/heroes/hero_sara/evolution.lua
LinkLuaModifier("modifier_sara_evolution", "heroes/hero_sara/evolution.lua", LUA_MODIFIER_MOTION_NONE) sara_evolution = class({ GetIntrinsicModifierName = function() return "modifier_sara_evolution" end, }) modifier_sara_evolution = class({ IsPurgable = function() return false end, DestroyOnExpire = function() return false end, }) function modifier_sara_evolution:DeclareFunctions() return { MODIFIER_EVENT_ON_ATTACK_LANDED, MODIFIER_EVENT_ON_DEATH, MODIFIER_PROPERTY_MANA_BONUS, MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS, MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, MODIFIER_PROPERTY_TOOLTIP } end function modifier_sara_evolution:GetModifierManaBonus() return self.ManaModifier or self:GetSharedKey("ManaModifier") or 0 end function modifier_sara_evolution:OnTooltip() local ability = self:GetAbility() return ability:GetSpecialValueFor("max_per_minute") + ability:GetSpecialValueFor("max_per_minute_pct") * self:GetParent():GetMaxMana() * 0.01 end function modifier_sara_evolution:GetModifierExtraHealthBonus() local ability = self:GetAbility() return ability:GetSpecialValueFor("bonus_health") / (1 - ability:GetSpecialValueFor("health_reduction_pct") * 0.01) end function modifier_sara_evolution:GetModifierPhysicalArmorBonus() return self.ArmorReduction end if IsServer() then modifier_sara_evolution.think_interval = 1/30 function modifier_sara_evolution:OnCreated() local parent = self:GetParent() local ability = self:GetAbility() if ability:GetLevel() == 0 then ability:SetLevel(1) end self:StartIntervalThink(self.think_interval) self:SetDuration(60, true) self.MaxEnergy = 100 self.Energy = self.MaxEnergy local illusionParent = parent:GetIllusionParent() if parent.SavedEnergyStates then self.Energy = parent.SavedEnergyStates.Energy or self.Energy self.MaxEnergy = parent.SavedEnergyStates.MaxEnergy or self.MaxEnergy parent.SavedEnergyStates = nil elseif IsValidEntity(illusionParent) and illusionParent.GetEnergy and illusionParent.GetMaxEnergy then self.Energy = illusionParent:GetEnergy() self.MaxEnergy = illusionParent:GetMaxEnergy() end parent:SetNetworkableEntityInfo("Energy", self.Energy) parent:SetNetworkableEntityInfo("MaxEnergy", self.MaxEnergy) parent.ModifyEnergy = function(_, value, bShowMessage) if value > 0 and parent:HasModifier("modifier_sara_fragment_of_logic_debuff") then return self.Energy end if bShowMessage then --print("Call: modify mana by " .. value .. ", result: old mana: " .. self.Energy .. " new mana: " .. math.min(math.max(self.Energy + value, 0), self.MaxEnergy)) SendOverheadEventMessage(nil, OVERHEAD_ALERT_MANA_ADD, parent, value, nil) end self.Energy = math.min(math.max(self.Energy + value, 0), self.MaxEnergy) parent:SetNetworkableEntityInfo("Energy", self.Energy) return self.Energy end parent.GetEnergy = function() return self.Energy end parent.GetMaxEnergy = function() return self.MaxEnergy end parent.ModifyMaxEnergy = function(_, value) self.MaxEnergy = self.MaxEnergy + value parent:SetNetworkableEntityInfo("MaxEnergy", self.MaxEnergy) return self.MaxEnergy end end function modifier_sara_evolution:OnDestroy() local parent = self:GetParent() if IsValidEntity(parent) then --For illusions and RecreateAbility function parent.SavedEnergyStates = { Energy = self.Energy, MaxEnergy = self.MaxEnergy } end end function modifier_sara_evolution:OnAttackLanded(keys) if keys.attacker == self:GetParent() then --keys.attacker:ModifyEnergy(keys.attacker:GetMaxEnergy() * self:GetAbility():GetSpecialValueFor("per_hit_pct") * 0.01) end end function modifier_sara_evolution:OnDeath(keys) if keys.attacker == self:GetParent() and keys.unit:IsRealCreep() then local ability = self:GetAbility() local energy = ability:GetSpecialValueFor("max_per_creep") + ability:GetSpecialValueFor("max_per_creep_pct") * keys.attacker:GetMaxEnergy() * 0.01 if keys.unit.SpaceDissectionMultiplier then energy = energy * keys.unit.SpaceDissectionMultiplier end keys.attacker:ModifyMaxEnergy(energy) end end function modifier_sara_evolution:OnIntervalThink() local parent = self:GetParent() local ability = self:GetAbility() if self:GetRemainingTime() <= 0 then self:GetParent():ModifyMaxEnergy(ability:GetSpecialValueFor("max_per_minute") + ability:GetSpecialValueFor("max_per_minute_pct") * parent:GetMaxEnergy() * 0.01) self:SetDuration(60, true) end local energyPS = (ability:GetSpecialValueFor("per_sec_pct") * parent:GetMaxEnergy() * 0.01 + ability:GetSpecialValueFor("per_sec")) if parent:HasScepter() then energyPS = energyPS * ability:GetSpecialValueFor("per_sec_multiplier_scepter") end parent:ModifyEnergy(energyPS * self.think_interval) parent:SetMana(self.Energy) local maxMana = parent:GetMaxMana() - (self.ManaModifier or 0) local previous = self.ManaModifier self.ManaModifier = self.MaxEnergy - maxMana self:SetSharedKey("ManaModifier", self.ManaModifier) if parent:IsAlive() then parent:CalculateHealthReduction() end self.ArmorReduction = self:GetAbility():GetSpecialValueFor("armor_reduction_pct") * self:GetParent():GetPhysicalArmorValue() * 0.01 end else function modifier_sara_evolution:OnCreated() self:StartIntervalThink(0.1) end function modifier_sara_evolution:OnIntervalThink() self.ArmorReduction = self:GetAbility():GetSpecialValueFor("armor_reduction_pct") * self:GetParent():GetPhysicalArmorValue() * 0.01 end end
LinkLuaModifier("modifier_sara_evolution", "heroes/hero_sara/evolution.lua", LUA_MODIFIER_MOTION_NONE) sara_evolution = class({ GetIntrinsicModifierName = function() return "modifier_sara_evolution" end, }) modifier_sara_evolution = class({ IsPurgable = function() return false end, DestroyOnExpire = function() return false end, }) function modifier_sara_evolution:DeclareFunctions() return { MODIFIER_EVENT_ON_ATTACK_LANDED, MODIFIER_EVENT_ON_DEATH, MODIFIER_PROPERTY_MANA_BONUS, MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS, MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, MODIFIER_PROPERTY_TOOLTIP } end function modifier_sara_evolution:GetModifierManaBonus() return self.ManaModifier or self:GetSharedKey("ManaModifier") or 0 end function modifier_sara_evolution:OnTooltip() local ability = self:GetAbility() return ability:GetSpecialValueFor("max_per_minute") + ability:GetSpecialValueFor("max_per_minute_pct") * self:GetParent():GetMaxMana() * 0.01 end function modifier_sara_evolution:GetModifierExtraHealthBonus() local ability = self:GetAbility() return ability:GetSpecialValueFor("bonus_health") / (1 - ability:GetSpecialValueFor("health_reduction_pct") * 0.01) end function modifier_sara_evolution:GetModifierPhysicalArmorBonus() return self.armorReduction end if IsServer() then modifier_sara_evolution.think_interval = 1/30 function modifier_sara_evolution:OnCreated() local parent = self:GetParent() local ability = self:GetAbility() if ability:GetLevel() == 0 then ability:SetLevel(1) end self:StartIntervalThink(self.think_interval) self:SetDuration(60, true) self.MaxEnergy = 100 self.Energy = self.MaxEnergy local illusionParent = parent:GetIllusionParent() if parent.SavedEnergyStates then self.Energy = parent.SavedEnergyStates.Energy or self.Energy self.MaxEnergy = parent.SavedEnergyStates.MaxEnergy or self.MaxEnergy parent.SavedEnergyStates = nil elseif IsValidEntity(illusionParent) and illusionParent.GetEnergy and illusionParent.GetMaxEnergy then self.Energy = illusionParent:GetEnergy() self.MaxEnergy = illusionParent:GetMaxEnergy() end parent:SetNetworkableEntityInfo("Energy", self.Energy) parent:SetNetworkableEntityInfo("MaxEnergy", self.MaxEnergy) parent.ModifyEnergy = function(_, value, bShowMessage) if value > 0 and parent:HasModifier("modifier_sara_fragment_of_logic_debuff") then return self.Energy end if bShowMessage then --print("Call: modify mana by " .. value .. ", result: old mana: " .. self.Energy .. " new mana: " .. math.min(math.max(self.Energy + value, 0), self.MaxEnergy)) SendOverheadEventMessage(nil, OVERHEAD_ALERT_MANA_ADD, parent, value, nil) end self.Energy = math.min(math.max(self.Energy + value, 0), self.MaxEnergy) parent:SetNetworkableEntityInfo("Energy", self.Energy) return self.Energy end parent.GetEnergy = function() return self.Energy end parent.GetMaxEnergy = function() return self.MaxEnergy end parent.ModifyMaxEnergy = function(_, value) self.MaxEnergy = self.MaxEnergy + value parent:SetNetworkableEntityInfo("MaxEnergy", self.MaxEnergy) return self.MaxEnergy end end function modifier_sara_evolution:OnDestroy() local parent = self:GetParent() if IsValidEntity(parent) then --For illusions and RecreateAbility function parent.SavedEnergyStates = { Energy = self.Energy, MaxEnergy = self.MaxEnergy } end end function modifier_sara_evolution:OnAttackLanded(keys) if keys.attacker == self:GetParent() then --keys.attacker:ModifyEnergy(keys.attacker:GetMaxEnergy() * self:GetAbility():GetSpecialValueFor("per_hit_pct") * 0.01) end end function modifier_sara_evolution:OnDeath(keys) if keys.attacker == self:GetParent() and keys.unit:IsRealCreep() then local ability = self:GetAbility() local energy = ability:GetSpecialValueFor("max_per_creep") + ability:GetSpecialValueFor("max_per_creep_pct") * keys.attacker:GetMaxEnergy() * 0.01 if keys.unit.SpaceDissectionMultiplier then energy = energy * keys.unit.SpaceDissectionMultiplier end keys.attacker:ModifyMaxEnergy(energy) end end function modifier_sara_evolution:OnIntervalThink() local parent = self:GetParent() local ability = self:GetAbility() if self:GetRemainingTime() <= 0 then self:GetParent():ModifyMaxEnergy(ability:GetSpecialValueFor("max_per_minute") + ability:GetSpecialValueFor("max_per_minute_pct") * parent:GetMaxEnergy() * 0.01) self:SetDuration(60, true) end local energyPS = (ability:GetSpecialValueFor("per_sec_pct") * parent:GetMaxEnergy() * 0.01 + ability:GetSpecialValueFor("per_sec")) if parent:HasScepter() then energyPS = energyPS * ability:GetSpecialValueFor("per_sec_multiplier_scepter") end parent:ModifyEnergy(energyPS * self.think_interval) parent:SetMana(self.Energy) local maxMana = parent:GetMaxMana() - (self.ManaModifier or 0) local previous = self.ManaModifier self.ManaModifier = self.MaxEnergy - maxMana self:SetSharedKey("ManaModifier", self.ManaModifier) if parent:IsAlive() then parent:CalculateHealthReduction() end self.armorReduction = ability:GetSpecialValueFor("armor_reduction_pct") * (parent:GetPhysicalArmorValue() - (self.armorReduction or 0)) * 0.01 end else function modifier_sara_evolution:OnCreated() self:StartIntervalThink(0.1) end function modifier_sara_evolution:OnIntervalThink() local parent = self:GetParent() local ability = self:GetAbility() self.armorReduction = ability:GetSpecialValueFor("armor_reduction_pct") * (parent:GetPhysicalArmorValue() - (self.armorReduction or 0)) * 0.01 end end
fix(sara): armor reduction works incorrectly
fix(sara): armor reduction works incorrectly Fixes #401.
Lua
mit
ark120202/aabs
f9ba3e694c284cc831722a2a4a7cc53074e39917
Quadtastic/AppLogic.lua
Quadtastic/AppLogic.lua
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function" or self._state.coroutine) local co, ret if self._state.coroutine then -- The coroutine might be running if this was a nested call. -- In this case however we do expect that a function was passed. if coroutine.running() then assert(type(f) == "function") co = coroutine.running() ret = {true, f(self, self._state.data, ...)} else co = self._state.coroutine ret = {coroutine.resume(co, ...)} end else co = coroutine.create(f) ret = {coroutine.resume(co, self, self._state.data, ...)} end -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else if coroutine.status(co) == "dead" then -- Remove dead coroutine self._state.coroutine = nil else assert(co == coroutine.running(), "coroutine wasn't running") end -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 1 then if #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else self._should_quit = true quit(ret[2]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} application._has_active_state_changed = false application._should_quit = false setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return setmetatable({}, {__index = function(_, event) local f = self._state.transitions[event] return function(...) run(self, f, ...) end end}) -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return setmetatable({}, {__index = function(_, event) return function(...) table.insert(self._event_queue[key], {event, {...}}) end end}) else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state if there isn't one already if not self._event_queue[self._state.name] then self._event_queue[self._state.name] = {} end -- Switch states self._state = new_state self._has_active_state_changed = true end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) self._has_active_state_changed = true local statename = self._state.name -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then run(self, nil, ...) end -- Catch up on events that happened for that state while we were in a -- different state, but make sure that states haven't changed since. if self._state.name == statename then for _,event_bundle in ipairs(self._event_queue[statename]) do local f = self._state.transitions[event_bundle[1]] run(self, f, unpack(event_bundle[2])) end self._event_queue[statename] = nil end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = {state, false} end -- Add the current state table.insert(states, {self._state, true}) return states end function AppLogic.get_current_state(self) return self._state.name end -- Will return true once after each time the active state has changed. function AppLogic.has_active_state_changed(self) local has_changed = self._has_active_state_changed self._has_active_state_changed = false return has_changed end return AppLogic
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function" or self._state.coroutine) local co, ret if self._state.coroutine then -- The coroutine might be running if this was a nested call. -- In this case however we do expect that a function was passed. if coroutine.running() then assert(type(f) == "function") co = coroutine.running() ret = {true, f(self, self._state.data, ...)} else co = self._state.coroutine ret = {coroutine.resume(co, ...)} end else co = coroutine.create(f) ret = {coroutine.resume(co, self, self._state.data, ...)} end -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else if coroutine.status(co) == "dead" then -- Remove dead coroutine self._state.coroutine = nil else assert(co == coroutine.running(), "coroutine wasn't running") end -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 1 then if #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else self._should_quit = true quit(ret[2]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} application._has_active_state_changed = false application._should_quit = false setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return setmetatable({}, {__index = function(_, event) local f = self._state.transitions[event] return function(...) run(self, f, ...) end end}) -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return setmetatable({}, {__index = function(_, event) return function(...) table.insert(self._event_queue[key], {event, {...}}) end end}) else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state if there isn't one already if not self._event_queue[self._state.name] then self._event_queue[self._state.name] = {} end -- Switch states self._state = new_state self._has_active_state_changed = true end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) self._has_active_state_changed = true local statename = self._state.name -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then run(self, nil, ...) end -- Catch up on events that happened for that state while we were in a -- different state, but make sure that states haven't changed since. if self._state.name == statename then local queued_events = self._event_queue[statename] self._event_queue[statename] = nil for _,event_bundle in ipairs(queued_events) do local f = self._state.transitions[event_bundle[1]] run(self, f, unpack(event_bundle[2])) end end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = {state, false} end -- Add the current state table.insert(states, {self._state, true}) return states end function AppLogic.get_current_state(self) return self._state.name end -- Will return true once after each time the active state has changed. function AppLogic.has_active_state_changed(self) local has_changed = self._has_active_state_changed self._has_active_state_changed = false return has_changed end return AppLogic
Fix issue where catching up on queued events could crash the app
Fix issue where catching up on queued events could crash the app
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
e447b010ce03f988d9ea3c1708bbcf50a0411f0e
mods/inventory_icon/init.lua
mods/inventory_icon/init.lua
inventory_icon = {} inventory_icon.hudids = {} inventory_icon.COLORIZE_STRING = "[colorize:#A00000:192" function inventory_icon.get_inventory_state(inv, listname) local size = inv:get_size(listname) local occupied = 0 for i=1,size do local stack = inv:get_stack(listname, i) if not stack:is_empty() then occupied = occupied + 1 end end return occupied, size end function inventory_icon.replace_icon(name) return "inventory_icon_"..name end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() inventory_icon.hudids[name] = {} local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end inventory_icon.hudids[name].main = {} inventory_icon.hudids[name].main.icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-32,y=-32}, text = icon, }) inventory_icon.hudids[name].main.text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-36,y=-20}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = string.format("%d/%d", occupied, size) }) if minetest.get_modpath("unified_inventory") ~= nil then inventory_icon.hudids[name].bags = {} local bags_inv = minetest.get_inventory({type = "detached", name = name.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end inventory_icon.hudids[name].bags[i] = {} inventory_icon.hudids[name].bags[i].icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = scale, size = { x=32, y=32 }, offset = {x=-36,y=-32 -40*i}, text = icon, }) inventory_icon.hudids[name].bags[i].text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = scale, offset = {x=-36,y=-20 -40*i}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = text, }) end end end) minetest.register_on_leaveplayer(function(player) inventory_icon.hudids[player:get_player_name()] = nil end) local function tick() minetest.after(1, tick) for playername,hudids in pairs(inventory_icon.hudids) do local player = minetest.get_player_by_name(playername) local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon, color if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end player:hud_change(hudids.main.icon, "text", icon) player:hud_change(hudids.main.text, "text", string.format("%d/%d", occupied, size)) if minetest.get_modpath("unified_inventory") ~= nil then local bags_inv = minetest.get_inventory({type = "detached", name = playername.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "text", icon) player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "scale", scale) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "text", text) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "scale", scale) end end end end tick()
inventory_icon = {} inventory_icon.hudids = {} inventory_icon.COLORIZE_STRING = "[colorize:#A00000:192" function inventory_icon.get_inventory_state(inv, listname) local size = inv:get_size(listname) local occupied = 0 for i=1,size do local stack = inv:get_stack(listname, i) if not stack:is_empty() then occupied = occupied + 1 end end return occupied, size end function inventory_icon.replace_icon(name) return "inventory_icon_"..name end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() inventory_icon.hudids[name] = {} local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end inventory_icon.hudids[name].main = {} inventory_icon.hudids[name].main.icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-32,y=-32}, text = icon, }) inventory_icon.hudids[name].main.text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-36,y=-20}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = string.format("%d/%d", occupied, size) }) if minetest.get_modpath("unified_inventory") ~= nil then inventory_icon.hudids[name].bags = {} local bags_inv = minetest.get_inventory({type = "detached", name = name.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end inventory_icon.hudids[name].bags[i] = {} inventory_icon.hudids[name].bags[i].icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = scale, size = { x=32, y=32 }, offset = {x=-36,y=-32 -40*i}, text = icon, }) inventory_icon.hudids[name].bags[i].text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = scale, offset = {x=-36,y=-20 -40*i}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = text, }) end end end) minetest.register_on_leaveplayer(function(player) inventory_icon.hudids[player:get_player_name()] = nil end) local function tick() minetest.after(1, tick) for playername,hudids in pairs(inventory_icon.hudids) do local player = minetest.get_player_by_name(playername) if player then local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon, color if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end player:hud_change(hudids.main.icon, "text", icon) player:hud_change(hudids.main.text, "text", string.format("%d/%d", occupied, size)) if minetest.get_modpath("unified_inventory") ~= nil then local bags_inv = minetest.get_inventory({type = "detached", name = playername.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "text", icon) player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "scale", scale) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "text", text) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "scale", scale) end end end end end tick()
fix crash if not player
fix crash if not player
Lua
unlicense
LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun
775a0922518b4e8f442688528297f39123beb54d
hymn/deposit.lua
hymn/deposit.lua
local Building = require "shared.building" local LogicCore = require "hymn.logiccore" local EntityStatics = require "hymn.staticdata.entitystatics" local GameMath = require "shared.gamemath" local Deposit = Building:subclass("Deposit") function Deposit:initialize(entityStatic) Building.initialize(self, entityStatic, player) self.claims = {} for playerId, player in pairs(LogicCore.players) do self.claims[playerId] = 0 end self:setAnimation("images/buildings/resourcesrock_neutral.png", 1) end local themes = { "frost", "lava", } function Deposit:update(dt) Building.update(self, dt) if somethingInterestingHappens then -- change ownership self:setAnimation("images/buildings/" .. self.theme .. "/resourcesrock.png", 0.1) end end function Deposit:takeOwnership(player) if self.owner then self.owner = self.owner.resource - 50 end player.resource = player.resource + 50 self.owner = player end function Deposit:claim(entity, amount) local playerId = entity.player.playerId local maxClaim = 0 for id, current in pairs(self.claims) do local diff = (id == playerId) and amount or -amount self.claims[id] = GameMath.clamp(current + diff, 0, 100) if id ~= playerId then maxClaim = math.max(maxClaim, self.claims[id]) end end dbgprint(table.concat(self.claims, ", ")) local ownClaim = self.claims[playerId] if maxClaim == 0 and ownClaim > 50 then self:takeOwnership(entity.player) end end return Deposit
local Building = require "shared.building" local LogicCore = require "hymn.logiccore" local EntityStatics = require "hymn.staticdata.entitystatics" local GameMath = require "shared.gamemath" local Deposit = Building:subclass("Deposit") function Deposit:initialize(entityStatic) Building.initialize(self, entityStatic, player) self.claims = {} for playerId, player in pairs(LogicCore.players) do self.claims[playerId] = 0 end self:setAnimation("images/buildings/resourcesrock_neutral.png", 1) end local themes = { "frost", "lava", } function Deposit:update(dt) Building.update(self, dt) if somethingInterestingHappens then -- change ownership self:setAnimation("images/buildings/" .. self.theme .. "/resourcesrock.png", 0.1) end end function Deposit:takeOwnership(player) if self.owner == player then return end if self.owner then self.owner = self.owner.resource - 50 end player.resource = player.resource + 50 self.owner = player end function Deposit:claim(entity, amount) local playerId = entity.player.playerId local maxClaim = 0 for id, current in pairs(self.claims) do local diff = (id == playerId) and amount or -amount self.claims[id] = GameMath.clamp(current + diff, 0, 100) if id ~= playerId then maxClaim = math.max(maxClaim, self.claims[id]) end end dbgprint(table.concat(self.claims, ", ")) local ownClaim = self.claims[playerId] if maxClaim == 0 and ownClaim > 50 then self:takeOwnership(entity.player) end end return Deposit
Fix: Don't change deposit ownership if already owned
Fix: Don't change deposit ownership if already owned
Lua
mit
ExcelF/project-navel
daa70acd8e6b5a05e5c761a7041b68838290eaa3
love2d/world.lua
love2d/world.lua
require "tileset" require "map" require "pawn" require "mapGenerator" function love.game.newWorld() local o = {} o.mapG = nil o.map = nil o.mapWidth = 32 o.mapHeight = 24 o.tileset = nil o.offsetX = 0 o.offsetY = 0 o.zoom = 1 o.offsetX = 0 o.offsetY = 0 o.goalX = 7 o.goalY =7 o.init = function() o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight) o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1) o.map = love.game.newMap(o.mapWidth, o.mapHeight) o.map.setTileset(o.tileset) o.map.init() --test for i = 1, o.mapWidth do for k = 1, o.mapHeight do -- field if MapGenerator.getID(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 1, 0) elseif MapGenerator.getID(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 1, 2) end --objects if MapGenerator.getObject(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 2, 3) elseif MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 2, 22) elseif MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18) else o.map.setTileLayer(i, k, 2, 63) end --objects 2 if MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k - 1, 3, 14) else o.map.setTileLayer(i, k - 1, 3, 63) end end end o.pawns = {} local pawn = love.game.newPawn(o) table.insert(o.pawns, pawn) end o.update = function(dt) if love.keyboard.isDown("left") then o.offsetX = o.offsetX + dt * 100 elseif love.keyboard.isDown("right") then o.offsetX = o.offsetX - dt * 100 end if love.keyboard.isDown("up") then o.offsetY = o.offsetY + dt * 100 elseif love.keyboard.isDown("down") then o.offsetY = o.offsetY - dt * 100 end o.map.update(dt) for i = 1, #o.pawns do o.pawns[i].update(dt) end for i = 1, o.mapWidth do for k = 1, o.mapHeight do if MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4)) end end end end o.draw = function() o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1) for i = 1, #o.pawns do o.pawns[i].draw(o.offsetX, o.offsetY) end o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2) o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3) o.drawMapCursor() end o.zoomIn = function(z) z = z or 2 o.zoom = o.zoom * z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.zoomOut = function(z) z = z or 2 o.zoom = o.zoom / z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.drawMapCursor = function() local mx = love.mouse.getX() local my = love.mouse.getY() --[[ local tileX, tileY = getTileFromScreen(o.map, mx, my) tileX = tileX * o.map.tileScale tileY = tileY * o.map.tileScale if tileX >= 0 and tileY >= 0 and tileX < o.map.width and tileY < o.map.height then G.setColor(255, 63, 0) G.setLineWidth(2) local tw = o.map.tileset.tileWidth local th = o.map.tileset.tileHeight if tw and th then G.rectangle("line", tileX * tw*o.zoom - o.offsetX , tileY * th*o.zoom - o.offsetY, tw*o.zoom*o.map.tileScale, th*o.zoom*o.map.tileScale) end end ]]-- G.setColor(255, 63, 0) G.rectangle("line", math.floor(mx / (o.tileset.tileWidth * o.map.tileScale * o.zoom)) * (o.tileset.tileWidth * o.map.tileScale * o.zoom), math.floor(my / (o.tileset.tileHeight * o.map.tileScale * o.zoom)) * (o.tileset.tileHeight * o.map.tileScale * o.zoom), o.tileset.tileWidth * o.map.tileScale * o.zoom, o.tileset.tileHeight * o.map.tileScale * o.zoom) end o.setGoal = function(map, x,y) o.goalX, o.goalY = getTileFromScreen(map,x,y) print (x, y, o.goalX, o.goalY) end return o end getTileFromScreen = function(map, mx, my) local ts = map.tileScale local tw = map.tileset.tileWidth local th = map.tileset.tileHeight local tileX =math.floor((mx) / (tw*ts)) local tileY =math.floor((my) / (tw*ts)) return tileX, tileY end
require "tileset" require "map" require "pawn" require "mapGenerator" function love.game.newWorld() local o = {} o.mapG = nil o.map = nil o.mapWidth = 32 o.mapHeight = 24 o.tileset = nil o.offsetX = 0 o.offsetY = 0 o.zoom = 1 o.offsetX = 0 o.offsetY = 0 o.goalX = 7 o.goalY =7 o.init = function() o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight) o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1) o.map = love.game.newMap(o.mapWidth, o.mapHeight) o.map.setTileset(o.tileset) o.map.init() --test for i = 1, o.mapWidth do for k = 1, o.mapHeight do -- field if MapGenerator.getID(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 1, 0) elseif MapGenerator.getID(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 1, 2) end --objects if MapGenerator.getObject(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 2, 3) elseif MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 2, 22) elseif MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18) else o.map.setTileLayer(i, k, 2, 63) end --objects 2 if MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k - 1, 3, 14) else o.map.setTileLayer(i, k - 1, 3, 63) end end end o.pawns = {} local pawn = love.game.newPawn(o) table.insert(o.pawns, pawn) end o.update = function(dt) if love.keyboard.isDown("left") then o.offsetX = o.offsetX + dt * 100 elseif love.keyboard.isDown("right") then o.offsetX = o.offsetX - dt * 100 end if love.keyboard.isDown("up") then o.offsetY = o.offsetY + dt * 100 elseif love.keyboard.isDown("down") then o.offsetY = o.offsetY - dt * 100 end o.map.update(dt) for i = 1, #o.pawns do o.pawns[i].update(dt) end for i = 1, o.mapWidth do for k = 1, o.mapHeight do if MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4)) end end end end o.draw = function() o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1) for i = 1, #o.pawns do o.pawns[i].draw(o.offsetX, o.offsetY) end o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2) o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3) o.drawMapCursor() end o.zoomIn = function(z) z = z or 2 o.zoom = o.zoom * z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.zoomOut = function(z) z = z or 2 o.zoom = o.zoom / z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.drawMapCursor = function() local mx = love.mouse.getX() local my = love.mouse.getY() --[[ local tileX, tileY = getTileFromScreen(o.map, mx, my) tileX = tileX * o.map.tileScale tileY = tileY * o.map.tileScale if tileX >= 0 and tileY >= 0 and tileX < o.map.width and tileY < o.map.height then G.setColor(255, 63, 0) G.setLineWidth(2) local tw = o.map.tileset.tileWidth local th = o.map.tileset.tileHeight if tw and th then G.rectangle("line", tileX * tw*o.zoom - o.offsetX , tileY * th*o.zoom - o.offsetY, tw*o.zoom*o.map.tileScale, th*o.zoom*o.map.tileScale) end end ]]-- G.setColor(255, 63, 0) G.rectangle("line", math.floor((mx - o.offsetX * o.zoom) / (o.tileset.tileWidth * o.map.tileScale * o.zoom)) * (o.tileset.tileWidth * o.map.tileScale * o.zoom) + (o.offsetX * o.zoom), math.floor((my - o.offsetY * o.zoom) / (o.tileset.tileHeight * o.map.tileScale * o.zoom)) * (o.tileset.tileHeight * o.map.tileScale * o.zoom) + (o.offsetY * o.zoom), o.tileset.tileWidth * o.map.tileScale * o.zoom, o.tileset.tileHeight * o.map.tileScale * o.zoom ) end o.setGoal = function(map, x,y) o.goalX, o.goalY = getTileFromScreen(map,x,y) print (x, y, o.goalX, o.goalY) end return o end getTileFromScreen = function(map, mx, my) local ts = map.tileScale local tw = map.tileset.tileWidth local th = map.tileset.tileHeight local tileX =math.floor((mx) / (tw*ts)) local tileY =math.floor((my) / (tw*ts)) return tileX, tileY end
Fix zoom.
Fix zoom.
Lua
mit
nczempin/lizard-journey
1e217337391c9a50d27e7632d8a284fa446f2e29
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/37_counters.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/37_counters.lua
--This program demonstrates how to use AINs as counters. --Most commonly users should throttle their code execution using the functions: --'LJ.IntervalConfig(0, 1000)', and 'if LJ.CheckInterval(0) then' ... --Array indeces 1-14 correspond with AIN0-13 --Array indeces 15-37 correspond with DIO0-22 as the following: --Index: 15 Channel: FIO0 (DIO0) --Index: 16 Channel: FIO1 (DIO1) --Index: 17 Channel: FIO2 (DIO2) --Index: 18 Channel: FIO3 (DIO3) --Index: 19 Channel: FIO4 (DIO4) --Index: 20 Channel: FIO5 (DIO5) --Index: 21 Channel: FIO6 (DIO6) --Index: 22 Channel: FIO7 (DIO7) --Index: 23 Channel: EIO0 (DIO8) --Index: 24 Channel: EIO1 (DIO9) --Index: 25 Channel: EIO2 (DIO10) --Index: 26 Channel: EIO3 (DIO11) --Index: 27 Channel: EIO4 (DIO12) --Index: 28 Channel: EIO5 (DIO13) --Index: 29 Channel: EIO6 (DIO14) --Index: 30 Channel: EIO7 (DIO15) --Index: 31 Channel: CIO0 (DIO16) --Index: 32 Channel: CIO1 (DIO17) --Index: 33 Channel: CIO2 (DIO18) --Index: 34 Channel: CIO3 (DIO19) --Index: 35 Channel: MIO0 (DIO20) --Index: 36 Channel: MIO1 (DIO21) --Index: 37 Channel: MIO2 (DIO22) print("Create and read 37 counters.") -- For sections of code that require precise timing assign global functions -- locally (local definitions of globals are marginally faster) local mbRead=MB.R local mbWrite=MB.W if (mbRead(60000, 3) ~= 7) then print("This example is only for the T7. Exiting Lua Script.") mbWrite(6000, 1, 0) end --AIN thresholds for binary conversion local threshold = {} threshold[1] = 2.8 threshold[2] = 2.8 threshold[3] = 2.8 threshold[4] = 2.8 threshold[5] = 1.5 threshold[6] = 1.5 threshold[7] = 1.5 threshold[8] = 1.5 threshold[9] = 1.5 threshold[10] = 1.5 threshold[11] = 4.1 threshold[12] = 4.1 threshold[13] = 4.1 threshold[14] = 4.1 --1 = Rising edge, 0 = falling local edge = {} for i = 1, 37 do edge[i] = 0 --sets all 37 counters to increment on falling edges end local bits = {} local bits_new = {} local count = {} --The throttle setting can correspond roughly with the length of the Lua --script. A rule of thumb for deciding a throttle setting is --throttle = (3*NumLinesCode) + 20 local throttleSetting = 100 --Default throttle setting is 10 instructions LJ.setLuaThrottle(throttleSetting) local throttleSetting = LJ.getLuaThrottle() print ("Current Lua Throttle Setting: ", throttleSetting) mbWrite(2600, 0, 0) --FIO to input mbWrite(2601, 0, 0) --EIO to input mbWrite(2602, 0, 0) --COI to input mbWrite(2603, 0, 0) --MIO to input mbWrite(43903, 0, 1) --AIN_ALL_RESOLUTION_INDEX to 1 mbWrite(6006, 1, 37) for i=1, 37 do bits[i] = 0 bits_new[i] = 99 count[i] = 0 end while true do --Analog channels AIN0-13 for i=1, 14 do if mbRead((i-1)*2, 3) > threshold[i] then bits_new[i]=1 else bits_new[i]=0 end end --Digital channels DIO0-22 for i=15, 37 do bits_new[i] = mbRead((i-15)+2000, 0) end --Compare bits_new to bits for i=1, 37 do if bits[i] ~= bits_new[i] then if edge[i] == 1 then if bits[i] == 0 then count[i] = count[i] + 1 print ("Counter: ", i, " Rising: ", count[i]) end else if bits[i] == 1 then count[i] = count[i] + 1 print ("Counter: ", i, " Falling: ", count[i]) end end bits[i] = bits_new[i] mbWrite(((i-1)*2)+46000, 3, count[i]) --Save in User RAM end end end
--[[ Name: 37_counters.lua Desc: This program demonstrates how to use AINs as counters. Note: In most cases, users should throttle their code execution using the functions: "LJ.IntervalConfig(0, 1000)", and "if LJ.CheckInterval(0)" --]] --Array indexes 1-14 correspond with AIN0-13 --Array indexes 15-37 correspond with DIO0-22 as the following: --Index: 15 Channel: FIO0 (DIO0) --Index: 16 Channel: FIO1 (DIO1) --Index: 17 Channel: FIO2 (DIO2) --Index: 18 Channel: FIO3 (DIO3) --Index: 19 Channel: FIO4 (DIO4) --Index: 20 Channel: FIO5 (DIO5) --Index: 21 Channel: FIO6 (DIO6) --Index: 22 Channel: FIO7 (DIO7) --Index: 23 Channel: EIO0 (DIO8) --Index: 24 Channel: EIO1 (DIO9) --Index: 25 Channel: EIO2 (DIO10) --Index: 26 Channel: EIO3 (DIO11) --Index: 27 Channel: EIO4 (DIO12) --Index: 28 Channel: EIO5 (DIO13) --Index: 29 Channel: EIO6 (DIO14) --Index: 30 Channel: EIO7 (DIO15) --Index: 31 Channel: CIO0 (DIO16) --Index: 32 Channel: CIO1 (DIO17) --Index: 33 Channel: CIO2 (DIO18) --Index: 34 Channel: CIO3 (DIO19) --Index: 35 Channel: MIO0 (DIO20) --Index: 36 Channel: MIO1 (DIO21) --Index: 37 Channel: MIO2 (DIO22) -- For sections of code that require precise timing assign global functions -- locally (local definitions of globals are marginally faster) local modbus_read=MB.R local modbus_write=MB.W print("Create and read 37 counters.") -- Read the PRODUCT_ID register to get the device type. This script will not -- run correctly on devices other than the T7 if (modbus_read(60000, 3) ~= 7) then print("This example is only for the T7. Exiting Lua Script.") -- Write a 0 to LUA_RUN to stop the script if not using a T7 modbus_write(6000, 1, 0) end -- AIN thresholds for binary conversion local threshold = {} threshold[1] = 2.8 threshold[2] = 2.8 threshold[3] = 2.8 threshold[4] = 2.8 threshold[5] = 1.5 threshold[6] = 1.5 threshold[7] = 1.5 threshold[8] = 1.5 threshold[9] = 1.5 threshold[10] = 1.5 threshold[11] = 4.1 threshold[12] = 4.1 threshold[13] = 4.1 threshold[14] = 4.1 -- 1 = Rising edge, 0 = falling local edge = {} for i = 1, 37 do edge[i] = 0 --sets all 37 counters to increment on falling edges end local bits = {} local newbits = {} local count = {} -- The throttle setting can correspond roughly with the length of the Lua -- script. A rule of thumb for deciding a throttle setting is -- Throttle = (3*NumLinesCode)+20. The default throttle setting is 10 instructions local throttle = 100 LJ.setLuaThrottle(throttle) throttle = LJ.getLuaThrottle() print ("Current Lua Throttle Setting: ", throttle) -- Set FIO registers to input modbus_write(2600, 0, 0) -- Set EIO registers to input modbus_write(2601, 0, 0) -- Set COI registers to input modbus_write(2602, 0, 0) -- Set MIO registers to input modbus_write(2603, 0, 0) -- Set AIN_ALL_RESOLUTION_INDEX to 1 (fastest setting) modbus_write(43903, 0, 1) for i=1, 37 do bits[i] = 0 newbits[i] = 99 count[i] = 0 end while true do --Analog channels AIN0-13 for i=1, 14 do -- If the channels value is above the threshold if modbus_read((i-1)*2, 3) > threshold[i] then newbits[i]=1 else newbits[i]=0 end end --Digital channels DIO0-22 for i=15, 37 do newbits[i] = modbus_read((i-15)+2000, 0) end --Compare newbits to bits for each counter for i=1, 37 do -- If bits[i] is different from newbits[i] the counter state changed if bits[i] ~= newbits[i] then -- If the counter should increase on a rising edge if edge[i] == 1 then -- If the last counter state was 0 then there was a rising edge, increment -- the counter if bits[i] == 0 then count[i] = count[i] + 1 print ("Counter: ", i-1, " Rising: ", count[i]) end -- If the counter should increase on a falling edge else -- If the last counter state was 1 then there was a falling edge, -- increment the counter if bits[i] == 1 then count[i] = count[i] + 1 print ("Counter: ", i-1, " Falling: ", count[i]) end end -- Adjust bits to reflect the new counter state bits[i] = newbits[i] -- Write the counter values to USER_RAM modbus_write(((i-1)*2)+46000, 3, count[i]) end end end
Fixed up the 37 counter example
Fixed up the 37 counter example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
1bd363f5fc2c4ff6a4042ce00063f6fa6eda5326
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/unipolar_full_step.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/unipolar_full_step.lua
-- The unipolar_full_step example script was written as part of LabJack''s -- "Stepper Motor Controller" App-Note. There is an accompanying python script -- as well as a (Windows Only) LabVIEW example application that should be run -- in conjunction wth this script. -- See: https://labjack.com/support/app-notes/digital-IO/stepper-motor-controller print("Use the following registers:") print("46080: Target Position (steps)") print("46082: Current Position (steps)") print("46180: enable, 1:enable, 0: disable") print("46181: eStop, 1: eStop, 0: run") print("46182: hold, 1: hold position of motor, 0: release motor (after movement)") print("46183: setHome, (setHome)") local mbR = MB.R local mbW = MB.W -- Configurable Variables local enable = false -- 46180, "USER_RAM0_U16", type: 0; enable/disable control. local targ = 0 -- 46080, "USER_RAM1_I32", type: 2 local pos = 0 -- 46082, "USER_RAM0_I32", type: 2 local eStop = 0 -- 46181, "USER_RAM1_U16", type: 0; Value read before setting I/O line states to immediately disengage motor. local hold = 1 -- 46182, "USER_RAM2_U16", type: 0;Enable hold mode by default at end of movement sequence. local setHome = 0 -- 46183, "USER_RAM3_U16", type: 0; Set new "zero" or "home" -- Define FIO Channels local chA = 2008--EIO0 local chB = 2009--EIO1 local chC = 2012--EIO4 local chD = 2013--EIO5 mbW(chA, 0, 0) --EIO0 = DIO8 mbW(chB, 0, 0) --EIO1 = DIO9 mbW(chC, 0, 0) --EIO4 = DIO12 mbW(chD, 0, 0) --EIO5 = DIO13 --Define the Full Step Sequence local a = {1,0,0,0} -- This is the control logic for line A local b = {0,0,1,0} -- This is the control logic for line A'' local c = {0,1,0,0} -- This is the control logic for line B local d = {0,0,0,1} -- This is the control logic for line B'' local numSteps =table.getn(a) local i = 0 local m0, m1, m2, m3 = 0 -- Set initial USER_RAM values. mbW(46080, 2, targ) mbW(46082, 2, pos) mbW(46180, 0, enable) mbW(46181, 0, eStop) mbW(46182, 0, hold) mbW(46183, 0, setHome) -- Initialize variable used for the Re-Zero "target"/Motor control. LJ.IntervalConfig(0, 4) -- For stepper motor control LJ.IntervalConfig(1, 1000) -- For printing current state while true do if LJ.CheckInterval(1) then print("Current State", enable, target, pos, eStop) end if LJ.CheckInterval(0) then enable = (mbR(46180, 0) == 1) -- Determine if we should start moving. targ = mbR(46080, 2) -- Read desired "target" if enable then -- if allowed to move if pos == targ then--if we have reached the new position --write enable to 0 to signal finished enable = false mbW(46180, 0, 0) print("reached new pos") -- Determine if motor should be "held in place" hold = mbR(46182, 0) if hold == 0 then --set all low to allow free movement m0 = 0 m1 = 0 m2 = 0 m3 = 0 end --else if hold then keep the same position activated elseif pos < targ then -- if behind, go foreward pos = pos+1--increment position by 1 i = pos%numSteps+1--lua is 1-indexed, so add a 1 m0 = a[i]--write the new positions m1 = b[i] m2 = c[i] m3 = d[i] elseif pos > targ then-- if ahead, move back pos = pos-1 i = pos%numSteps+1 m0 = a[i] m1 = b[i] m2 = c[i] m3 = d[i] end else -- if not enable hold = mbR(46182, 0) setHome = mbR(46183, 0) if setHome == 1 then-- if home register is set to make a new home print("New home created") mbW(46183, 0, 0) pos = 0;--make a new home end if hold == 0 then m0 = 0 m1 = 0 m2 = 0 m3 = 0 end end -- Update variable with current position mbW(46082, 2, pos) eStop = mbR(46181, 0) if eStop == 1 then m0 = 0; m1 = 0; m2 = 0; m3 = 0 end mbW(chA, 0, m0) --EIO0 = DIO8 mbW(chB, 0, m1) --EIO1 = DIO9 mbW(chC, 0, m2) --EIO2 = DIO10 mbW(chD, 0, m3) --EIO3 = DIO11 end end
--[[ Name: unipolar_full_step.lua Desc: The unipolar_full_step example script was written as part of LabJack's "Stepper Motor Controller" App-Note. Note: There is an accompanying python script as well as a (Windows Only) LabVIEW example application that should be run in conjunction wth this script. See: https://labjack.com/support/app-notes/digital-IO/stepper-motor-controller --]] print("Use the following registers:") print("46080: Target Position (steps)") print("46082: Current Position (steps)") print("46180: enable, 1:enable, 0: disable") print("46181: estop, 1: estop, 0: run") print("46182: hold, 1: hold position of motor, 0: release motor (after movement)") print("46183: sethome, (sethome)") -- 46180, "USER_RAM0_U16", type: 0; enable/disable control local enable = false -- 46080, "USER_RAM1_I32", type: 2; target location local targ = 0 -- 46082, "USER_RAM0_I32", type: 2; position relative to the target local pos = 0 -- 46181, "USER_RAM1_U16", type: 0; Value read before setting I/O line states -- to immediately disengage motor local estop = 0 -- 46182, "USER_RAM2_U16", type: 0; Enable hold mode by default at end of a -- movement sequence local hold = 1 -- 46183, "USER_RAM3_U16", type: 0; Set new "zero" or "home" local sethome = 0 --EIO0 local channela = 2008 --EIO1 local channelb = 2009 --EIO4 local channelc = 2012 --EIO5 local channeld = 2013 MB.W(channela, 0, 0) MB.W(channelb, 0, 0) MB.W(channelc, 0, 0) MB.W(channeld, 0, 0) --Define the Full Step Sequence local a = {1,0,0,0} -- This is the control logic for line A local b = {0,0,1,0} -- This is the control logic for line A' local c = {0,1,0,0} -- This is the control logic for line B local d = {0,0,0,1} -- This is the control logic for line B' local numSteps =table.getn(a) local i = 0 local m0, m1, m2, m3 = 0 -- Set initial USER_RAM values. MB.W(46080, 2, targ) MB.W(46082, 2, pos) MB.W(46180, 0, enable) MB.W(46181, 0, estop) MB.W(46182, 0, hold) MB.W(46183, 0, sethome) -- Configure an interval for stepper motor control LJ.IntervalConfig(0, 4) -- Configure an interval for printing the current state LJ.IntervalConfig(1, 1000) while true do -- If a print interval is done if LJ.CheckInterval(1) then print("Current State", enable, target, pos, estop) end -- If a stepper interval is done if LJ.CheckInterval(0) then -- Read USER_RAM to determine if we should start moving enable = (MB.R(46180, 0) == 1) -- Read USER_RAM to get the desired target targ = MB.R(46080, 2) -- If the motor is allowed to move if enable then -- If we have reached the new position if pos == targ then -- Set enable to 0 to signal that the movement is finished enable = false MB.W(46180, 0, 0) print("reached new pos") -- Determine if the motor should be "held in place" hold = MB.R(46182, 0) if hold == 0 then -- Set all low to allow free movement m0 = 0 m1 = 0 m2 = 0 m3 = 0 end -- Else if the motor should be held keep the same position activated -- If behind the target, go forward elseif pos < targ then pos = pos+1 -- Lua is 1-indexed, so add a 1 i = pos%numSteps+1 -- Write the new positions m0 = a[i] m1 = b[i] m2 = c[i] m3 = d[i] -- If ahead of the target, move back elseif pos > targ then pos = pos-1 i = pos%numSteps+1 m0 = a[i] m1 = b[i] m2 = c[i] m3 = d[i] end -- If the motor is not enabled to move else -- Check again if the motor is enabled to move hold = MB.R(46182, 0) sethome = MB.R(46183, 0) -- If the home register is set to make a new home if sethome == 1 then print("New home created") MB.W(46183, 0, 0) -- Make a new home pos = 0; end if hold == 0 then m0 = 0 m1 = 0 m2 = 0 m3 = 0 end end -- Save the current position to USER_RAM MB.W(46082, 2, pos) estop = MB.R(46181, 0) if estop == 1 then m0 = 0; m1 = 0; m2 = 0; m3 = 0 end MB.W(channela, 0, m0) MB.W(channelb, 0, m1) MB.W(channelc, 0, m2) MB.W(channeld, 0, m3) end end
Fixed up the formatting of the unipolar full step example
Fixed up the formatting of the unipolar full step example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
9c349998457260a6b87a897138d82b0b0530176f
lua/wire/client/cl_gpulib.lua
lua/wire/client/cl_gpulib.lua
local RT_CACHE_SIZE = 32 // // Create rendertarget cache // if not RenderTargetCache then RenderTargetCache = {} for i = 1,RT_CACHE_SIZE do RenderTargetCache[i] = { Target = GetRenderTarget("WireGPU_RT_"..i, 512, 512), Used = false } end end // // Create basic fonts // surface.CreateFont("lucida console", 20, 800, true, false, "WireGPU_ConsoleFont") // // Create screen textures and materials // WireGPU_matScreen = Material("ignore_this_error") -------------------------------------------------------------------------------- -- WireGPU class -------------------------------------------------------------------------------- -- Usage: -- Initialize: -- self.GPU = WireGPU(self.Entity) -- -- OnRemove: -- self.GPU:Finalize() -- -- Draw (if something changes): -- self.GPU:RenderToGPU(function() -- ...code... -- end) -- -- Draw (every frame): -- self.GPU:Render() -------------------------------------------------------------------------------- local GPU = {} GPU.__index = GPU function WireGPU(ent) local self = { entindex = ent:EntIndex(), Entity = ent, } setmetatable(self, GPU) self:Initialize() return self end function GPU:Initialize() -- Rendertarget cache management -- fallback self.RT = RenderTargetCache[1].Target -- find a free one for i = 1,#RenderTargetCache do if not RenderTargetCache[i].Used then RenderTargetCache[i].Used = true self.RTindex = i self.RT = RenderTargetCache[i].Target break end end self:Clear() return self.RT end function GPU:Finalize() if self.RTindex and RenderTargetCache[self.RTindex] then RenderTargetCache[self.RTindex].Used = false end end function GPU:Clear() render.ClearRenderTarget(self.RT, Color(0, 0, 0)) end local texcoords = { [0] = { { u = 0, v = 0 }, { u = 1, v = 0 }, { u = 1, v = 1 }, { u = 0, v = 1 }, }, { { u = 0, v = 1 }, { u = 0, v = 0 }, { u = 1, v = 0 }, { u = 1, v = 1 }, }, { { u = 1, v = 1 }, { u = 0, v = 1 }, { u = 0, v = 0 }, { u = 1, v = 0 }, }, { { u = 1, v = 0 }, { u = 1, v = 1 }, { u = 0, v = 1 }, { u = 0, v = 0 }, }, } -- helper function for GPU:Render function GPU.DrawScreen(x, y, w, h, rotation, scale) -- generate vertex data local vertices = { Vector(x , y ), Vector(x+w, y ), Vector(x+w, y+h), Vector(x , y+h), --[[ { x = x , y = y }, { x = x+w, y = y }, { x = x+w, y = y+h }, { x = x , y = y+h }, ]] } -- rotation and scaling local rotated_texcoords = texcoords[rotation] or texcoords[0] for index,vertex in ipairs(vertices) do local tex = rotated_texcoords[index] if tex.u == 0 then vertex.u = tex.u-scale else vertex.u = tex.u+scale end if tex.v == 0 then vertex.v = tex.v-scale else vertex.v = tex.v+scale end end --surface.DrawPoly(vertices) render.DrawQuad(unpack(vertices)) end function GPU:RenderToGPU(renderfunction) local oldw = ScrW() local oldh = ScrH() local NewRT = self.RT local OldRT = render.GetRenderTarget() render.SetRenderTarget(NewRT) render.SetViewPort(0, 0, 512, 512) cam.Start2D() PCallError(renderfunction) cam.End2D() render.SetViewPort(0, 0, oldw, oldh) render.SetRenderTarget(OldRT) end function GPU:Render(rotation, scale, width, height, postrenderfunction) local model = self.Entity:GetModel() local monitor = WireGPU_Monitors[model] local ang = self.Entity:LocalToWorldAngles(monitor.rot) local pos = self.Entity:LocalToWorld(monitor.offset) local OldTex = WireGPU_matScreen:GetMaterialTexture("$basetexture") WireGPU_matScreen:SetMaterialTexture("$basetexture", self.RT) cam.Start3D2D(pos, ang, monitor.RS) PCallError(function() local aspect = 1/monitor.RatioX local w = (width or 512)*aspect local h = (height or 512) local x = -w/2 local y = -h/2 surface.SetDrawColor(0,0,0,255) surface.DrawRect(-256*aspect,-256,512*aspect,512) render.SetMaterial(WireGPU_matScreen) self.DrawScreen(x, y, w, h, rotation or 0, scale or 0) if postrenderfunction then postrenderfunction(pos, ang, monitor.RS, aspect) end end) cam.End3D2D() WireGPU_matScreen:SetMaterialTexture("$basetexture", OldTex) end -- compatibility local GPUs = {} function WireGPU_NeedRenderTarget(entindex) if not GPUs[entindex] then GPUs[entindex] = WireGPU(Entity(entindex)) end return GPUs[entindex].RT end function WireGPU_GetMyRenderTarget(entindex) local self = GPUs[entindex] if self.RT then return self.RT end return self:Initialize() end function WireGPU_ReturnRenderTarget(entindex) return GPUs[entindex]:Finalize() end function WireGPU_DrawScreen(x, y, w, h, rotation, scale) return GPU.DrawScreen(x, y, w, h, rotation, scale) end
local RT_CACHE_SIZE = 32 // // Create rendertarget cache // if not RenderTargetCache then RenderTargetCache = {} for i = 1,RT_CACHE_SIZE do RenderTargetCache[i] = { Target = GetRenderTarget("WireGPU_RT_"..i, 512, 512), Used = false } end end // // Create basic fonts // surface.CreateFont("lucida console", 20, 800, true, false, "WireGPU_ConsoleFont") // // Create screen textures and materials // WireGPU_matScreen = Material("ignore_this_error") WireGPU_texScreen = surface.GetTextureID("ignore_this_error") -------------------------------------------------------------------------------- -- WireGPU class -------------------------------------------------------------------------------- -- Usage: -- Initialize: -- self.GPU = WireGPU(self.Entity) -- -- OnRemove: -- self.GPU:Finalize() -- -- Draw (if something changes): -- self.GPU:RenderToGPU(function() -- ...code... -- end) -- -- Draw (every frame): -- self.GPU:Render() -------------------------------------------------------------------------------- local GPU = {} GPU.__index = GPU function WireGPU(ent) local self = { entindex = ent:EntIndex(), Entity = ent, } setmetatable(self, GPU) self:Initialize() return self end function GPU:Initialize() -- Rendertarget cache management -- fallback self.RT = RenderTargetCache[1].Target -- find a free one for i = 1,#RenderTargetCache do if not RenderTargetCache[i].Used then RenderTargetCache[i].Used = true self.RTindex = i self.RT = RenderTargetCache[i].Target break end end self:Clear() return self.RT end function GPU:Finalize() if self.RTindex and RenderTargetCache[self.RTindex] then RenderTargetCache[self.RTindex].Used = false end end function GPU:Clear() render.ClearRenderTarget(self.RT, Color(0, 0, 0)) end local texcoords = { [0] = { { u = 0, v = 0 }, { u = 1, v = 0 }, { u = 1, v = 1 }, { u = 0, v = 1 }, }, { { u = 0, v = 1 }, { u = 0, v = 0 }, { u = 1, v = 0 }, { u = 1, v = 1 }, }, { { u = 1, v = 1 }, { u = 0, v = 1 }, { u = 0, v = 0 }, { u = 1, v = 0 }, }, { { u = 1, v = 0 }, { u = 1, v = 1 }, { u = 0, v = 1 }, { u = 0, v = 0 }, }, } -- helper function for GPU:Render function GPU.DrawScreen(x, y, w, h, rotation, scale) -- generate vertex data local vertices = { --[[ Vector(x , y ), Vector(x+w, y ), Vector(x+w, y+h), Vector(x , y+h), ]] { x = x , y = y }, { x = x+w, y = y }, { x = x+w, y = y+h }, { x = x , y = y+h }, } -- rotation and scaling local rotated_texcoords = texcoords[rotation] or texcoords[0] for index,vertex in ipairs(vertices) do local tex = rotated_texcoords[index] if tex.u == 0 then vertex.u = tex.u-scale else vertex.u = tex.u+scale end if tex.v == 0 then vertex.v = tex.v-scale else vertex.v = tex.v+scale end end surface.DrawPoly(vertices) --render.DrawQuad(unpack(vertices)) end function GPU:RenderToGPU(renderfunction) local oldw = ScrW() local oldh = ScrH() local NewRT = self.RT local OldRT = render.GetRenderTarget() render.SetRenderTarget(NewRT) render.SetViewPort(0, 0, 512, 512) cam.Start2D() PCallError(renderfunction) cam.End2D() render.SetViewPort(0, 0, oldw, oldh) render.SetRenderTarget(OldRT) end function GPU:Render(rotation, scale, width, height, postrenderfunction) local model = self.Entity:GetModel() local monitor = WireGPU_Monitors[model] local ang = self.Entity:LocalToWorldAngles(monitor.rot) local pos = self.Entity:LocalToWorld(monitor.offset) local OldTex = WireGPU_matScreen:GetMaterialTexture("$basetexture") WireGPU_matScreen:SetMaterialTexture("$basetexture", self.RT) cam.Start3D2D(pos, ang, monitor.RS) PCallError(function() local aspect = 1/monitor.RatioX local w = (width or 512)*aspect local h = (height or 512) local x = -w/2 local y = -h/2 surface.SetDrawColor(0,0,0,255) surface.DrawRect(-256*aspect,-256,512*aspect,512) surface.SetTexture(WireGPU_texScreen) self.DrawScreen(x, y, w, h, rotation or 0, scale or 0) if postrenderfunction then postrenderfunction(pos, ang, monitor.RS, aspect) end end) cam.End3D2D() WireGPU_matScreen:SetMaterialTexture("$basetexture", OldTex) end -- compatibility local GPUs = {} function WireGPU_NeedRenderTarget(entindex) if not GPUs[entindex] then GPUs[entindex] = WireGPU(Entity(entindex)) end return GPUs[entindex].RT end function WireGPU_GetMyRenderTarget(entindex) local self = GPUs[entindex] if self.RT then return self.RT end return self:Initialize() end function WireGPU_ReturnRenderTarget(entindex) return GPUs[entindex]:Finalize() end function WireGPU_DrawScreen(x, y, w, h, rotation, scale) return GPU.DrawScreen(x, y, w, h, rotation, scale) end
[GPULib] Drawing textures instead of materials again. This might or might not fix the bugs where a screen displays the wrong contents.
[GPULib] Drawing textures instead of materials again. This might or might not fix the bugs where a screen displays the wrong contents.
Lua
apache-2.0
mitterdoo/wire,CaptainPRICE/wire,bigdogmat/wire,dvdvideo1234/wire,sammyt291/wire,rafradek/wire,garrysmodlua/wire,Grocel/wire,mms92/wire,notcake/wire,wiremod/wire,NezzKryptic/Wire,immibis/wiremod,plinkopenguin/wiremod,Python1320/wire,thegrb93/wire
ae32c5bb6a4e7ec9e804e0d9cdec9493a19a440e
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " ") or ""; local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ((#body > length_threshold) or (body:find(trigger_string, 1, true) == 1)) then body = body:gsub("^" .. trigger_string, "", 1); local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Fix trigger_string matching when no trigger is set, and add support for counting lines (pastebin_line_threshold, default: 4)
mod_pastebin: Fix trigger_string matching when no trigger is set, and add support for counting lines (pastebin_line_threshold, default: 4)
Lua
mit
BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,syntafin/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,softer/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,heysion/prosody-modules
0bd6a3916227608d5a1f952a05e70238de8d79c7
bin/busted.lua
bin/busted.lua
if ngx ~= nil then ngx.exit = function()end end if os.getenv('CI') == 'true' then local luacov = require('luacov.runner') local pwd = os.getenv('PWD') for _, option in ipairs({"statsfile", "reportfile"}) do -- properly expand current working dir, workaround for https://github.com/openresty/resty-cli/issues/35 luacov.defaults[option] = pwd .. package.config:sub(1, 1) .. luacov.defaults[option] end table.insert(arg, '--coverage') end -- Busted command-line runner require 'busted.runner'({ standalone = false })
-- Clean warning on openresty 1.15.8.1, where some global variables are set -- using ngx.timer that triggers an invalid warning message. -- Code related: https://github.com/openresty/lua-nginx-module/blob/61e4d0aac8974b8fad1b5b93d0d3d694d257d328/src/ngx_http_lua_util.c#L795-L839 getmetatable(_G).__newindex = nil if ngx ~= nil then ngx.exit = function()end end if os.getenv('CI') == 'true' then local luacov = require('luacov.runner') local pwd = os.getenv('PWD') for _, option in ipairs({"statsfile", "reportfile"}) do -- properly expand current working dir, workaround for https://github.com/openresty/resty-cli/issues/35 luacov.defaults[option] = pwd .. package.config:sub(1, 1) .. luacov.defaults[option] end table.insert(arg, '--coverage') end -- Busted command-line runner require 'busted.runner'({ standalone = false })
Fix invalid warning message from openresty 1.15.8.1
Fix invalid warning message from openresty 1.15.8.1 Signed-off-by: Eloy Coto <2a8acc28452926ceac4d9db555411743254cf5f9@gmail.com>
Lua
mit
3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast
716941cd019a1d1c398261fe05b1474fab8eb65e
nvim/.config/nvim/lua/gb/lsp.lua
nvim/.config/nvim/lua/gb/lsp.lua
local nvim_lsp = require("lspconfig") 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 = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()) nvim_lsp.terraformls.setup{ on_attach = function (client) require "lsp-format".on_attach(client) end, on_init = custom_on_init } nvim_lsp.vimls.setup {} nvim_lsp.jsonls.setup { cmd = {"vscode-json-language-server", "--stdio"}, on_attach = function (client) require "lsp-format".on_attach(client) end, capabilities = capabilities, filetypes = {"json", "jsonc"}, settings = { json = { -- Schemas https://www.schemastore.org schemas = { { fileMatch = {"package.json"}, url = "https://json.schemastore.org/package.json" }, { fileMatch = {"tsconfig*.json"}, url = "https://json.schemastore.org/tsconfig.json" }, { fileMatch = { ".prettierrc", ".prettierrc.json", "prettier.config.json" }, url = "https://json.schemastore.org/prettierrc.json" }, { fileMatch = {".eslintrc", ".eslintrc.json"}, url = "https://json.schemastore.org/eslintrc.json" }, { fileMatch = {".babelrc", ".babelrc.json", "babel.config.json"}, url = "https://json.schemastore.org/babelrc.json" }, { fileMatch = {"lerna.json"}, url = "https://json.schemastore.org/lerna.json" }, { fileMatch = {"now.json", "vercel.json"}, url = "https://json.schemastore.org/now.json" }, { fileMatch = { ".stylelintrc", ".stylelintrc.json", "stylelint.config.json" }, url = "http://json.schemastore.org/stylelintrc.json" } } } } } --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.server_capabilities.documentFormattingProvider = false end, capabilities = capabilities, 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 } nvim_lsp.rust_analyzer.setup { on_attach = function (client) require "lsp-format".on_attach(client) end } --must run: npm install -g pyright nvim_lsp.pyright.setup { on_init = custom_on_init, on_attach = function(client) require "lsp-format".on_attach(client) end } 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-langservers-extracted nvim_lsp.cssls.setup { on_init = custom_on_init, capabilities = capabilities } -- npm i -g vscode-langservers-extracted nvim_lsp.html.setup { on_init = custom_on_init } nvim_lsp.eslint.setup { on_init = custom_on_init, on_attach = function(client) -- local group = vim.api.nvim_create_augroup("Eslint", {}) -- vim.api.nvim_create_autocmd("BufWritePre", { -- group = group, -- pattern = "*.ts,*.tsx,*.js", -- command = "EslintFixAll", -- desc = "Run eslint when saving buffer.", -- }) end, capabilities = capabilities, -- declared elsewhere } local cmp = require("cmp") local lspkind = require("lspkind") cmp.setup { sources = { {name = "nvim_lsp"}, {name = "buffer"}, {name = "nvim_lua"}, {name = "path"}, { name = 'nvim_lsp_signature_help' } }, comparators = { cmp.config.compare.recently_used, cmp.config.compare.locality, cmp.config.compare.score, -- based on : score = score + ((#sources - (source_index - 1)) * sorting.priority_weight) cmp.config.compare.offset, cmp.config.compare.order, }, formatting = { format = lspkind.cmp_format( { mode = "symbol_text", maxwidth = 50, -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters) -- The function below will be called before any actual modifications from lspkind -- so that you can provide more controls on popup customization. (See [#30](https://github.com/onsails/lspkind-nvim/pull/30)) before = function(entry, vim_item) vim_item.kind = lspkind.presets.default[vim_item.kind] .. " " .. vim_item.kind -- set a name for each source vim_item.menu = ({ buffer = " (Buffer)", nvim_lsp = " (LSP)", nvim_lua = " (Lua)", path = " (Path)", })[entry.source.name] return vim_item end } ) }, mapping = { ["<Tab>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}), ["<S-Tab>"] = cmp.mapping(cmp.mapping.select_prev_item(), {"i", "s"}), ["<C-Space>"] = cmp.mapping.complete(), ["<CR>"] = cmp.mapping.confirm( { behavior = cmp.ConfirmBehavior.Replace, select = true } ) } } local signs = {"Error", "Warn", "Hint", "Info"} for index, type in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, {text = "▊ ", texthl = hl, numhl = hl}) end vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"} vim.opt.completeopt = "menu,menuone,noselect" vim.keymap.set("n", "<leader>f", '<CMD>EslintFixAll<CR>', {silent = true}) vim.keymap.set("n", "gd", function() vim.lsp.buf.definition() end, {silent = true}) vim.keymap.set("n", "gR", function() vim.lsp.buf.rename() end) vim.keymap.set("n", "gr", function() require'telescope.builtin'.lsp_references({cwd= vim.fn.expand('%:h')}) end) -- vim.keymap.set("n", "gr", "<cmd>Telescope lsp_references({cwd: utils.buffer_dir()})<cr>") vim.keymap.set("n", "<leader>e", function() vim.diagnostic.goto_next() end, {silent = true}) vim.keymap.set("n", "<leader>cd", function() vim.diagnostic.show_line_diagnostics() end, {silent = true}) vim.keymap.set("n", "K", function() vim.lsp.buf.hover() end, {silent = true}) vim.keymap.set("n", "<leader>ca", function () vim.lsp.buf.code_action() end)
local nvim_lsp = require("lspconfig") 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 = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()) nvim_lsp.terraformls.setup{ on_attach = function (client) require "lsp-format".on_attach(client) end, on_init = custom_on_init } nvim_lsp.vimls.setup {} nvim_lsp.jsonls.setup { cmd = {"vscode-json-language-server", "--stdio"}, on_attach = function (client) require "lsp-format".on_attach(client) end, capabilities = capabilities, filetypes = {"json", "jsonc"}, settings = { json = { -- Schemas https://www.schemastore.org schemas = { { fileMatch = {"package.json"}, url = "https://json.schemastore.org/package.json" }, { fileMatch = {"tsconfig*.json"}, url = "https://json.schemastore.org/tsconfig.json" }, { fileMatch = { ".prettierrc", ".prettierrc.json", "prettier.config.json" }, url = "https://json.schemastore.org/prettierrc.json" }, { fileMatch = {".eslintrc", ".eslintrc.json"}, url = "https://json.schemastore.org/eslintrc.json" }, { fileMatch = {".babelrc", ".babelrc.json", "babel.config.json"}, url = "https://json.schemastore.org/babelrc.json" }, { fileMatch = {"lerna.json"}, url = "https://json.schemastore.org/lerna.json" }, { fileMatch = {"now.json", "vercel.json"}, url = "https://json.schemastore.org/now.json" }, { fileMatch = { ".stylelintrc", ".stylelintrc.json", "stylelint.config.json" }, url = "http://json.schemastore.org/stylelintrc.json" } } } } } --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.server_capabilities.documentFormattingProvider = false end, capabilities = capabilities, 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 } nvim_lsp.rust_analyzer.setup { on_attach = function (client) require "lsp-format".on_attach(client) end } --must run: npm install -g pyright nvim_lsp.pyright.setup { on_init = custom_on_init, on_attach = function(client) require "lsp-format".on_attach(client) end } 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-langservers-extracted nvim_lsp.cssls.setup { on_init = custom_on_init, capabilities = capabilities } -- npm i -g vscode-langservers-extracted nvim_lsp.html.setup { on_init = custom_on_init } nvim_lsp.eslint.setup { on_init = custom_on_init, on_attach = function(client) -- local group = vim.api.nvim_create_augroup("Eslint", {}) -- vim.api.nvim_create_autocmd("BufWritePre", { -- group = group, -- pattern = "*.ts,*.tsx,*.js", -- command = "EslintFixAll", -- desc = "Run eslint when saving buffer.", -- }) end, capabilities = capabilities, -- declared elsewhere } local cmp = require("cmp") local lspkind = require("lspkind") cmp.setup { sources = { {name = "nvim_lsp"}, {name = "buffer"}, {name = "nvim_lua"}, {name = "path"}, { name = 'nvim_lsp_signature_help' } }, snippet = { expand = function() end }, comparators = { cmp.config.compare.recently_used, cmp.config.compare.locality, cmp.config.compare.score, -- based on : score = score + ((#sources - (source_index - 1)) * sorting.priority_weight) cmp.config.compare.offset, cmp.config.compare.order, }, formatting = { format = lspkind.cmp_format( { mode = "symbol_text", maxwidth = 50, -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters) -- The function below will be called before any actual modifications from lspkind -- so that you can provide more controls on popup customization. (See [#30](https://github.com/onsails/lspkind-nvim/pull/30)) before = function(entry, vim_item) vim_item.kind = lspkind.presets.default[vim_item.kind] .. " " .. vim_item.kind -- set a name for each source vim_item.menu = ({ buffer = " (Buffer)", nvim_lsp = " (LSP)", nvim_lua = " (Lua)", path = " (Path)", })[entry.source.name] return vim_item end } ) }, mapping = { ["<Tab>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}), ["<S-Tab>"] = cmp.mapping(cmp.mapping.select_prev_item(), {"i", "s"}), ["<C-Space>"] = cmp.mapping.complete(), ["<CR>"] = cmp.mapping.confirm( { behavior = cmp.ConfirmBehavior.Replace, select = true } ) } } local signs = {"Error", "Warn", "Hint", "Info"} for index, type in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, {text = "▊ ", texthl = hl, numhl = hl}) end vim.g.completion_matching_strategy_list = {"exact", "substring", "fuzzy"} vim.opt.completeopt = "menu,menuone,noselect" vim.keymap.set("n", "<leader>f", '<CMD>EslintFixAll<CR>', {silent = true}) vim.keymap.set("n", "gd", function() vim.lsp.buf.definition() end, {silent = true}) vim.keymap.set("n", "gR", function() vim.lsp.buf.rename() end) vim.keymap.set("n", "gr", function() require'telescope.builtin'.lsp_references({cwd= vim.fn.expand('%:h')}) end) -- vim.keymap.set("n", "gr", "<cmd>Telescope lsp_references({cwd: utils.buffer_dir()})<cr>") vim.keymap.set("n", "<leader>e", function() vim.diagnostic.goto_next() end, {silent = true}) vim.keymap.set("n", "<leader>cd", function() vim.diagnostic.show_line_diagnostics() end, {silent = true}) vim.keymap.set("n", "K", function() vim.lsp.buf.hover() end, {silent = true}) vim.keymap.set("n", "<leader>ca", function () vim.lsp.buf.code_action() end)
Fix lsp with empty snippet function for tsserver
Fix lsp with empty snippet function for tsserver
Lua
mit
gblock0/dotfiles
bf573701018606d334e57349afc2f5962818ba16
share/lua/website/bbc.lua
share/lua/website/bbc.lua
-- quvi -- Copyright (C) 2010 quvi project -- -- This file is part of quvi <http://quvi.googlecode.com/>. -- -- 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 -- Obtained with grep -oP '(?<=service=")[^"]+(?=")' on config local fmt_id_lookup = { high = 'iplayer_streaming_h264_flv_high', standard = 'iplayer_streaming_h264_flv', low = 'iplayer_streaming_h264_flv_lo', vlow = 'iplayer_streaming_h264_flv_vlo' -- iplayer_streaming_n95_3g -- iplayer_streaming_n95_wifi } -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "www.bbc.co.uk" r.formats = "default|best" for k,_ in pairs(fmt_id_lookup) do r.formats = r.formats .."|".. k end r.categories = C.proto_rtmp local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/iplayer/"}) return r end -- Parse video URL. function parse(self) function create_uri_for_limelight_level3_iplayertok(params) params.uri = 'rtmp://' .. params.server .. ':1935/ondemand?_fcs_vhost=' .. params.server .. '&auth=' .. params.authString .. '&aifp=v001&slist=' .. params.identifier end function process_akamai(params) params.application = params.application or 'ondemand' params.application = params.application .. '?_fcs_vhost=' .. params.server .. '&undefined' params.uri = 'rtmp://' .. params.server .. ':1935/' .. params.application if not params.authString:find("&aifp=") then params.authString = params.authString .. '&aifp=v001' end if not params.authString:find("&slist=") then params.identifier = params.identifier:gsub('^mp[34]:', '') params.authString = params.authString .. '&slist=' .. params.identifier end params.identifier = params.identifier .. '?' .. params.authString params.uri = params.uri .. '&' .. params.authString params.application = params.application .. '&' .. params.authString params.tcurl = 'rtmp://' .. params.server .. ':80/' .. params.application end function process_limelight_level3(params) create_uri_for_limelight_level3_iplayertok(params) params.application = params.application .. '&' .. params.authString params.tcurl = 'rtmp://' .. params.server .. ':1935/' .. params.application end function process_iplayertok(params) create_uri_for_limelight_level3_iplayertok(params) params.identifier = params.identifier .. '?' .. params.authString params.identifier = params.identifier:gsub('^mp[34]:', '') params.tcurl = 'rtmp://' .. params.server .. ':1935/' .. params.application end self.host_id = 'bbc' local _,_,s = self.page_url:find('episode/(.-)/') local episode_id = s or error('no match: episode id') self.id = episode_id local playlist_uri = 'http://www.bbc.co.uk/iplayer/playlist/' .. episode_id local playlist = quvi.fetch(playlist_uri, {fetch_type = 'playlist'}) local pl_item_p,_,s = playlist:find('<item kind="programme".-identifier="(.-)"') local media_id = s or error('no match: media id') local _,_,s = playlist:find('duration="(%d+)"', pl_item_p) self.duration = tonumber(s) or 0 local _,_,s = playlist:find('<title>(.-)</title>') self.title = s or error('no match: video title') local _,_,s = playlist:find('<link rel="holding" href="(.-)"') self.media_thumbnail_url = s or "" -- stolen from http://lua-users.org/wiki/MathLibraryTutorial math.randomseed(os.time()) math.random() math.random() math.random() local config_uri = 'http://www.bbc.co.uk/mediaselector/4/mtis/stream/' .. media_id .. "?cb=" .. math.random(10000) local config = quvi.fetch(config_uri, {fetch_type = 'config'}) available_formats = {} for fmt_id in config:gmatch("iplayer_streaming_[%w_]+") do available_formats[fmt_id] = true end -- Create the list of acceptable formats, ordered by preference local r = self.requested_format local preferred = ((r == 'best') and {'high', 'standard', 'low', 'vlow'}) or ((r == 'default') and {'standard', 'low', 'vlow', 'high'}) or {r} -- Pick the first acceptable format available local format for _, cur_format in ipairs(preferred) do if available_formats[fmt_id_lookup[cur_format]] then format = cur_format break end end if not format then error('format not available') end -- Iterate over <media/>s local media for section in config:gmatch('<media .-</media>') do if section:find('service="' .. fmt_id_lookup[format] .. '"') then media = section break end end if not media then error("Couldn't parse the config") end self.url = {} for connection in media:gmatch('<connection .-/>') do local params, complete_uri = {}, '' for _,param in pairs{'supplier', 'server', 'application', 'identifier', 'authString'} do _,_,params[param] = connection:find(param .. '="(.-)"') end -- in 'application', mp has a value containing one or more entries separated by strings. -- We only keep the first entry. params.application = params.application:gsub("&mp=([^,&]+),?.-&", "&mp=%1&")) if params.supplier == 'akamai' then process_akamai(params) end if (params.supplier == 'limelight' or params.supplier == 'level3') then process_limelight_level3(params) end params.uri = params.uri or error('Could not create RTMP URL') complete_uri = params.uri .. ' app=' .. params.application .. ' playpath=' .. params.identifier .. ' swfUrl=http://www.bbc.co.uk/emp/revisions/18269_21576_10player.swf?revision=18269_21576 swfVfy=1' if params.tcurl then complete_uri = complete_uri .. ' tcUrl=' .. params.tcurl end self.url[#(self.url) + 1] = complete_uri end return self end
-- quvi -- Copyright (C) 2010 quvi project -- -- This file is part of quvi <http://quvi.googlecode.com/>. -- -- 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 -- Obtained with grep -oP '(?<=service=")[^"]+(?=")' on config local fmt_id_lookup = { high = 'iplayer_streaming_h264_flv_high', standard = 'iplayer_streaming_h264_flv', low = 'iplayer_streaming_h264_flv_lo', vlow = 'iplayer_streaming_h264_flv_vlo' -- iplayer_streaming_n95_3g -- iplayer_streaming_n95_wifi } -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "www.bbc.co.uk" r.formats = "default|best" for k,_ in pairs(fmt_id_lookup) do r.formats = r.formats .."|".. k end r.categories = C.proto_rtmp local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/iplayer/"}) return r end -- Parse video URL. function parse(self) function create_uri_for_limelight_level3_iplayertok(params) params.uri = 'rtmp://' .. params.server .. ':1935/ondemand?_fcs_vhost=' .. params.server .. '&auth=' .. params.authString .. '&aifp=v001&slist=' .. params.identifier end function process_akamai(params) params.application = params.application or 'ondemand' params.application = params.application .. '?_fcs_vhost=' .. params.server .. '&undefined' params.uri = 'rtmp://' .. params.server .. ':1935/' .. params.application if not params.authString:find("&aifp=") then params.authString = params.authString .. '&aifp=v001' end if not params.authString:find("&slist=") then params.identifier = params.identifier:gsub('^mp[34]:', '') params.authString = params.authString .. '&slist=' .. params.identifier end params.identifier = params.identifier .. '?' .. params.authString params.uri = params.uri .. '&' .. params.authString params.application = params.application .. '&' .. params.authString params.tcurl = 'rtmp://' .. params.server .. ':80/' .. params.application end function process_limelight_level3(params) create_uri_for_limelight_level3_iplayertok(params) params.application = params.application .. '&' .. params.authString params.tcurl = 'rtmp://' .. params.server .. ':1935/' .. params.application end function process_iplayertok(params) create_uri_for_limelight_level3_iplayertok(params) params.identifier = params.identifier .. '?' .. params.authString params.identifier = params.identifier:gsub('^mp[34]:', '') params.tcurl = 'rtmp://' .. params.server .. ':1935/' .. params.application end self.host_id = 'bbc' local _,_,s = self.page_url:find('episode/(.-)/') local episode_id = s or error('no match: episode id') self.id = episode_id local playlist_uri = 'http://www.bbc.co.uk/iplayer/playlist/' .. episode_id local playlist = quvi.fetch(playlist_uri, {fetch_type = 'playlist'}) local pl_item_p,_,s = playlist:find('<item kind="programme".-identifier="(.-)"') local media_id = s or error('no match: media id') local _,_,s = playlist:find('duration="(%d+)"', pl_item_p) self.duration = tonumber(s) or 0 local _,_,s = playlist:find('<title>(.-)</title>') self.title = s or error('no match: video title') local _,_,s = playlist:find('<link rel="holding" href="(.-)"') self.media_thumbnail_url = s or "" -- stolen from http://lua-users.org/wiki/MathLibraryTutorial math.randomseed(os.time()) math.random() math.random() math.random() local config_uri = 'http://www.bbc.co.uk/mediaselector/4/mtis/stream/' .. media_id .. "?cb=" .. math.random(10000) local config = quvi.fetch(config_uri, {fetch_type = 'config'}) available_formats = {} for fmt_id in config:gmatch("iplayer_streaming_[%w_]+") do available_formats[fmt_id] = true end -- Create the list of acceptable formats, ordered by preference local r = self.requested_format local preferred = ((r == 'best') and {'high', 'standard', 'low', 'vlow'}) or ((r == 'default') and {'standard', 'low', 'vlow', 'high'}) or {r} -- Pick the first acceptable format available local format for _, cur_format in ipairs(preferred) do if available_formats[fmt_id_lookup[cur_format]] then format = cur_format break end end if not format then error('format not available') end -- Iterate over <media/>s local media for section in config:gmatch('<media .-</media>') do if section:find('service="' .. fmt_id_lookup[format] .. '"') then media = section break end end if not media then error("Couldn't parse the config") end self.url = {} for connection in media:gmatch('<connection .-/>') do local params, complete_uri = {}, '' for _,param in pairs{'supplier', 'server', 'application', 'identifier', 'authString'} do _,_,params[param] = connection:find(param .. '="(.-)"') end -- in 'application', mp has a value containing one or more entries separated by strings. -- We only keep the first entry. if params.application then params.application = params.application:gsub("&mp=([^,&]+),?.-&", "&mp=%1&") end if params.supplier == 'akamai' then process_akamai(params) end if (params.supplier == 'limelight' or params.supplier == 'level3') then process_limelight_level3(params) end params.uri = params.uri or error('Could not create RTMP URL') complete_uri = params.uri .. ' app=' .. params.application .. ' playpath=' .. params.identifier .. ' swfUrl=http://www.bbc.co.uk/emp/revisions/18269_21576_10player.swf?revision=18269_21576 swfVfy=1' if params.tcurl then complete_uri = complete_uri .. ' tcUrl=' .. params.tcurl end self.url[#(self.url) + 1] = complete_uri end return self end
bbc.lua: Only modify the application string if we have one
bbc.lua: Only modify the application string if we have one And fix extraneous closing bracket.
Lua
lgpl-2.1
hadess/libquvi-scripts-iplayer,hadess/libquvi-scripts-iplayer
3e6a5d49c2d0ca60653ffdae949b41987b30b8d6
SpatialConvolution.lua
SpatialConvolution.lua
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padding = padding or 0 self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() self.padding = self.padding or 0 if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padding = padding or 0 self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() self.padding = self.padding or 0 if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end function SpatialConvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end
fixing typing in SpatialConvolution
fixing typing in SpatialConvolution
Lua
bsd-3-clause
sagarwaghmare69/nn,douwekiela/nn,witgo/nn,fmassa/nn,Jeffyrao/nn,zchengquan/nn,lvdmaaten/nn,hery/nn,bartvm/nn,GregSatre/nn,PierrotLC/nn,noa/nn,lukasc-ch/nn,jonathantompson/nn,PraveerSINGH/nn,mys007/nn,rotmanmi/nn,andreaskoepf/nn,karpathy/nn,colesbury/nn,Djabbz/nn,boknilev/nn,abeschneider/nn,Moodstocks/nn,eriche2016/nn,adamlerer/nn,kmul00/nn,sbodenstein/nn,nicholas-leonard/nn,forty-2/nn,clementfarabet/nn,ivendrov/nn,szagoruyko/nn,elbamos/nn,diz-vara/nn,zhangxiangxiao/nn,vgire/nn,Aysegul/nn,aaiijmrtt/nn,LinusU/nn,joeyhng/nn,davidBelanger/nn,caldweln/nn,xianjiec/nn,ominux/nn,jhjin/nn,jzbontar/nn,apaszke/nn,mlosch/nn,EnjoyHacking/nn,eulerreich/nn,hughperkins/nn
1af184763249882bbf4cbb56c144abecf68b63e6
premake4.lua
premake4.lua
if os.get() == "windows" then _ACTION = _ACTION or "vs2010" elseif os.get() == "linux"then _ACTION = _ACTION or "gmake" end newoption { trigger = "clincdir", value = "PATH", description = "Set path to a directory that contains CL/cl.h" } newoption { trigger = "cllibdir", value = "PATH", description = "Set path to a directory that contains OpenCL.lib or libOpenCL.so" } newoption { trigger = "cllib64dir", value = "PATH", description = "Set path to a directory that contains OpenCL.lib or libOpenCL.so for x86_64 architecture" } newoption { trigger = "opencl12", value = "no", description = "Enables OpenCL 1.2 features" } _OPTIONS["opencl12"] = _OPTIONS["opencl12"] or "no" -- Default paths on windows for AMD APP SDK if os.get() == "windows" then _OPTIONS["clincdir"] = _OPTIONS["clincdir"] or os.getenv("AMDAPPSDKROOT") .. "include" _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or os.getenv("AMDAPPSDKROOT") .. "lib/x86" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or os.getenv("AMDAPPSDKROOT") .. "lib/x86_64" elseif os.get() == "linux" then _OPTIONS["clincdir"] = _OPTIONS["clincdir"] or "usr/include" if os.is64bit ~= nil and os.is64bit() == false then _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or "usr/lib" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or "usr/lib64" else -- assume it's 64-bit _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or "usr/lib32" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or "usr/lib" end end -- Common settings per project local function configureProject() configuration "Debug or DebugLib" targetsuffix "_d" defines { "DEBUG", "_DEBUG", } flags { "Symbols", "ExtraWarnings" } configuration "Release or ReleaseLib" defines "NDEBUG" flags { "OptimizeSpeed", "NoEditAndContinue", "NoFramePointer", "ExtraWarnings" } configuration { "linux", "gmake" } buildoptions "-std=c++11" links "stdc++" end solution "clw" configurations { "Debug", "Release", "DebugLib", "ReleaseLib" } platforms { "x32", "x64" } -- Available in premake4.4 if vpaths ~= nil then vpaths { ["Header Files"] = { "**.h" }, ["Source Files"] = { "**.cpp" } } end -- -- Library itself -- project "clw" language "C++" location "proj" objdir "obj" includedirs { _OPTIONS["clincdir"] } files { "clw/*.cpp", "clw/*.h" } defines { -- needed in AMD's OpenCL headers to enable still used functions (such as clCreateImage2D) "CL_USE_DEPRECATED_OPENCL_1_1_APIS", "HAVE_OPENCL_1_1" } if _OPTIONS["opencl12"] == "yes" then defines "HAVE_OPENCL_1_2" end -- linker settings for different architectures configuration "x32" libdirs { _OPTIONS["cllibdir"] } configuration "x64" libdirs { _OPTIONS["cllib64dir"] } -- donfiguration for static builds configuration "DebugLib or ReleaseLib" kind "StaticLib" defines "CLW_STATIC_LIB" -- configuration for dll builds configuration "Debug or Release" kind "SharedLib" defines "CLW_BUILD_SHARED" links "OpenCL" -- output directory for different builds and architectures configuration { "DebugLib or ReleaseLib", "x32" } targetdir "lib" configuration { "DebugLib or ReleaseLib", "x64" } targetdir "lib64" configuration { "Debug or Release", "x32" } targetdir "bin" configuration { "Debug or Release", "x64" } targetdir "bin64" configureProject() -- copy CL directory configuration "windows" postbuildcommands { [[xcopy "]] .. _OPTIONS["clincdir"] .. [[" ..\ /S /Y]] } -- TODO: linux -- -- Simple tool to query basic platform and its devices attributes -- project "clwinfo" language "C++" location "proj" kind "ConsoleApp" objdir "obj" files "clwinfo/main.cpp" includedirs { ".", _OPTIONS["clincdir"] } defines "HAVE_OPENCL_1_1" if _OPTIONS["opencl12"] == "yes" then defines "HAVE_OPENCL_1_2" end links "clw" configuration "x32" targetdir "bin" configuration "x64" targetdir "bin64" configuration "DebugLib or ReleaseLib" defines "CLW_STATIC_LIB" -- need to explicitly link OpenCL links "OpenCL" configuration "x32" libdirs { _OPTIONS["cllibdir"] } configuration "x64" libdirs { _OPTIONS["cllib64dir"] } configureProject() configuration "linux" linkoptions "-Wl,--rpath=."
if os.get() == "windows" then _ACTION = _ACTION or "vs2010" elseif os.get() == "linux"then _ACTION = _ACTION or "gmake" end newoption { trigger = "clincdir", value = "PATH", description = "Set path to a directory that contains CL/cl.h" } newoption { trigger = "cllibdir", value = "PATH", description = "Set path to a directory that contains OpenCL.lib or libOpenCL.so" } newoption { trigger = "cllib64dir", value = "PATH", description = "Set path to a directory that contains OpenCL.lib or libOpenCL.so for x86_64 architecture" } newoption { trigger = "opencl12", value = "no", description = "Enables OpenCL 1.2 features" } _OPTIONS["opencl12"] = _OPTIONS["opencl12"] or "no" -- Default paths on windows for AMD APP SDK if os.get() == "windows" then _OPTIONS["clincdir"] = _OPTIONS["clincdir"] or os.getenv("AMDAPPSDKROOT") .. "include" _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or os.getenv("AMDAPPSDKROOT") .. "lib/x86" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or os.getenv("AMDAPPSDKROOT") .. "lib/x86_64" elseif os.get() == "linux" then _OPTIONS["clincdir"] = _OPTIONS["clincdir"] or "/usr/include" if os.is64bit ~= nil and os.is64bit() == false then _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or "/usr/lib" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or "/usr/lib64" else -- assume it's 64-bit _OPTIONS["cllibdir"] = _OPTIONS["cllibdir"] or "/usr/lib32" _OPTIONS["cllib64dir"] = _OPTIONS["cllib64dir"] or "/usr/lib" end end -- Common settings per project local function configureProject() configuration "Debug or DebugLib" targetsuffix "_d" defines { "DEBUG", "_DEBUG", } flags { "Symbols", "ExtraWarnings" } configuration "Release or ReleaseLib" defines "NDEBUG" flags { "OptimizeSpeed", "NoEditAndContinue", "NoFramePointer", "ExtraWarnings" } configuration { "linux", "gmake" } buildoptions "-std=c++11" links "stdc++" end solution "clw" configurations { "Debug", "Release", "DebugLib", "ReleaseLib" } platforms { "x32", "x64" } -- Available in premake4.4 if vpaths ~= nil then vpaths { ["Header Files"] = { "**.h" }, ["Source Files"] = { "**.cpp" } } end -- -- Library itself -- project "clw" language "C++" location "proj" objdir "obj" includedirs { _OPTIONS["clincdir"] } files { "clw/*.cpp", "clw/*.h" } defines { -- needed in AMD's OpenCL headers to enable still used functions (such as clCreateImage2D) "CL_USE_DEPRECATED_OPENCL_1_1_APIS", "HAVE_OPENCL_1_1" } if _OPTIONS["opencl12"] == "yes" then defines "HAVE_OPENCL_1_2" end -- linker settings for different architectures configuration "x32" libdirs { _OPTIONS["cllibdir"] } configuration "x64" libdirs { _OPTIONS["cllib64dir"] } -- donfiguration for static builds configuration "DebugLib or ReleaseLib" kind "StaticLib" defines "CLW_STATIC_LIB" -- configuration for dll builds configuration "Debug or Release" kind "SharedLib" defines "CLW_BUILD_SHARED" links "OpenCL" -- output directory for different builds and architectures configuration { "DebugLib or ReleaseLib", "x32" } targetdir "lib" configuration { "DebugLib or ReleaseLib", "x64" } targetdir "lib64" configuration { "Debug or Release", "x32" } targetdir "bin" configuration { "Debug or Release", "x64" } targetdir "bin64" configureProject() -- copy CL directory configuration "windows" postbuildcommands { [[xcopy "]] .. _OPTIONS["clincdir"] .. [[\CL" ..\CL /S /Y /I]] } configuration "linux" postbuildcommands { [[cp -R "]] .. _OPTIONS["clincdir"] .. [[/CL" ../]] } -- -- Simple tool to query basic platform and its devices attributes -- project "clwinfo" language "C++" location "proj" kind "ConsoleApp" objdir "obj" files "clwinfo/main.cpp" includedirs { ".", _OPTIONS["clincdir"] } defines "HAVE_OPENCL_1_1" if _OPTIONS["opencl12"] == "yes" then defines "HAVE_OPENCL_1_2" end links "clw" configuration "x32" targetdir "bin" configuration "x64" targetdir "bin64" configuration "DebugLib or ReleaseLib" defines "CLW_STATIC_LIB" -- need to explicitly link OpenCL links "OpenCL" configuration "x32" libdirs { _OPTIONS["cllibdir"] } configuration "x64" libdirs { _OPTIONS["cllib64dir"] } configureProject() configuration "linux" linkoptions "-Wl,--rpath=." links "OpenCL"
fixed project file for linux build
fixed project file for linux build
Lua
mit
k0zmo/clw,k0zmo/clw
1b5683e842ec68eebc2e1a18b94da8655a457d38
prosody/mod_auth_wordpress.lua
prosody/mod_auth_wordpress.lua
-- Prosody Wordpress Authentication local datamanager = require "util.datamanager"; local md5 = require "md5"; local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local log = require "util.logger".init("auth_wordpress"); local db = require 'luasql.mysql' local hosts = hosts; local mysql_server = module:get_option("wordpress_mysql_host") or "localhost"; local mysql_port = module:get_option("wordpress_mysql_port") or 3306; local mysql_database = module:get_option("wordpress_mysql_database") or "wordpress"; local mysql_username = module:get_option("wordpress_mysql_username") or "root"; local mysql_password = module:get_option("wordpress_mysql_password") or ""; local mysql_prefix = module:get_option("wordpress_mysql_prefix") or "wp_"; local env = assert(db.mysql()) function new_wordpress_provider(host) local provider = { name = "wordpress" }; log("debug", "initializing wordpress authentication provider for host '%s'", host); function provider.test_password(username, password) local pass = false; local query = string.format("select user_pass from %susers where `user_login` = '%s'", mysql_prefix, username); local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port)); local cursor = assert (connection:execute (query)); if cursor:numrows() > 0 then user_pass = cursor:fetch(); md5_pass = md5.sumhexa(password) pass = md5_pass == user_pass; end cursor:close(); connection:close(); if pass then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Password unavailable for Wordpress."; end function provider.set_password(username, password) return nil, "Password unavailable for Wordpress."; end function provider.create_user(username, password) return nil, "Account creation/modification not available with Wordpress."; end function provider.user_exists(username) log("debug", "Exists %s", username); local pass = false; local query = string.format("select id from %susers where `user_login` = '%s'", mysql_prefix, username); local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port)); local cursor = assert (connection:execute (query)); if cursor:numrows() > 0 then pass = true; end cursor:close(); connection:close(); if not pass then log("debug", "Account not found for username '%s' at host '%s'", username, module.host); return nil, "Auth failed. Invalid username"; end return true; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local realm = module:get_option("sasl_realm") or module.host; local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return provider.test_password(prepped_username, password), true; end }; return new_sasl(realm, testpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_wordpress_provider(module.host));
-- Prosody Wordpress Authentication local datamanager = require "util.datamanager"; local base64 = require "util.encodings".base64; local md5 = require "util.hashes".md5; local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local log = require "util.logger".init("auth_wordpress"); local db = require 'luasql.mysql' local hosts = hosts; local mysql_server = module:get_option("wordpress_mysql_host") or "localhost"; local mysql_port = module:get_option("wordpress_mysql_port") or 3306; local mysql_database = module:get_option("wordpress_mysql_database") or "wordpress"; local mysql_username = module:get_option("wordpress_mysql_username") or "root"; local mysql_password = module:get_option("wordpress_mysql_password") or ""; local mysql_prefix = module:get_option("wordpress_mysql_prefix") or "wp_"; local env = assert(db.mysql()) function new_wordpress_provider(host) local provider = { name = "wordpress" }; log("debug", "initializing wordpress authentication provider for host '%s'", host); function provider.test_password(username, password) local pass = false; local query = string.format("select user_pass from %susers where `user_login` = '%s'", mysql_prefix, username); local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port)); local cursor = assert (connection:execute (query)); if cursor:numrows() > 0 then user_pass = cursor:fetch(); md5_pass = md5(password, true); pass = md5_pass == user_pass; end cursor:close(); connection:close(); if pass then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Password unavailable for Wordpress."; end function provider.set_password(username, password) return nil, "Password unavailable for Wordpress."; end function provider.create_user(username, password) return nil, "Account creation/modification not available with Wordpress."; end function provider.user_exists(username) log("debug", "Exists %s", username); local pass = false; local query = string.format("select id from %susers where `user_login` = '%s'", mysql_prefix, username); local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port)); local cursor = assert (connection:execute (query)); if cursor:numrows() > 0 then pass = true; end cursor:close(); connection:close(); if not pass then log("debug", "Account not found for username '%s' at host '%s'", username, module.host); return nil, "Auth failed. Invalid username"; end return true; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local realm = module:get_option("sasl_realm") or module.host; local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return provider.test_password(prepped_username, password), true; end }; return new_sasl(realm, testpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_wordpress_provider(module.host));
Change md5 header to use internal prosody library. fix #5
Change md5 header to use internal prosody library. fix #5
Lua
mit
llun/wordpress-authenticator
2cb4d5386aa3a60314a2f7d0a66495eb58770cbf
home/.config/nvim/lua/plugin-config/lsp.lua
home/.config/nvim/lua/plugin-config/lsp.lua
local servers = { -------------- -- Languages "html", "jsonls", "yamlls", "cssls", "sumneko_lua", "tsserver", "bashls", -- "elixirls", -- "rust_analyzer", -- "fsautocomplete", -------------- -- Frameworks "ember", "glint", -------------- -- Tools "graphql", "tailwindcss", "graphql", "dockerls", -------------- -- Linting "eslint", } --------------------------- -- Settings and other available servers -- https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md --------------------------- local mySettings = { tsserver = { format = { enable = false }, }, eslint = { format = { enable = true }, lintTask = { enable = true }, codeAction = { showDocumentation = true } }, sumneko_lua = { Lua = { diagnostics = { globals = { 'vim' }, }, workspace = { -- Make the server aware of Neovim runtime files library = vim.api.nvim_get_runtime_file("", true), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, } } } require("nvim-lsp-installer").setup { ensure_installed = servers, automatic_installation = true, ui = { icons = { server_installed = "✓", server_pending = "➜", server_uninstalled = "✗" } } } local cmp = require'cmp' -- https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#menu-type -- for later ^ cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) require('luasnip').lsp_expand(args.body) end, }, window = { -- completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered(), }, mapping = cmp.mapping.preset.insert({ -- Scroll up in docs ['<C-k>'] = cmp.mapping.scroll_docs(-4), -- Scroll down in docs ['<C-j>'] = cmp.mapping.scroll_docs(4), -- Same as the escape key ['<C-e>'] = cmp.mapping.abort(), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Selects next item in completion menu ['<Tab>'] = function(fallback) if cmp.visible() then cmp.select_next_item() else fallback() end end, -- Selects previous item in completion menu ['<S-Tab>'] = function(fallback) if cmp.visible() then cmp.select_prev_item() else fallback() end end }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' }, }, { { name = 'buffer' }, }) }) -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) local lsp = require('lspconfig') for _, serverName in ipairs(servers) do local server = lsp[serverName] if server then server.setup({ capabilities = capabilities, settings = mySettings[serverName], on_attach = function(client, bufnr) -- Helpers, Utilities, etc. (lua -> vim apis are verbose) local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end local function n(line) vim.cmd([[nnoremap ]] .. line) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Global keymaps (no-remap by default, cause... sanity) n([[gD :lua vim.lsp.buf.declaration()<CR>]]) n([[gd :lua vim.lsp.buf.definition()<CR>]]) n([[gi :lua vim.lsp.buf.implementation()<CR>]]) n([[gt :lua vim.lsp.buf.type_definition()<CR>]]) n([[gr :lua vim.lsp.buf.references()<CR>]]) n([[<leader>ff :lua vim.lsp.buf.format({ async = true })<CR>]]) n([[<leader><Space> :lua vim.lsp.buf.hover()<CR>]]) n([[<leader>a :lua vim.lsp.buf.code_action()<CR>]]) n([[<leader>rn :lua vim.lsp.buf.rename()<CR>]]) -- Server-specific things to do if serverName == 'eslint' then n([[<leader>ff :EslintFixAll<CR>]]) end -- Show line diagnostics automatically in hover window vim.api.nvim_create_autocmd("CursorHold", { buffer = bufnr, callback = function() local opts = { focusable = false, close_events = { "BufLeave", "CursorMoved", "InsertEnter", "FocusLost" }, border = 'rounded', source = 'always', prefix = ' ', scope = 'cursor', } vim.diagnostic.open_float(nil, opts) end }) end }) end end vim.diagnostic.config({ virtual_text = { prefix = '➢', -- Could be '●', '▎', 'x' source = 'always' } }) -- Change diagnostic symbols in the sign column (gutter) -- https://github.com/neovim/nvim-lspconfig/wiki/UI-Customization#change-diagnostic-symbols-in-the-sign-column-gutter local signs = { Error = " ", Warn = " ", Hint = " ", Info = " " } for type, icon in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = hl }) end vim.diagnostic.config({ -- virtual text makes things pretty claustrophobic -- would be great to only turn on/off for certain diagnostics providers tho virtual_text = false, signs = true, underline = true, update_in_insert = false, severity_sort = false, })
local servers = { -------------- -- Languages "html", "jsonls", "yamlls", "cssls", "sumneko_lua", "tsserver", "bashls", -- "elixirls", -- "rust_analyzer", -- "fsautocomplete", -------------- -- Frameworks "ember", "glint", -------------- -- Tools "graphql", "tailwindcss", "graphql", "dockerls", -------------- -- Linting "eslint", } --------------------------- -- Settings and other available servers -- https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md --------------------------- local mySettings = { eslint = { format = true, }, sumneko_lua = { Lua = { diagnostics = { globals = { 'vim' }, }, workspace = { -- Make the server aware of Neovim runtime files library = vim.api.nvim_get_runtime_file("", true), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, } } } require("nvim-lsp-installer").setup { ensure_installed = servers, automatic_installation = true, ui = { icons = { server_installed = "✓", server_pending = "➜", server_uninstalled = "✗" } } } local cmp = require'cmp' -- https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#menu-type -- for later ^ cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) require('luasnip').lsp_expand(args.body) end, }, window = { -- completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered(), }, mapping = cmp.mapping.preset.insert({ -- Scroll up in docs ['<C-k>'] = cmp.mapping.scroll_docs(-4), -- Scroll down in docs ['<C-j>'] = cmp.mapping.scroll_docs(4), -- Same as the escape key ['<C-e>'] = cmp.mapping.abort(), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Selects next item in completion menu ['<Tab>'] = function(fallback) if cmp.visible() then cmp.select_next_item() else fallback() end end, -- Selects previous item in completion menu ['<S-Tab>'] = function(fallback) if cmp.visible() then cmp.select_prev_item() else fallback() end end }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' }, }, { { name = 'buffer' }, }) }) -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) local lsp = require('lspconfig') for _, serverName in ipairs(servers) do local server = lsp[serverName] if server then server.setup({ capabilities = capabilities, settings = mySettings[serverName], on_attach = function(client, bufnr) -- Helpers, Utilities, etc. (lua -> vim apis are verbose) local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end local function n(line) vim.cmd([[nnoremap ]] .. line) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Global keymaps (no-remap by default, cause... sanity) n([[gD :lua vim.lsp.buf.declaration()<CR>]]) n([[gd :lua vim.lsp.buf.definition()<CR>]]) n([[gi :lua vim.lsp.buf.implementation()<CR>]]) n([[gt :lua vim.lsp.buf.type_definition()<CR>]]) n([[gr :lua vim.lsp.buf.references()<CR>]]) -- n([[<leader>ff :lua vim.lsp.buf.format({ async = true })<CR>]]) n([[<leader><Space> :lua vim.lsp.buf.hover()<CR>]]) n([[<leader>a :lua vim.lsp.buf.code_action()<CR>]]) n([[<leader>rn :lua vim.lsp.buf.rename()<CR>]]) -- Server-specific things to do if serverName == 'eslint' then n([[<leader>ff :EslintFixAll<CR>]]) end -- Show line diagnostics automatically in hover window vim.api.nvim_create_autocmd("CursorHold", { buffer = bufnr, callback = function() local opts = { focusable = false, close_events = { "BufLeave", "CursorMoved", "InsertEnter", "FocusLost" }, border = 'rounded', source = 'always', prefix = ' ', scope = 'cursor', } vim.diagnostic.open_float(nil, opts) end }) end }) end end vim.diagnostic.config({ virtual_text = { prefix = '➢', -- Could be '●', '▎', 'x' source = 'always' } }) -- Change diagnostic symbols in the sign column (gutter) -- https://github.com/neovim/nvim-lspconfig/wiki/UI-Customization#change-diagnostic-symbols-in-the-sign-column-gutter local signs = { Error = " ", Warn = " ", Hint = " ", Info = " " } for type, icon in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = hl }) end vim.diagnostic.config({ -- virtual text makes things pretty claustrophobic -- would be great to only turn on/off for certain diagnostics providers tho virtual_text = false, signs = true, underline = true, update_in_insert = false, severity_sort = false, })
Fix ESLint formatting
Fix ESLint formatting
Lua
mit
NullVoxPopuli/dotfiles,NullVoxPopuli/dotfiles,NullVoxPopuli/dotfiles
3da68e2665f2c68d4840b526badbd1422723edf6
vanilla/v/dispatcher.lua
vanilla/v/dispatcher.lua
-- vanilla local Controller = require 'vanilla.v.controller' local Request = require 'vanilla.v.request' local Router = require 'vanilla.v.router' local Response = require 'vanilla.v.response' local View = require 'vanilla.v.views.rtpl' local Error = require 'vanilla.v.error' -- perf local error = error local pairs = pairs local pcall = pcall local require = require local setmetatable = setmetatable local function tappend(t, v) t[#t+1] = v end local function new_view(view_conf) return View:new(view_conf) end local function run_route(router_instance) return router_instance:route() end local Dispatcher = {} function Dispatcher:new(application) self.request = Request:new() self.response = Response:new() self.router = Router:new(self.request) local instance = { application = application, plugins = {}, controller_prefix = 'controllers.', error_controller = 'error', error_action = 'error' } setmetatable(instance, {__index = self}) return instance end function Dispatcher:getRequest() return self.request end function Dispatcher:setRequest(request) self.request = request end function Dispatcher:getResponse() return self.response end function Dispatcher:registerPlugin(plugin) if plugin ~= nil then tappend(self.plugins, plugin) end end function Dispatcher:_runPlugins(hook) for _, plugin in ipairs(self.plugins) do if plugin[hook] ~= nil then plugin[hook](plugin, self.request, self.response) end end end function Dispatcher:getRouter() return self.router end function Dispatcher:_route() local ok, controller_name_or_error, action= pcall(run_route, self.router) if ok and controller_name_or_error then self.request.controller_name = controller_name_or_error self.request.action_name = action return true else self:errResponse(controller_name_or_error) end end local function require_controller(controller_prefix, controller_name) return require(controller_prefix .. controller_name) end local function call_controller(Dispatcher, matched_controller, controller_name, action_name) if matched_controller[action_name] == nil then Dispatcher:errResponse({ code = 102, msg = {NoAction = action_name}}) end Dispatcher:initView() local body = matched_controller[action_name](matched_controller) if body ~= nil then return body else Dispatcher:errResponse({ code = 104, msg = {Exec_Err = controller_name .. '/' .. action_name}}) end end function Dispatcher:dispatch() self:_runPlugins('routerStartup') self:_route() self:_runPlugins('routerShutdown') self.controller = Controller:new(self.request, self.response, self.application.config) self.view = self.application:lpcall(new_view, self.application.config.view) self:_runPlugins('dispatchLoopStartup') self:_runPlugins('preDispatch') local matched_controller = self:lpcall(require_controller, self.controller_prefix, self.request.controller_name) setmetatable(matched_controller, { __index = self.controller }) local c_rs = self:lpcall(call_controller, self, matched_controller, self.request.controller_name, self.request.action_name) if type(c_rs) ~= 'string' then self:errResponse({ code = 103, msg = {Rs_Error = self.request.controller_name .. '/' .. self.request.action_name .. ' must return a String.'}}) end self.response.body = c_rs self:_runPlugins('postDispatch') self.response:response() self:_runPlugins('dispatchLoopShutdown') end function Dispatcher:initView(view, controller_name, action_name) if view ~= nil then self.view = view end self.controller:initView(self.view, controller_name, action_name) end function Dispatcher:lpcall( ... ) local ok, rs_or_error = pcall( ... ) if ok then return rs_or_error else self:errResponse(rs_or_error) end end function Dispatcher:errResponse(err) self.response.body = self:raise_error(err) self.response:response() ngx.eof() end function Dispatcher:raise_error(err) local error_controller = require(self.controller_prefix .. self.error_controller) setmetatable(error_controller, { __index = self.controller }) self:initView(self.view, self.error_controller, self.error_action) local error_instance = Error:new(err.code, err.msg) if error_instance ~= false then error_controller.err = error_instance else error_controller.err = Error:new(100, {msg = err}) end self.response:setStatus(error_controller.err.status) return error_controller[self.error_action](error_controller) end function Dispatcher:getApplication() return self.application end function Dispatcher:setView(view) self.view = view end function Dispatcher:returnResponse() return self.response end function Dispatcher:setDefaultAction(default_action) if default_action ~= nil then self.request.action_name = default_action end end function Dispatcher:setDefaultController(default_controller) if default_controller ~= nil then self.request.controller_name = default_controller end end function Dispatcher:setErrorHandler(err_handler) if type(err_handler) == 'table' then if err_handler['controller'] ~= nil then self.error_controller = err_handler['controller'] end if err_handler['action'] ~= nil then self.error_action = err_handler['action'] end return true end return false end return Dispatcher
-- vanilla local Controller = require 'vanilla.v.controller' local Request = require 'vanilla.v.request' local Router = require 'vanilla.v.router' local Response = require 'vanilla.v.response' local View = require 'vanilla.v.views.rtpl' local Error = require 'vanilla.v.error' -- perf local error = error local pairs = pairs local pcall = pcall local require = require local setmetatable = setmetatable local function tappend(t, v) t[#t+1] = v end local function new_view(view_conf) return View:new(view_conf) end local function run_route(router_instance) return router_instance:route() end local Dispatcher = {} function Dispatcher:new(application) self.request = Request:new() self.response = Response:new() self.router = Router:new(self.request) local instance = { application = application, plugins = {}, controller_prefix = 'controllers.', error_controller = 'error', error_action = 'error' } setmetatable(instance, {__index = self}) return instance end function Dispatcher:getRequest() return self.request end function Dispatcher:setRequest(request) self.request = request end function Dispatcher:getResponse() return self.response end function Dispatcher:registerPlugin(plugin) if plugin ~= nil then tappend(self.plugins, plugin) end end function Dispatcher:_runPlugins(hook) for _, plugin in ipairs(self.plugins) do if plugin[hook] ~= nil then plugin[hook](plugin, self.request, self.response) end end end function Dispatcher:getRouter() return self.router end function Dispatcher:_route() local ok, controller_name_or_error, action= pcall(run_route, self.router) if ok and controller_name_or_error then self.request.controller_name = controller_name_or_error self.request.action_name = action return true else self:errResponse(controller_name_or_error) end end local function require_controller(controller_prefix, controller_name) return require(controller_prefix .. controller_name) end local function call_controller(Dispatcher, matched_controller, controller_name, action_name) if matched_controller[action_name] == nil then Dispatcher:errResponse({ code = 102, msg = {NoAction = action_name}}) end Dispatcher:initView() local body = matched_controller[action_name](matched_controller) if body ~= nil then return body else Dispatcher:errResponse({ code = 104, msg = {Exec_Err = controller_name .. '/' .. action_name}}) end end function Dispatcher:dispatch() self:_runPlugins('routerStartup') self:_route() self:_runPlugins('routerShutdown') self.controller = Controller:new(self.request, self.response, self.application.config) self.view = self.application:lpcall(new_view, self.application.config.view) self:_runPlugins('dispatchLoopStartup') self:_runPlugins('preDispatch') local matched_controller = self:lpcall(require_controller, self.controller_prefix, self.request.controller_name) setmetatable(matched_controller, { __index = self.controller }) local c_rs = self:lpcall(call_controller, self, matched_controller, self.request.controller_name, self.request.action_name) if type(c_rs) ~= 'string' then self:errResponse({ code = 103, msg = {Rs_Error = self.request.controller_name .. '/' .. self.request.action_name .. ' must return a String.'}}) end self.response.body = c_rs self:_runPlugins('postDispatch') self.response:response() self:_runPlugins('dispatchLoopShutdown') end function Dispatcher:initView(view, controller_name, action_name) if view ~= nil then self.view = view end self.controller:initView(self.view, controller_name, action_name) end function Dispatcher:lpcall( ... ) local ok, rs_or_error = pcall( ... ) if ok then return rs_or_error else self:errResponse(rs_or_error) end end function Dispatcher:errResponse(err) self.response.body = self:raise_error(err) self.response:response() ngx.eof() end function Dispatcher:raise_error(err) if self.controller == nil then self.controller = Controller:new(self.request, self.response, self.application.config) end if self.view == nil then self.view = self.application:lpcall(new_view, self.application.config.view) end local error_controller = require(self.controller_prefix .. self.error_controller) setmetatable(error_controller, { __index = self.controller }) self:initView(self.view, self.error_controller, self.error_action) local error_instance = Error:new(err.code, err.msg) if error_instance ~= false then error_controller.err = error_instance else error_controller.err = Error:new(100, {msg = err}) end self.response:setStatus(error_controller.err.status) return error_controller[self.error_action](error_controller) end function Dispatcher:getApplication() return self.application end function Dispatcher:setView(view) self.view = view end function Dispatcher:returnResponse() return self.response end function Dispatcher:setDefaultAction(default_action) if default_action ~= nil then self.request.action_name = default_action end end function Dispatcher:setDefaultController(default_controller) if default_controller ~= nil then self.request.controller_name = default_controller end end function Dispatcher:setErrorHandler(err_handler) if type(err_handler) == 'table' then if err_handler['controller'] ~= nil then self.error_controller = err_handler['controller'] end if err_handler['action'] ~= nil then self.error_action = err_handler['action'] end return true end return false end return Dispatcher
fix route err bug
fix route err bug
Lua
mit
idevz/vanilla,lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla,idevz/vanilla
67bd708ae8784eec5018841bf83a9e7c1adfd9df
share/lua/website/videobash.lua
share/lua/website/videobash.lua
-- libquvi-scripts -- Copyright (C) 2011 Thomas Preud'homme <robotux@celest.fr> -- -- 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 = "videobash%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"}) 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 = "videobash" local page = quvi.fetch(self.page_url) local _,_,s = page:find("<title>(.-)%s+-") self.title = s or error ("no match: media title") local _,_,s = page:find("addFavorite%((%d+)") self.id = s or error ("no match: media id") local _,_,s = page:find("video_url=(.-)%?") self.url = {s or error ("no match: flv")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2011 Thomas Preud'homme <robotux@celest.fr> -- -- 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 = "videobash%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"}) 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 = "videobash" local page = quvi.fetch(self.page_url) local _,_,s = page:find("<title>(.-)%s+-") self.title = s or error ("no match: media title") local _,_,s = page:find("addFavorite%((%d+)") self.id = s or error ("no match: media id") local s = page:match('video_url="(.-);') or error("no match: media url") s = s:gsub("['%s+]",'') self.url = {s} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: videobash.lua: media URL parsing (#81)
FIX: videobash.lua: media URL parsing (#81) * http://sourceforge.net/apps/trac/quvi/ticket/81
Lua
agpl-3.0
legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
324d9f945b7cb1840fb8c958b5a30405a29861c8
scen_edit/view/file_panel.lua
scen_edit/view/file_panel.lua
--//============================================================================= FilePanel = LayoutPanel:Inherit{ -- so, this should be changed here as well -- (see unitdefsview.lua) classname = "imagelistview", autosize = true, autoArrangeH = false, autoArrangeV = false, centerItems = false, iconX = 64, iconY = 64, itemMargin = {1, 1, 1, 1}, selectable = true, multiSelect = true, items = {}, extFilters = {'.sdz'}, imageFile = SCEN_EDIT_IMG_DIR .. "file.png", dir = '', drawcontrolv2 = true, columns = 5, } local this = FilePanel local inherited = this.inherited --//============================================================================= --//============================================================================= function FilePanel:New(obj) if not obj.dir then obj.dir = FilePanel.lastDir end obj = inherited.New(self,obj) obj:SetDir(obj.dir) return obj end --//============================================================================= local function GetParentDir(dir) dir = dir:gsub("\\", "/") local lastChar = dir:sub(-1) if (lastChar == "/") then dir = dir:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = dir:find("/",init,true) until (not b) if (n==1) then return '' else return dir:sub(1,pos) end end local function ExtractFileName(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(pos+1) end end local function ExtractDir(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(1,pos) end end --//============================================================================= function FilePanel:_AddFile(name,imageFile) self:AddChild( LayoutPanel:New{ width = self.iconX+10, height = self.iconY+20, padding = {0,0,0,0}, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, rows = 2, columns = 1, children = { Image:New{ width = self.iconX, height = self.iconY, passive = true, file = ':clr' .. self.iconX .. ',' .. self.iconY .. ':' .. imageFile, }, Label:New{ width = self.iconX+10, height = 20, align = 'center', autosize = false, caption = name, }, }, }) end function FilePanel:ScanDir() local files = VFS.DirList(self.dir, "*", VFS.RAW_ONLY) local dirs = VFS.SubDirs("", "*", VFS.RAW_ONLY) local imageFiles = {} for i=1,#files do local f = files[i] local ext = (f:GetExt() or ""):lower() if (table.ifind(self.extFilters,ext))then imageFiles[#imageFiles+1]=f end end self._dirsNum = #dirs self._dirList = dirs local n = 1 local items = self.items --FIXME: loading from complex paths is broken, uncomment this when they get fixed --items[n] = '..' --n = n+1 for i=1,#dirs do --FIXME: loading from complex paths is broken, uncomment this when they get fixed --items[n],n=dirs[i],n+1 end for i=1,#imageFiles do items[n],n=imageFiles[i],n+1 end if (#items>n-1) then for i=n,#items do items[i] = nil end end self:DisableRealign() --// clear old for i=#self.children,1,-1 do self:RemoveChild(self.children[i]) end --// add ".." --FIXME: loading from complex paths is broken, uncomment this when they get fixed --self:_AddFile('..',self.imageFolderUp) --// add dirs at top for i=1,#dirs do --FIXME: loading from complex paths is broken, uncomment this when they get fixed --self:_AddFile(ExtractFileName(dirs[i]),self.imageFolder) end --// add files for i=1,#imageFiles do self:_AddFile(ExtractFileName(imageFiles[i]),self.imageFile) end self:EnableRealign() end function FilePanel:SetDir(directory) self:DeselectAll() self.dir = directory FilePanel.lastDir = self.dir self:ScanDir() if (self.parent) then self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end function FilePanel:GotoFile(filepath) local dir = ExtractDir(filepath) local file = ExtractFileName(filepath) self.dir = dir self:ScanDir() self:Select(file) if (self.parent) then if (self.parent.classname == "scrollpanel") then local x,y,w,h = self:GetItemXY(next(self.selectedItems)) self.parent:SetScrollPos(x+w*0.5, y+h*0.5, true) end self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end --//============================================================================= function FilePanel:Select(item) if (type(item)=="number") then self:SelectItem(item) else local items = self.items for i=1,#items do if (ExtractFileName(items[i])==item) then self:SelectItem(i) return end end self:SelectItem(1) end end --//============================================================================= function FilePanel:DrawItemBkGnd(index) local cell = self._cells[index] local itemPadding = self.itemPadding if (self.selectedItems[index]) then self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"selected") else self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"normal") end end --//============================================================================= function FilePanel:HitTest(x,y) local cx,cy = self:LocalToClient(x,y) local obj = inherited.HitTest(self,cx,cy) if (obj) then return obj end local itemIdx = self:GetItemIndexAt(cx,cy) return (itemIdx>=0) and self end function FilePanel:MouseDblClick(x,y) local cx,cy = self:LocalToClient(x,y) local itemIdx = self:GetItemIndexAt(cx,cy) if (itemIdx<0) then return end if (itemIdx==1) then self:SetDir(GetParentDir(self.dir)) return self end --FIXME: loading from complex paths is broken, change this when they get fixed if false and (itemIdx<=self._dirsNum+1) then self:SetDir(self._dirList[itemIdx-1]) return self else self:CallListeners(self.OnDblClickItem, self.items[itemIdx], itemIdx) return self end end --//=============================================================================
--//============================================================================= FilePanel = LayoutPanel:Inherit{ -- so, this should be changed here as well -- (see unitdefsview.lua) classname = "imagelistview", autosize = true, autoArrangeH = false, autoArrangeV = false, centerItems = false, iconX = 64, iconY = 64, itemMargin = {1, 1, 1, 1}, selectable = true, multiSelect = true, items = {}, extFilters = {'.sdz'}, imageFile = SCEN_EDIT_IMG_DIR .. "file.png", dir = '', drawcontrolv2 = true, columns = 5, } local this = FilePanel local inherited = this.inherited --//============================================================================= --//============================================================================= function FilePanel:New(obj) if not obj.dir then obj.dir = FilePanel.lastDir end obj = inherited.New(self,obj) obj:SetDir(obj.dir) return obj end --//============================================================================= local function GetParentDir(dir) dir = dir:gsub("\\", "/") local lastChar = dir:sub(-1) if (lastChar == "/") then dir = dir:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = dir:find("/",init,true) until (not b) if (n==1) then return '' else return dir:sub(1,pos) end end local function ExtractFileName(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(pos+1) end end local function ExtractDir(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(1,pos) end end --//============================================================================= function FilePanel:_AddFile(name,imageFile) self:AddChild( LayoutPanel:New{ width = self.iconX+10, height = self.iconY+20, padding = {0,0,0,0}, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, rows = 2, columns = 1, children = { Image:New{ width = self.iconX, height = self.iconY, passive = true, file = ':clr' .. self.iconX .. ',' .. self.iconY .. ':' .. imageFile, }, Label:New{ width = self.iconX+10, height = 20, align = 'center', autosize = false, caption = name, }, }, }) end function FilePanel:ScanDir() local files = VFS.DirList(self.dir, "*", VFS.RAW_ONLY) local dirs = VFS.SubDirs("", "*", VFS.RAW_ONLY) local imageFiles = {} for i=1,#files do local f = files[i] local ext = (f:GetExt() or ""):lower() if (table.ifind(self.extFilters,ext))then imageFiles[#imageFiles+1]=f end end self._dirsNum = #dirs self._dirList = dirs local n = 1 local items = self.items --FIXME: loading from complex paths is broken, uncomment this when they get fixed --items[n] = '..' --n = n+1 for i=1,#dirs do --FIXME: loading from complex paths is broken, uncomment this when they get fixed --items[n],n=dirs[i],n+1 end for i=1,#imageFiles do items[n],n=imageFiles[i],n+1 end if (#items>n-1) then for i=n,#items do items[i] = nil end end self:DisableRealign() --// clear old for i=#self.children,1,-1 do self:RemoveChild(self.children[i]) end --// add ".." --FIXME: loading from complex paths is broken, uncomment this when they get fixed --self:_AddFile('..',self.imageFolderUp) --// add dirs at top for i=1,#dirs do --FIXME: loading from complex paths is broken, uncomment this when they get fixed --self:_AddFile(ExtractFileName(dirs[i]),self.imageFolder) end --// add files for i=1,#imageFiles do self:_AddFile(ExtractFileName(imageFiles[i]),self.imageFile) end self:EnableRealign() end function FilePanel:SetDir(directory) self:DeselectAll() self.dir = directory FilePanel.lastDir = self.dir self:ScanDir() if (self.parent) then self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end function FilePanel:GotoFile(filepath) local dir = ExtractDir(filepath) local file = ExtractFileName(filepath) self.dir = dir self:ScanDir() self:Select(file) if (self.parent) then if (self.parent.classname == "scrollpanel") then local x,y,w,h = self:GetItemXY(next(self.selectedItems)) self.parent:SetScrollPos(x+w*0.5, y+h*0.5, true) end self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end --//============================================================================= function FilePanel:Select(item) if (type(item)=="number") then self:SelectItem(item) else local items = self.items for i=1,#items do if (ExtractFileName(items[i])==item) then self:SelectItem(i) return end end self:SelectItem(1) end end --//============================================================================= function FilePanel:DrawItemBkGnd(index) local cell = self._cells[index] local itemPadding = self.itemPadding if (self.selectedItems[index]) then self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"selected") else self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"normal") end end --//============================================================================= function FilePanel:HitTest(x,y) local cx,cy = self:LocalToClient(x,y) local obj = inherited.HitTest(self,cx,cy) if (obj) then return obj end local itemIdx = self:GetItemIndexAt(cx,cy) return (itemIdx>=0) and self end function FilePanel:MouseDblClick(x,y) local cx,cy = self:LocalToClient(x,y) local itemIdx = self:GetItemIndexAt(cx,cy) if (itemIdx<0) then return end --FIXME: loading from complex paths is broken, change this when they get fixed if false and (itemIdx==1) then self:SetDir(GetParentDir(self.dir)) return self end --FIXME: loading from complex paths is broken, change this when they get fixed if false and (itemIdx<=self._dirsNum+1) then self:SetDir(self._dirList[itemIdx-1]) return self else self:CallListeners(self.OnDblClickItem, self.items[itemIdx], itemIdx) return self end end --//=============================================================================
fixed clicking on file_panel's first item
fixed clicking on file_panel's first item
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
a117ab7f0d15ded3851f1566dad78a2ef797bd99
share/luaplaylist/youtube.lua
share/luaplaylist/youtube.lua
-- $Id$ -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( vlc.path, "^.*"..name.."=([^&]*).*$", "%1" ) end -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "youtube.com" ) and ( string.match( vlc.path, "watch%?v=" ) or string.match( vlc.path, "watch_fullscreen%?video_id=" ) or string.match( vlc.path, "p.swf" ) or string.match( vlc.path, "player2.swf" ) ) end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end if string.match( line, "player2.swf" ) then video_id = string.gsub( line, ".*&video_id=([^\"]*).*", "%1" ) end if name and description and artist and video_id then break end end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id; name = name; description = description; artist = artist } } else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end return { { path = "http://www.youtube.com/get_video.php?video_id="..get_url_param( vlc.path, "video_id" ).."&t="..get_url_param( vlc.patch, "t" ); name = name } } end end
-- $Id$ -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" ) end function get_arturl( path, video_id ) if string.match( vlc.path, "iurl=" ) then return vlc.decode_uri( get_url_param( vlc.path, "iurl" ) ) end if not arturl then return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end end -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "youtube.com" ) and ( string.match( vlc.path, "watch%?v=" ) -- the html page or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page or string.match( vlc.path, "p.swf" ) -- the (old?) player url or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007) or string.match( vlc.path, "player2.swf" ) ) -- another player url or ( string.match( vlc.path, "get_video%?video_id=" ) and not string.match( vlc.path, "t=" ) ) -- the video url without the t= parameter which is mandatory (since 24/08/2007) end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end -- var swfArgs = {hl:'en',BASE_YT_URL:'http://youtube.com/',video_id:'XPJ7d8dq0t8',l:'292',t:'OEgsToPDskLFdOYrrlDm3FQPoQBYaCP1',sk:'0gnr-AE6QZJEZmCMd3lq_AC'}; if string.match( line, "swfArgs" ) and string.match( line, "video_id" ) then if string.match( line, "BASE_YT_URL" ) then base_yt_url = string.gsub( line, ".*BASE_YT_URL:'([^']*)'.*", "%1" ) end t = string.gsub( line, ".*t:'([^']*)'.*", "%1" ) vlc.msg_err( t ) -- video_id = string.gsub( line, ".*&video_id:'([^']*)'.*", "%1" ) end if name and description and artist --[[and video_id]] then break end end if not video_id then video_id = get_url_param( vlc.path, "v" ) end if not base_yt_url then base_yt_url = "http://youtube.com/" end art_url = get_arturl( vlc.path, video_id ) if t then return { { path = base_yt_url .. "get_video?video_id="..video_id.."&t="..t; name = name; description = description; artist = artist; arturl = arturl } } else -- This shouldn't happen ... but keep it as a backup. return { { path = "http://www.youtube.com/v/"..video_id; name = name; description = description; artist = artist; arturl = arturl } } end else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end video_id = get_url_param( vlc.path, "video_id" ) art_url = get_arturl( vlc.path, video_id ) if not string.match( vlc.path, "t=" ) then -- This sucks, we're missing "t" which is now mandatory. Let's -- try using another url return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } } end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" ); name = name; arturl = arturl } } end end
Attempt to fix youtube demux script. I still get connections errors towards youtube but i wanted to commit what i'd already done since i'll be gone for a week.
Attempt to fix youtube demux script. I still get connections errors towards youtube but i wanted to commit what i'd already done since i'll be gone for a week.
Lua
lgpl-2.1
vlc-mirror/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc
8c98aa0a67ed6e19068c8fbef1e50dde888f0693
bin/toc2breaks.lua
bin/toc2breaks.lua
#!/bin/env lua -- local dump = require("pl.pretty").dump local project = os.getenv("PROJECT") local basename = arg[1] local tocfile = io.open(arg[2], "r") if not tocfile then return false end local doc = tocfile:read("*a") tocfile:close() local toc = assert(loadstring(doc))() local yaml = require("yaml") local meta = yaml.loadpath(arg[3]) local share = "https://owncloud.alerque.com/" .. (meta.owncloudshare and "index.php/s/" .. meta.owncloudshare .. "/download?path=%2F&files=" or "remote.php/webdav/viachristus/" .. project .. "/") local infofile = io.open(arg[4], "w") if not infofile then return false end local infow = function(str, endpar) str = str or "" endpar = endpar and "\n" or "" infofile:write(str .. "\n" .. endpar) end infow("BOOK NAME:") infow(meta.title, true) infow("SUBTITLE:") infow(meta.subtitle, true) for k, v in ipairs(meta.creator) do if v.role == "author" then meta.author = v.text end end infow("AUTHOR:" ) infow(meta.author, true) infow("ABSTRACT:") infow(meta.abstract, true) -- Drop the first TOC entry, the top of the file will be 1 table.remove(toc, 1) local lastpage = 1 local breaks = { 1 } -- Get a table of major (more that 2 pages apart) TOC entries for k, tocentry in pairs(toc) do local pageno = tonumber(tocentry.pageno) if pageno > lastpage + 2 then table.insert(breaks, pageno) lastpage = pageno end end -- Convert the table to page rages suitable for pdftk for i, v in pairs(breaks) do if i ~= 1 then breaks[i-1] = breaks[i-1] .. "-" .. v - 1 end end breaks[#breaks] = breaks[#breaks] .. "-end" infow("WHOLE FILE:") local out = basename .. "-app.pdf" infow(share .. out, true) -- Output a list suitable for shell script parsing for i, v in pairs(breaks) do local n = string.format("%03d", i) local out = basename .. "-app-" .. n .. ".pdf" -- Fieds expected by makefile to pass to pdftk print(v, out) -- Human readable info for copy/paste to the church app infow("CHUNK " .. i .. ":") infow(share .. out, true) end infofile:close()
#!/bin/env lua local dump = require("pl.pretty").dump local d = function(t) dump(t, "/dev/stderr") end local project = os.getenv("PROJECT") local basename = arg[1] local tocfile = io.open(arg[2], "r") if not tocfile then return false end local doc = tocfile:read("*a") tocfile:close() local toc = assert(loadstring(doc))() local yaml = require("yaml") local meta = yaml.loadpath(arg[3]) local share = "https://owncloud.alerque.com/" .. (meta.owncloudshare and "index.php/s/" .. meta.owncloudshare .. "/download?path=%2F&files=" or "remote.php/webdav/viachristus/" .. project .. "/") local infofile = io.open(arg[4], "w") if not infofile then return false end local infow = function(str, endpar) str = str or "" endpar = endpar and "\n" or "" infofile:write(str .. "\n" .. endpar) end infow("TITLE:") infow(meta.title, true) infow("SUBTITLE:") infow(meta.subtitle, true) for k, v in ipairs(meta.creator) do if v.role == "author" then meta.author = v.text end end infow("AUTHOR:" ) infow(meta.author, true) infow("ABSTRACT:") infow(meta.abstract, true) local labels = {} -- loctal setlabel = function(i, str) labels[i] = str end labels[1] = toc[1].label[1] -- Drop the first TOC entry, the top of the file will be 1 table.remove(toc, 1) local lastpage = 1 local breaks = { 1 } -- Get a table of major (more that 2 pages apart) TOC entries for i, tocentry in pairs(toc) do local pageno = tonumber(tocentry.pageno) if pageno > lastpage + 2 then table.insert(breaks, pageno) labels[#breaks] = tocentry.label[1] lastpage = pageno else labels[#breaks] = labels[#breaks] .. ", " .. tocentry.label[1] end end -- Convert the table to page rages suitable for pdftk for i, v in pairs(breaks) do if i ~= 1 then breaks[i-1] = breaks[i-1] .. "-" .. v - 1 end end breaks[#breaks] = breaks[#breaks] .. "-end" infow("SINGLE PDF:") local out = basename .. "-app.pdf" infow(share .. out, true) -- Output a list suitable for shell script parsing for i, v in pairs(breaks) do local n = string.format("%03d", i) local out = basename .. "-app-" .. n .. ".pdf" -- Fieds expected by makefile to pass to pdftk print(v, out) -- Human readable info for copy/paste to the church app infow("CHUNK " .. i .. ":") infow(labels[i]) infow(share .. out, true) end infofile:close()
Add chapter titles to exported app info file
Add chapter titles to exported app info file Fixes #23
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
05516130a06fc6124526bf1756fb94463f0ffa9a
plugins/weather.lua
plugins/weather.lua
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local API_KEY = "" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url.."?q="..location url = url.."&units=metric" url = url.."&appid="..API_KEY print(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Venezia' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Venezia is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local API_KEY = "" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url.."?q="..string.gsub(location, " ", "+") url = url.."&units=metric" url = url.."&appid="..API_KEY local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Venezia' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Venezia is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
Fix weather.lua
Fix weather.lua Now it looks up the weather also for cities with multiple words as name.
Lua
mit
KevinGuarnati/controllore,KevinGuarnati/controllore
a557155f7d421612dad712d6dbbcfa8e65755f8a
premake4.lua
premake4.lua
local GCC_AVR_CC_PATH = "avr-gcc" local GCC_AVR_CPP_PATH = "avr-g++" local GCC_AVR_AR_PATH = "avr-ar" premake.gcc.cc = GCC_AVR_CC_PATH premake.gcc.cxx = GCC_AVR_CPP_PATH premake.gcc.ar = GCC_AVR_AR_PATH solution "yalla" -------------------------------------------------------------------------------- -- Command line options -------------------------------------------------------------------------------- newoption { trigger = "mmcu", description = "Chose the target platform (default = atmega8)", value="MMCU", allowed = { { "atmega8", "ATmega8" }, { "test", "Test" } } } newoption { trigger = "fcpu", description = "Specify the CPU frequency (default = 8000000)", value="FCPU" } -------------------------------------------------------------------------------- -- Premake settings -------------------------------------------------------------------------------- location "build" language "C++" kind "ConsoleApp" -------------------------------------------------------------------------------- -- General build settings -------------------------------------------------------------------------------- -- Includes includedirs { "include", "include/yalla", "include/yalla/device/atmega8", "/usr/include/simavr/avr/"} -- Enables some additional warnings. buildoptions { "-Wall" } -- Enables C++11 support. buildoptions { "-std=c++14" } -- set optimization. buildoptions { "-Os " } -- set AVR specific options buildoptions {"-fshort-enums -funsigned-char -funsigned-bitfields"} if _OPTIONS["mmcu"] then buildoptions { "-mmcu=" .. _OPTIONS["mmcu"] } end if _OPTIONS["fcpu"] then defines { "F_CPU=" .. _OPTIONS["fcpu"] } end -------------------------------------------------------------------------------- -- Configurations -------------------------------------------------------------------------------- configurations { "release", "debug" } configuration "release" objdir "build/bin/obj" targetdir "build/bin" configuration "debug" objdir "build/dbg/obj" targetdir "build/dbg" -------------------------------------------------------------------------------- -- Projects -------------------------------------------------------------------------------- project "iomm" files { "src/test/avr/iomm/iomm.cpp", "src/test/avr/iomm/iomm_trace.c" } targetname (project().name .. ".elf") postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} postbuildcommands { "avr-size bin/" .. project().name .. ".elf"} project "register" files { "src/test/avr/register/register.cpp", "src/test/avr/register/register_trace.c" } targetname (project().name .. ".elf") postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} postbuildcommands { "avr-size bin/" .. project().name .. ".elf"} -- Add new projects here -- Template: -- project "<name>" -- files { "<file>" } -- targetname (project().name .. ".elf") -- postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} -- postbuildcommands { "avr-size bin/" .. project().name .. ".elf"}
local GCC_AVR_CC_PATH = "avr-gcc" local GCC_AVR_CPP_PATH = "avr-g++" local GCC_AVR_AR_PATH = "avr-ar" premake.gcc.cc = GCC_AVR_CC_PATH premake.gcc.cxx = GCC_AVR_CPP_PATH premake.gcc.ar = GCC_AVR_AR_PATH solution "yalla" -------------------------------------------------------------------------------- -- Command line options -------------------------------------------------------------------------------- newoption { trigger = "mmcu", description = "Chose the target platform (default = atmega8)", value="MMCU", allowed = { { "atmega8", "ATmega8" }, { "test", "Test" } } } newoption { trigger = "fcpu", description = "Specify the CPU frequency (default = 8000000)", value="FCPU" } -------------------------------------------------------------------------------- -- Premake settings -------------------------------------------------------------------------------- location "build" language "C++" kind "ConsoleApp" -------------------------------------------------------------------------------- -- General build settings -------------------------------------------------------------------------------- -- Includes includedirs { "include", "include/yalla", "include/yalla/device/atmega8"} -- Enables some additional warnings. buildoptions { "-Wall" } -- Enables C++11 support. buildoptions { "-std=c++14" } -- set optimization. buildoptions { "-Os " } -- set AVR specific options buildoptions {"-fshort-enums -funsigned-char -funsigned-bitfields"} buildoptions {"`pkg-config --cflags simavr`" } if _OPTIONS["mmcu"] then buildoptions { "-mmcu=" .. _OPTIONS["mmcu"] } end if _OPTIONS["fcpu"] then defines { "F_CPU=" .. _OPTIONS["fcpu"] } end -------------------------------------------------------------------------------- -- Configurations -------------------------------------------------------------------------------- configurations { "release", "debug" } configuration "release" objdir "build/bin/obj" targetdir "build/bin" configuration "debug" objdir "build/dbg/obj" targetdir "build/dbg" -------------------------------------------------------------------------------- -- Projects -------------------------------------------------------------------------------- project "iomm" files { "src/test/avr/iomm/iomm.cpp", "src/test/avr/iomm/iomm_trace.c" } targetname (project().name .. ".elf") postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} postbuildcommands { "avr-size bin/" .. project().name .. ".elf"} project "register" files { "src/test/avr/register/register.cpp", "src/test/avr/register/register_trace.c" } targetname (project().name .. ".elf") postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} postbuildcommands { "avr-size bin/" .. project().name .. ".elf"} -- Add new projects here -- Template: -- project "<name>" -- files { "<file>" } -- targetname (project().name .. ".elf") -- postbuildcommands { "avr-objcopy -O ihex bin/" .. project().name .. ".elf bin/" .. project().name .. ".hex"} -- postbuildcommands { "avr-size bin/" .. project().name .. ".elf"}
premake fix: use pkg-config to find simavr include path
premake fix: use pkg-config to find simavr include path
Lua
mit
chrism333/yalla,chrism333/yalla,chrism333/yalla
a1fab8b2dff5edb077f9b2e045dc962873a306ce
premake4.lua
premake4.lua
function copy(src, dst, always) local action = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\"" src = "\"" .. src .. "\"" dst = "\"" .. dst .. "\"" cwd = "\"" .. os.getcwd() .. "\"" postbuildcommands { action .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) } end function resource(src, dst, always) if always == nil then always = false else always = true end copy(src, path.join("build", dst), always) copy(src, path.join("bin", dst), always) end function windows_libdir(basePath) for _,arch in pairs({"x32", "x64"}) do for _,conf in pairs({"debug", "release"}) do for _, plat in pairs({"vs2008"}) do local confpath = plat .. "/" .. arch .. "/" .. conf configuration { arch, conf, plat } libdirs { path.join(basePath, confpath) } end end end configuration "*" end function windows_binary(basePath, dllName) for _,arch in pairs({"x32", "x64"}) do for _,conf in pairs({"debug", "release"}) do for _, plat in pairs({"vs2008"}) do local confpath = plat .. "/" .. arch .. "/" .. conf configuration { arch, conf, plat } resource(path.join(path.join(basePath, confpath), dllName), dllName, true) end end end configuration "*" end newaction { trigger = 'clean', description = 'Cleans up the project.', shortname = "clean", execute = function() os.rmdir("bin") os.rmdir("build") end } solution "blowmorph" configurations { "debug", "release" } platforms { "x32", "x64" } location "build" targetdir "bin" flags { "FatalWarnings", "NoRTTI" } configuration { "linux" } flags { "NoExceptions" } configuration { "windows" } defines { "WIN32", "_WIN32" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } configuration { "debug" } defines { "DEBUG" } flags { "Symbols" } configuration { "release" } defines { "NDEBUG" } flags { "Optimize" } project "client" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/client/**.cpp", "src/client/**.hpp" } links { "bm-base" } links { "bm-enet" } links { "interpolator" } configuration "linux" includedirs { "/usr/include/freetype2", "ext-libs/glm/include" } links { "SDLmain", "SDL", "freeimage", "GLEW", "freetype" } configuration "windows" includedirs { "ext-libs/SDL1.2/include", "ext-libs/glew/include", "ext-libs/glm/include", "ext-libs/FreeImage/include", "ext-libs/freetype2/include" } links { "SDLmain", "SDL", "freeimage", "opengl32", "glu32", "glew32", "freetype", "ws2_32", "winmm" } windows_libdir("ext-libs/SDL1.2/bin") windows_libdir("ext-libs/glew/bin") windows_libdir("ext-libs/enet/bin") windows_libdir("ext-libs/FreeImage/bin") windows_libdir("ext-libs/freetype2/bin") windows_binary("ext-libs/SDL1.2/bin", "SDL.dll") windows_binary("ext-libs/glew/bin", "glew32.dll") windows_binary("ext-libs/FreeImage/bin", "FreeImage.dll") windows_binary("ext-libs/freetype2/bin", "freetype.dll") resource("data", "data") project "bm-base" kind "SharedLib" language "C++" defines { "BM_BASE_DLL" } includedirs { "include/", "src/" } files { "src/base/**.cpp", "src/base/**.hpp" } project "bm-enet" kind "SharedLib" language "C++" defines { "BM_ENET_DLL" } includedirs { "include/", "src/" } files { "src/enet-wrapper/**.cpp", "src/enet-wrapper/**.hpp" } links { "bm-base" } includedirs { "ext-libs/enet/include" } links { "enet" } for _,arch in pairs({"x32", "x64"}) do for _,conf in pairs({"debug", "release"}) do local confpath = arch .. "/" .. conf configuration { arch, conf, "vs2008" } libdirs { path.join("ext-libs/enet/bin/vs2008", confpath) } end end configuration "windows" links { "ws2_32", "winmm" } project "interpolator" kind "StaticLib" language "C++" includedirs { "include/", "src/" } files { "src/interpolator/**.cpp", "src/interpolator/**.hpp" } project "server" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/server/**.cpp", "src/server/**.hpp" } links { "bm-base" } links { "bm-enet" } resource("data", "data") project "sample-server" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/enet-sample/server.cpp" } links { "bm-base" } links { "bm-enet" } project "sample-client" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/enet-sample/client.cpp" } links { "bm-base" } links { "bm-enet" }
function copy(src, dst, always) local action = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\"" src = "\"" .. src .. "\"" dst = "\"" .. dst .. "\"" cwd = "\"" .. os.getcwd() .. "\"" postbuildcommands { action .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) } end function resource(src, dst, always) if always == nil then always = false else always = true end copy(src, path.join("build", dst), always) copy(src, path.join("bin", dst), always) end function windows_libdir(basePath) for _,arch in pairs({"x32", "x64"}) do for _,conf in pairs({"debug", "release"}) do for _, plat in pairs({"vs2008"}) do local confpath = plat .. "/" .. arch .. "/" .. conf configuration { arch, conf, plat } libdirs { path.join(basePath, confpath) } end end end configuration "*" end function windows_binary(basePath, dllName) for _,arch in pairs({"x32", "x64"}) do for _,conf in pairs({"debug", "release"}) do for _, plat in pairs({"vs2008"}) do local confpath = plat .. "/" .. arch .. "/" .. conf configuration { arch, conf, plat } resource(path.join(path.join(basePath, confpath), dllName), dllName, true) end end end configuration "*" end newaction { trigger = 'clean', description = 'Cleans up the project.', shortname = "clean", execute = function() os.rmdir("bin") os.rmdir("build") end } solution "blowmorph" configurations { "debug", "release" } platforms { "x32", "x64" } location "build" targetdir "bin" flags { "FatalWarnings", "NoRTTI" } configuration { "linux" } flags { "NoExceptions" } configuration { "windows" } defines { "WIN32", "_WIN32" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } configuration { "debug" } defines { "DEBUG" } flags { "Symbols" } configuration { "release" } defines { "NDEBUG" } flags { "Optimize" } project "client" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/client/**.cpp", "src/client/**.hpp" } links { "bm-base" } links { "bm-enet" } links { "interpolator" } configuration "linux" includedirs { "/usr/include/freetype2", "ext-libs/glm/include" } links { "SDLmain", "SDL", "freeimage", "GLEW", "freetype" } configuration "windows" includedirs { "ext-libs/SDL1.2/include", "ext-libs/glew/include", "ext-libs/glm/include", "ext-libs/FreeImage/include", "ext-libs/freetype2/include" } links { "SDLmain", "SDL", "freeimage", "opengl32", "glu32", "glew32", "freetype" } windows_libdir("ext-libs/SDL1.2/bin") windows_libdir("ext-libs/glew/bin") windows_libdir("ext-libs/FreeImage/bin") windows_libdir("ext-libs/freetype2/bin") windows_binary("ext-libs/SDL1.2/bin", "SDL.dll") windows_binary("ext-libs/glew/bin", "glew32.dll") windows_binary("ext-libs/FreeImage/bin", "FreeImage.dll") windows_binary("ext-libs/freetype2/bin", "freetype.dll") resource("data", "data") project "bm-base" kind "SharedLib" language "C++" defines { "BM_BASE_DLL" } includedirs { "include/", "src/" } files { "src/base/**.cpp", "src/base/**.hpp" } project "bm-enet" kind "SharedLib" language "C++" defines { "BM_ENET_DLL" } includedirs { "include/", "src/" } files { "src/enet-wrapper/**.cpp", "src/enet-wrapper/**.hpp" } links { "bm-base" } includedirs { "ext-libs/enet/include" } links { "enet" } windows_libdir("ext-libs/enet/bin") configuration "windows" links { "ws2_32", "winmm" } project "interpolator" kind "StaticLib" language "C++" includedirs { "include/", "src/" } files { "src/interpolator/**.cpp", "src/interpolator/**.hpp" } project "server" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/server/**.cpp", "src/server/**.hpp" } links { "bm-base" } links { "bm-enet" } resource("data", "data") project "sample-server" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/enet-sample/server.cpp" } links { "bm-base" } links { "bm-enet" } project "sample-client" kind "ConsoleApp" language "C++" includedirs { "include/", "src/" } files { "src/enet-sample/client.cpp" } links { "bm-base" } links { "bm-enet" }
fixes in premake4.lua
fixes in premake4.lua
Lua
bsd-3-clause
bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph
e0723fdcd7128f84cf4a1236c175d2094b865ffb
whereami.lua
whereami.lua
local modname = { 'whereami','core' } local concat = table.concat local ok, ffi = pcall(require,'ffi') if not ok then return require(concat(modname,'.')) end local wai_getExe ffi.cdef[[ int wai_getExecutablePath(char* out, int capacity, int* dirname_length); ]] pcall(function() if ffi.C.wai_getExecutablePath then wai_getExe = ffi.C.wai_getExecutablePath end end) if not wai_getExe then local dir_sep, sep, sub local gmatch = string.gmatch local match = string.match local open = io.open local close = io.close for m in gmatch(package.config, '[^\n]+') do local m = m:gsub('([^%w])','%%%1') if not dir_sep then dir_sep = m elseif not sep then sep = m elseif not sub then sub = m end end local function find_lib(name) for m in gmatch(package.cpath, '[^' .. sep ..';]+') do local so_path, r = m:gsub(sub,name) if(r > 0) then local f = open(so_path) if f ~= nil then close(f) return so_path end end end end local function load_lib() local so_path = find_lib(concat(modname,dir_sep)) if so_path then return ffi.load(so_path) end end local lib = load_lib() if lib then wai_getExe = lib.wai_getExecutablePath end end if not wai_getExe then return nil,'failed to load module' end return function() local path_size = wai_getExe(nil,0,nil) local path = ffi.new("char[?]",path_size) local res = wai_getExe(path,path_size,nil) return ffi.string(path,path_size), nil end
local modname = { 'whereami','core' } local concat = table.concat local ok, ffi = pcall(require,'ffi') if not ok then return require(concat(modname,'.')) end local wai_lib ffi.cdef[[ int wai_getExecutablePath(char* out, int capacity, int* dirname_length); ]] pcall(function() if ffi.C.wai_getExecutablePath then wai_lib = ffi.C end end) if not wai_lib then local dir_sep, sep, sub local gmatch = string.gmatch local match = string.match local open = io.open local close = io.close for m in gmatch(package.config, '[^\n]+') do local m = m:gsub('([^%w])','%%%1') if not dir_sep then dir_sep = m elseif not sep then sep = m elseif not sub then sub = m end end local function find_lib(name) for m in gmatch(package.cpath, '[^' .. sep ..';]+') do local so_path, r = m:gsub(sub,name) if(r > 0) then local f = open(so_path) if f ~= nil then close(f) return so_path end end end end local function load_lib() local so_path = find_lib(concat(modname,dir_sep)) if so_path then return ffi.load(so_path) end end wai_lib = load_lib() end if not wai_lib then return nil,'failed to load module' end return function() local path_size = wai_lib.wai_getExecutablePath(nil,0,nil) local path = ffi.new("char[?]",path_size) local res = wai_lib.wai_getExecutablePath(path,path_size,nil) return ffi.string(path,path_size), nil end
fix potential segfault
fix potential segfault
Lua
mit
jprjr/lua-whereami
069a4415a7b6a2dd766fa63f20b086b08399012e
extension/script/backend/master/mgr.lua
extension/script/backend/master/mgr.lua
local json = require 'common.json' local proto = require 'common.protocol' local ev = require 'backend.event' local thread = require 'remotedebug.thread' local stdio = require 'remotedebug.stdio' local redirect = {} local mgr = {} local network local seq = 0 local initialized = false local stat = {} local queue = {} local masterThread local client = {} local maxThreadId = 0 local threadChannel = {} local threadCatalog = {} local threadStatus = {} local threadName = {} local terminateDebuggeeCallback local function genThreadId() maxThreadId = maxThreadId + 1 return maxThreadId end local function event_in(data) local msg = proto.recv(data, stat) if msg then queue[#queue + 1] = msg while msg do msg = proto.recv('', stat) if msg then queue[#queue + 1] = msg end end end end local function event_close() if not initialized then return end mgr.broadcastToWorker { cmd = 'terminated', } ev.emit('close') seq = 0 initialized = false stat = {} queue = {} end local function recv() if #queue == 0 then return end return table.remove(queue, 1) end function mgr.newSeq() seq = seq + 1 return seq end function mgr.init(io) network = io masterThread = thread.channel 'DbgMaster' network.event_in(event_in) network.event_close(event_close) return true end local function lst2map(t) local r = {} for _, v in ipairs(t) do r[v] = true end return r end function mgr.initConfig(config) if redirect.stdout then redirect.stdout:close() redirect.stdout = nil end if redirect.stderr then redirect.stderr:close() redirect.stderr = nil end local outputCapture = lst2map(config.initialize.outputCapture) if outputCapture.stdout then redirect.stdout = stdio.redirect 'stdout' end if outputCapture.stderr then redirect.stderr = stdio.redirect 'stderr' end end function mgr.sendToClient(pkg) network.send(proto.send(pkg, stat)) end function mgr.sendToWorker(w, pkg) return threadChannel[w]:push(json.encode(pkg)) end function mgr.broadcastToWorker(pkg) local msg = json.encode(pkg) for _, channel in pairs(threadChannel) do channel:push(msg) end end function mgr.setThreadName(w, name) threadName[w] = name end function mgr.workers() return threadChannel end function mgr.threads() local t = {} for threadId, status in pairs(threadStatus) do if status == "connect" then t[#t + 1] = { name = ('%s (%d)'):format(threadName[threadId] or "Thread", threadId), id = threadId, } end end table.sort(t, function (a, b) return a.name < b.name end) return t end function mgr.hasThread(w) return threadChannel[w] ~= nil end function mgr.initWorker(WorkerIdent) local workerChannel = ('DbgWorker(%s)'):format(WorkerIdent) local threadId = genThreadId() threadChannel[threadId] = assert(thread.channel(workerChannel)) threadCatalog[WorkerIdent] = threadId threadStatus[threadId] = "disconnect" threadName[threadId] = nil ev.emit('worker-ready', threadId) end function mgr.setThreadStatus(threadId, status) threadStatus[threadId] = status if terminateDebuggeeCallback and status == "disconnect" then for _, s in pairs(threadStatus) do if s == "connect" then return end end terminateDebuggeeCallback() end end function mgr.setTerminateDebuggeeCallback(callback) for _, s in pairs(threadStatus) do if s == "connect" then terminateDebuggeeCallback = callback return end end callback() end function mgr.exitWorker(w) threadChannel[w] = nil for WorkerIdent, threadId in pairs(threadCatalog) do if threadId == w then threadCatalog[WorkerIdent] = nil end end threadStatus[w] = nil threadName[w] = nil end local function updateOnce() local threadCMD = require 'backend.master.threads' while true do local ok, w, cmd, msg = masterThread:pop() if not ok then break end if threadCMD[cmd] then local pkg = json.decode(msg) threadCMD[cmd](threadCatalog[w] or w, pkg) end end if redirect.stderr then local res = redirect.stderr:read(redirect.stderr:peek()) if res then local event = require 'backend.master.event' event.output { category = 'stderr', output = res, } end end if redirect.stdout then local res = redirect.stdout:read(redirect.stdout:peek()) if res then local event = require 'backend.master.event' event.output { category = 'stdout', output = res, } end end if not network.update() then return true end local req = recv() if not req then return true end if req.type == 'request' then -- TODO local request = require 'backend.master.request' if not initialized then if req.command == 'initialize' then initialized = true request.initialize(req) else local response = require 'backend.master.response' response.error(req, ("`%s` not yet implemented.(birth)"):format(req.command)) end else local f = request[req.command] if f and req.command ~= 'initialize' then if f(req) then return true end else local response = require 'backend.master.response' response.error(req, ("`%s` not yet implemented.(idle)"):format(req.command)) end end end return false end function mgr.update() while true do if updateOnce() then thread.sleep(0.01) return end end end function mgr.setClient(c) client = c end function mgr.getClient() return client end return mgr
local json = require 'common.json' local proto = require 'common.protocol' local ev = require 'backend.event' local thread = require 'remotedebug.thread' local stdio = require 'remotedebug.stdio' local redirect = {} local mgr = {} local network local seq = 0 local initialized = false local stat = {} local queue = {} local masterThread local client = {} local maxThreadId = 0 local threadChannel = {} local threadCatalog = {} local threadStatus = {} local threadName = {} local terminateDebuggeeCallback local function genThreadId() maxThreadId = maxThreadId + 1 return maxThreadId end local function event_in(data) local msg = proto.recv(data, stat) if msg then queue[#queue + 1] = msg while msg do msg = proto.recv('', stat) if msg then queue[#queue + 1] = msg end end end end local function event_close() if not initialized then return end mgr.broadcastToWorker { cmd = 'terminated', } ev.emit('close') seq = 0 initialized = false stat = {} queue = {} end local function recv() if #queue == 0 then return end return table.remove(queue, 1) end function mgr.newSeq() seq = seq + 1 return seq end function mgr.init(io) network = io masterThread = thread.channel 'DbgMaster' network.event_in(event_in) network.event_close(event_close) return true end local function lst2map(t) local r = {} for _, v in ipairs(t) do r[v] = true end return r end function mgr.initConfig(config) if redirect.stdout then redirect.stdout:close() redirect.stdout = nil end if redirect.stderr then redirect.stderr:close() redirect.stderr = nil end local outputCapture = lst2map(config.initialize.outputCapture) if outputCapture.stdout then redirect.stdout = stdio.redirect 'stdout' end if outputCapture.stderr then redirect.stderr = stdio.redirect 'stderr' end end function mgr.sendToClient(pkg) network.send(proto.send(pkg, stat)) end function mgr.sendToWorker(w, pkg) return threadChannel[w]:push(json.encode(pkg)) end function mgr.broadcastToWorker(pkg) local msg = json.encode(pkg) for _, channel in pairs(threadChannel) do channel:push(msg) end end function mgr.setThreadName(w, name) if name == json.null then threadName[w] = nil else threadName[w] = name end end function mgr.workers() return threadChannel end function mgr.threads() local t = {} for threadId, status in pairs(threadStatus) do if status == "connect" then t[#t + 1] = { name = ('%s (%d)'):format(threadName[threadId] or "Thread", threadId), id = threadId, } end end table.sort(t, function (a, b) return a.name < b.name end) return t end function mgr.hasThread(w) return threadChannel[w] ~= nil end function mgr.initWorker(WorkerIdent) local workerChannel = ('DbgWorker(%s)'):format(WorkerIdent) local threadId = genThreadId() threadChannel[threadId] = assert(thread.channel(workerChannel)) threadCatalog[WorkerIdent] = threadId threadStatus[threadId] = "disconnect" threadName[threadId] = nil ev.emit('worker-ready', threadId) end function mgr.setThreadStatus(threadId, status) threadStatus[threadId] = status if terminateDebuggeeCallback and status == "disconnect" then for _, s in pairs(threadStatus) do if s == "connect" then return end end terminateDebuggeeCallback() end end function mgr.setTerminateDebuggeeCallback(callback) for _, s in pairs(threadStatus) do if s == "connect" then terminateDebuggeeCallback = callback return end end callback() end function mgr.exitWorker(w) threadChannel[w] = nil for WorkerIdent, threadId in pairs(threadCatalog) do if threadId == w then threadCatalog[WorkerIdent] = nil end end threadStatus[w] = nil threadName[w] = nil end local function updateOnce() local threadCMD = require 'backend.master.threads' while true do local ok, w, cmd, msg = masterThread:pop() if not ok then break end if threadCMD[cmd] then local pkg = json.decode(msg) threadCMD[cmd](threadCatalog[w] or w, pkg) end end if redirect.stderr then local res = redirect.stderr:read(redirect.stderr:peek()) if res then local event = require 'backend.master.event' event.output { category = 'stderr', output = res, } end end if redirect.stdout then local res = redirect.stdout:read(redirect.stdout:peek()) if res then local event = require 'backend.master.event' event.output { category = 'stdout', output = res, } end end if not network.update() then return true end local req = recv() if not req then return true end if req.type == 'request' then -- TODO local request = require 'backend.master.request' if not initialized then if req.command == 'initialize' then initialized = true request.initialize(req) else local response = require 'backend.master.response' response.error(req, ("`%s` not yet implemented.(birth)"):format(req.command)) end else local f = request[req.command] if f and req.command ~= 'initialize' then if f(req) then return true end else local response = require 'backend.master.response' response.error(req, ("`%s` not yet implemented.(idle)"):format(req.command)) end end end return false end function mgr.update() while true do if updateOnce() then thread.sleep(0.01) return end end end function mgr.setClient(c) client = c end function mgr.getClient() return client end return mgr
fixes bug
fixes bug
Lua
mit
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
a325d89df8376b75fa9a26d40da6a32501f940bd
gin/cli/application.lua
gin/cli/application.lua
-- dep local ansicolors = require 'ansicolors' -- gin local Gin = require 'gin.core.gin' local helpers = require 'gin.helpers.common' local gitignore = [[ # gin client_body_temp fastcgi_temp logs proxy_temp tmp uwsgi_temp # vim .*.sw[a-z] *.un~ Session.vim # textmate *.tmproj *.tmproject tmtags # OSX .DS_Store ._* .Spotlight-V100 .Trashes *.swp ]] local pages_controller = [[ local PagesController = {} function PagesController:root() return 200, { message = "Hello world from Gin!" } end return PagesController ]] local errors = [[ ------------------------------------------------------------------------------------------------------------------- -- Define all of your application errors in here. They should have the format: -- -- local Errors = { -- [1000] = { status = 400, message = "My Application error.", headers = { ["X-Header"] = "header" } }, -- } -- -- where: -- '1000' is the error number that can be raised from controllers with `self:raise_error(1000) -- 'status' (required) is the http status code -- 'message' (required) is the error description -- 'headers' (optional) are the headers to be returned in the response ------------------------------------------------------------------------------------------------------------------- local Errors = {} return Errors ]] local application = [[ local Application = { name = "{{APP_NAME}}", version = '0.0.1' } return Application ]] mysql = [[ local SqlDatabase = require 'gin.db.sql' local Gin = require 'gin.core.gin' -- First, specify the environment settings for this database, for instance: -- local DbSettings = { -- development = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_development", -- user = "root", -- password = "", -- pool = 5 -- }, -- test = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_test", -- user = "root", -- password = "", -- pool = 5 -- }, -- production = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_production", -- user = "root", -- password = "", -- pool = 5 -- } -- } -- Then initialize and return your database: -- local MySql = SqlDatabase.new(DbSettings[Gin.env]) -- -- return MySql ]] local nginx_config = [[ pid ]] .. Gin.app_dirs.tmp .. [[/{{GIN_ENV}}-nginx.pid; # This number should be at maxium the number of CPU on the server worker_processes 4; events { # Number of connections per worker worker_connections 4096; } http { # use sendfile sendfile on; # Gin initialization {{GIN_INIT}} server { # List port listen {{GIN_PORT}}; # Access log with buffer, or disable it completetely if unneeded access_log ]] .. Gin.app_dirs.logs .. [[/{{GIN_ENV}}-access.log combined buffer=16k; # access_log off; # Error log error_log ]] .. Gin.app_dirs.logs .. [[/{{GIN_ENV}}-error.log; # Gin runtime {{GIN_RUNTIME}} } } ]] local routes = [[ local routes = require 'gin.core.routes' -- define version local v1 = routes.version(1) -- define routes v1:GET("/", { controller = "pages", action = "root" }) return routes ]] local settings = [[ -------------------------------------------------------------------------------- -- Settings defined here are environment dependent. Inside of your application, -- `Gin.settings` will return the ones that correspond to the environment -- you are running the server in. -------------------------------------------------------------------------------- local Settings = {} Settings.development = { code_cache = false, port = 7200, expose_api_console = true } Settings.test = { code_cache = true, port = 7201, expose_api_console = false } Settings.production = { code_cache = true, port = 80, expose_api_console = false } return Settings ]] local pages_controller_spec = [[ require 'spec.spec_helper' describe("PagesController", function() describe("#root", function() it("responds with a welcome message", function() local response = hit({ method = 'GET', path = "/" }) assert.are.same(200, response.status) assert.are.same({ message = "Hello world from Gin!" }, response.body) end) end) end) ]] local spec_helper = [[ require 'gin.spec.runner' ]] local GinApplication = {} GinApplication.files = { ['.gitignore'] = gitignore, ['app/controllers/1/pages_controller.lua'] = pages_controller, ['app/models/.gitkeep'] = "", ['config/errors.lua'] = errors, ['config/application.lua'] = "", ['config/nginx.conf'] = nginx_config, ['config/routes.lua'] = routes, ['config/settings.lua'] = settings, ['db/migrations/.gitkeep'] = "", ['db/schemas/.gitkeep'] = "", ['db/mysql.lua'] = "", ['lib/.gitkeep'] = "", ['spec/controllers/1/pages_controller_spec.lua'] = pages_controller_spec, ['spec/models/.gitkeep'] = "", ['spec/spec_helper.lua'] = spec_helper } function GinApplication.new(name) print(ansicolors("Creating app %{cyan}" .. name .. "%{reset}...")) GinApplication.files['config/application.lua'] = string.gsub(application, "{{APP_NAME}}", name) GinApplication.files['db/mysql.lua'] = string.gsub(mysql, "{{APP_NAME}}", name) GinApplication.create_files(name) end function GinApplication.create_files(parent) for file_path, file_content in pairs(GinApplication.files) do -- ensure containing directory exists local full_file_path = parent .. "/" .. file_path helpers.mkdirs(full_file_path) -- create file local fw = io.open(full_file_path, "w") fw:write(file_content) fw:close() print(ansicolors(" %{green}created file%{reset} " .. full_file_path)) end end return GinApplication
-- dep local ansicolors = require 'ansicolors' -- gin local Gin = require 'gin.core.gin' local helpers = require 'gin.helpers.common' local gitignore = [[ # gin client_body_temp fastcgi_temp logs proxy_temp tmp uwsgi_temp # vim .*.sw[a-z] *.un~ Session.vim # textmate *.tmproj *.tmproject tmtags # OSX .DS_Store ._* .Spotlight-V100 .Trashes *.swp ]] local pages_controller = [[ local PagesController = {} function PagesController:root() return 200, { message = "Hello world from Gin!" } end return PagesController ]] local errors = [[ ------------------------------------------------------------------------------------------------------------------- -- Define all of your application errors in here. They should have the format: -- -- local Errors = { -- [1000] = { status = 400, message = "My Application error.", headers = { ["X-Header"] = "header" } }, -- } -- -- where: -- '1000' is the error number that can be raised from controllers with `self:raise_error(1000) -- 'status' (required) is the http status code -- 'message' (required) is the error description -- 'headers' (optional) are the headers to be returned in the response ------------------------------------------------------------------------------------------------------------------- local Errors = {} return Errors ]] local application = [[ local Application = { name = "{{APP_NAME}}", version = '0.0.1' } return Application ]] mysql = [[ local SqlDatabase = require 'gin.db.sql' local Gin = require 'gin.core.gin' -- First, specify the environment settings for this database, for instance: -- local DbSettings = { -- development = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_development", -- user = "root", -- password = "", -- pool = 5 -- }, -- test = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_test", -- user = "root", -- password = "", -- pool = 5 -- }, -- production = { -- adapter = 'mysql', -- host = "127.0.0.1", -- port = 3306, -- database = "{{APP_NAME}}_production", -- user = "root", -- password = "", -- pool = 5 -- } -- } -- Then initialize and return your database: -- local MySql = SqlDatabase.new(DbSettings[Gin.env]) -- -- return MySql ]] local nginx_config = [[ pid ]] .. Gin.app_dirs.tmp .. [[/{{GIN_ENV}}-nginx.pid; # This number should be at maxium the number of CPU on the server worker_processes 4; events { # Number of connections per worker worker_connections 4096; } http { # use sendfile sendfile on; # Gin initialization {{GIN_INIT}} server { # List port listen {{GIN_PORT}}; # Access log with buffer, or disable it completetely if unneeded access_log ]] .. Gin.app_dirs.logs .. [[/{{GIN_ENV}}-access.log combined buffer=16k; # access_log off; # Error log error_log ]] .. Gin.app_dirs.logs .. [[/{{GIN_ENV}}-error.log; # Gin runtime {{GIN_RUNTIME}} } # set temp paths proxy_temp_path tmp; client_body_temp_path tmp; fastcgi_temp_path tmp; scgi_temp_path tmp; uwsgi_temp_path tmp; } ]] local routes = [[ local routes = require 'gin.core.routes' -- define version local v1 = routes.version(1) -- define routes v1:GET("/", { controller = "pages", action = "root" }) return routes ]] local settings = [[ -------------------------------------------------------------------------------- -- Settings defined here are environment dependent. Inside of your application, -- `Gin.settings` will return the ones that correspond to the environment -- you are running the server in. -------------------------------------------------------------------------------- local Settings = {} Settings.development = { code_cache = false, port = 7200, expose_api_console = true } Settings.test = { code_cache = true, port = 7201, expose_api_console = false } Settings.production = { code_cache = true, port = 80, expose_api_console = false } return Settings ]] local pages_controller_spec = [[ require 'spec.spec_helper' describe("PagesController", function() describe("#root", function() it("responds with a welcome message", function() local response = hit({ method = 'GET', path = "/" }) assert.are.same(200, response.status) assert.are.same({ message = "Hello world from Gin!" }, response.body) end) end) end) ]] local spec_helper = [[ require 'gin.spec.runner' ]] local GinApplication = {} GinApplication.files = { ['.gitignore'] = gitignore, ['app/controllers/1/pages_controller.lua'] = pages_controller, ['app/models/.gitkeep'] = "", ['config/errors.lua'] = errors, ['config/application.lua'] = "", ['config/nginx.conf'] = nginx_config, ['config/routes.lua'] = routes, ['config/settings.lua'] = settings, ['db/migrations/.gitkeep'] = "", ['db/schemas/.gitkeep'] = "", ['db/mysql.lua'] = "", ['lib/.gitkeep'] = "", ['spec/controllers/1/pages_controller_spec.lua'] = pages_controller_spec, ['spec/models/.gitkeep'] = "", ['spec/spec_helper.lua'] = spec_helper } function GinApplication.new(name) print(ansicolors("Creating app %{cyan}" .. name .. "%{reset}...")) GinApplication.files['config/application.lua'] = string.gsub(application, "{{APP_NAME}}", name) GinApplication.files['db/mysql.lua'] = string.gsub(mysql, "{{APP_NAME}}", name) GinApplication.create_files(name) end function GinApplication.create_files(parent) for file_path, file_content in pairs(GinApplication.files) do -- ensure containing directory exists local full_file_path = parent .. "/" .. file_path helpers.mkdirs(full_file_path) -- create file local fw = io.open(full_file_path, "w") fw:write(file_content) fw:close() print(ansicolors(" %{green}created file%{reset} " .. full_file_path)) end end return GinApplication
Set temp paths to avoid polluting the app directory.
Set temp paths to avoid polluting the app directory. Fixed as suggested in #21
Lua
mit
istr/gin,ostinelli/gin
96a25fb33c61991056990e05afc66026f299d296
hammerspoon/tap-modifier-for-hotkey.lua
hammerspoon/tap-modifier-for-hotkey.lua
local eventtap = require('hs.eventtap') local events = eventtap.event.types local modal={} -- Return an object whose behavior is inspired by hs.hotkey.modal. In this case, -- the modal state is entered when the specified modifier key is tapped (i.e., -- pressed and then released in quick succession). modal.new = function(modifier) local instance = { modifier = modifier, tapTimeoutInSeconds = 0.5, modalStateTimeoutInSeconds = 0.5, modalKeybindings = {}, reset = function(self) self.inModalState = false self.modifierDownHappened = false return self end, -- Enable the modal -- -- Mimics hs.modal:enable() enable = function(self) self.watcher:start() end, -- Disable the modal -- -- Mimics hs.modal:disable() disable = function(self) self.watcher:stop() self.watcher:reset() end, -- Temporarily enter the modal state in which the modal's hotkeys are -- active. The modal state will terminate after `modalStateTimeoutInSeconds` -- or after the first keydown event, whichever comes first. -- -- Mimics hs.modal.modal:enter() enter = function(self) self.inModalState = true self:entered() hs.timer.doAfter(self.modalStateTimeoutInSeconds, function() self:exit() end ) end, -- Exit the modal state in which the modal's hotkey are active -- -- Mimics hs.modal.modal:exit() exit = function(self) if not self.inModalState then return end self:reset() self:exited() end, -- Optional callback for when modal state is entered -- -- Mimics hs.modal.modal:entered() entered = function(self) end, -- Optional callback for when modal state is exited -- -- Mimics hs.modal.modal:exited() exited = function(self) end, -- Bind hotkey that will be enabled/disabled as modal state is -- entered/exited bind = function(self, key, fn) self.modalKeybindings[key] = fn end, } isNoModifiers = function(flagsChangedEvent) local isFalsey = function(value) return not value end return hs.fnutils.every(flagsChangedEvent:getFlags(), isFalsey) end isOnlyModifier = function(flagsChangedEvent) return hs.fnutils.every(flagsChangedEvent:getFlags(), function(isDown, modifierName) return (isDown and modifierName == modifier) or (not isDown and not modifierName == modifier) end) end onModifierChange = function(event) -- If it's only the modifier that we care about, then this could be the -- start of a tap, so start watching for the modifier to be released. if isOnlyModifier(event) and not instance.modifierDownHappened then instance.modifierDownHappened = true -- If the modifier isn't released before the timeout, then it doesn't seem -- like the user is intending to *tap* the modifier key. So, start over. hs.timer.doAfter(instance.tapTimeoutInSeconds, function() if not instance.inModalState then instance:reset() end end) return end -- If we've seen one press of the modifier we care about, and now no -- modifiers are down, then this is the key-up event for the modifier we care -- about. So, enter the modal state. if isNoModifiers(event) and instance.modifierDownHappened then instance:enter() return end -- If we get there, then this isn't the sequence of events we were looking -- for, so start over. instance:reset() -- Allow the event to propagate return false end onKeyDown = function(event) if instance.inModalState then local fn = instance.modalKeybindings[event:getCharacters():lower()] if fn then fn() end instance:exit() -- Delete the event so that we're the sole consumer of it return true else -- Since we're not in the modal state, this event isn't part of a sequence -- of events that represents the modifier being tapped, so start over. instance:reset() -- Allow the event to propagate return false end end instance.watcher = eventtap.new({events.flagsChanged, events.keyDown}, function(event) if event:getType() == events.flagsChanged then return onModifierChange(event) else return onKeyDown(event) end end ) return instance:reset() end return modal
local eventtap = require('hs.eventtap') local events = eventtap.event.types local modal={} -- Return an object whose behavior is inspired by hs.hotkey.modal. In this case, -- the modal state is entered when the specified modifier key is tapped (i.e., -- pressed and then released in quick succession). modal.new = function(modifier) local instance = { modifier = modifier, tapTimeoutInSeconds = 0.5, modalStateTimeoutInSeconds = 0.5, modalKeybindings = {}, reset = function(self) self.inModalState = false self.modifierDownHappened = false return self end, -- Enable the modal -- -- Mimics hs.modal:enable() enable = function(self) self.watcher:start() end, -- Disable the modal -- -- Mimics hs.modal:disable() disable = function(self) self.watcher:stop() self.watcher:reset() end, -- Temporarily enter the modal state in which the modal's hotkeys are -- active. The modal state will terminate after `modalStateTimeoutInSeconds` -- or after the first keydown event, whichever comes first. -- -- Mimics hs.modal.modal:enter() enter = function(self) self.inModalState = true self:entered() hs.timer.doAfter(self.modalStateTimeoutInSeconds, function() self:exit() end ) end, -- Exit the modal state in which the modal's hotkey are active -- -- Mimics hs.modal.modal:exit() exit = function(self) if not self.inModalState then return end self:reset() self:exited() end, -- Optional callback for when modal state is entered -- -- Mimics hs.modal.modal:entered() entered = function(self) end, -- Optional callback for when modal state is exited -- -- Mimics hs.modal.modal:exited() exited = function(self) end, -- Bind hotkey that will be enabled/disabled as modal state is -- entered/exited bind = function(self, key, fn) self.modalKeybindings[key] = fn end, } isNoModifiers = function(flagsChangedEvent) local isFalsey = function(value) return not value end return hs.fnutils.every(flagsChangedEvent:getFlags(), isFalsey) end isOnlyModifier = function(flagsChangedEvent) local flags = flagsChangedEvent:getFlags() isPrimaryModiferDown = flags[modifier] areOtherModifiersDown = hs.fnutils.some(flags, function(isDown, modifierName) return isDown and not modifierName == modifier end) return isPrimaryModiferDown and not areOtherModifiersDown end onModifierChange = function(event) -- If it's only the modifier that we care about, then this could be the -- start of a tap, so start watching for the modifier to be released. if isOnlyModifier(event) and not instance.modifierDownHappened then instance.modifierDownHappened = true -- If the modifier isn't released before the timeout, then it doesn't seem -- like the user is intending to *tap* the modifier key. So, start over. hs.timer.doAfter(instance.tapTimeoutInSeconds, function() if not instance.inModalState then instance:reset() end end) return end -- If we've seen one press of the modifier we care about, and now no -- modifiers are down, then this is the key-up event for the modifier we care -- about. So, enter the modal state. if isNoModifiers(event) and instance.modifierDownHappened then instance:enter() return end -- If we get there, then this isn't the sequence of events we were looking -- for, so start over. instance:reset() -- Allow the event to propagate return false end onKeyDown = function(event) if instance.inModalState then local fn = instance.modalKeybindings[event:getCharacters():lower()] if fn then fn() end instance:exit() -- Delete the event so that we're the sole consumer of it return true else -- Since we're not in the modal state, this event isn't part of a sequence -- of events that represents the modifier being tapped, so start over. instance:reset() -- Allow the event to propagate return false end end instance.watcher = eventtap.new({events.flagsChanged, events.keyDown}, function(event) if event:getType() == events.flagsChanged then return onModifierChange(event) else return onKeyDown(event) end end ) return instance:reset() end return modal
:bug: Fix isOnlyModifier fn
:bug: Fix isOnlyModifier fn
Lua
mit
jasonrudolph/keyboard,jasonrudolph/keyboard
f6550cfe915192fc9067250f8c428e086489e418
src/cosy/cli/init.lua
src/cosy/cli/init.lua
os.remove (os.getenv "HOME" .. "/.cosy/client.log") local Cli = {} Cli.__index = Cli function Cli.new () return setmetatable ({}, Cli) end ----------------------------- -- While not found Cli tries to determine what server it will connect to -- by scanning in that order : -- 1. --server=xxx cmd line option -- 2. ~/.cosy/cli.data config file (ie last server used) -- 3. configuration function Cli.configure (cli, arguments) assert (getmetatable (cli) == Cli) local _ = require "copas" ---- WARNING WE CANNOT WAIT TO GET IT FROM THE SERVER local Lfs = require "lfs" -- C module : won't be reloaded from server local Json = require "cjson" -- lua tables are transcoded into json for server (pkg comes with lua socket) local Ltn12 = require "ltn12" -- to store the content of the requests ( pkgcomes with lua socket) local Mime = require "mime" local Hotswap = require "hotswap.http" -- parse the cmd line arguments to fetch server and/or color options local key = "server" local pattern = "%-%-" .. key .. "=(.*)" local j = 1 while j <= #arguments do local argument = arguments [j] local value = argument:match (pattern) -- value contains only right hand side of equals if value then -- matched assert (not cli [key]) -- (better) nil or false cli [key] = value table.remove (arguments, j) else j = j + 1 end end cli.arguments = arguments -- reads the config local cosy_dir = os.getenv "HOME" .. "/.cosy" local data_file = cosy_dir .. "/cli-server" -- contains last server uri if not cli.server then ---- try to fetch the server from the previously saved config local file = io.open (data_file,"r") if file then cli.server = file:read "*all" -- all the file file:close () end end if not cli.server then ---- still not : -- try to fetch the server from the default config cli.server = "http://public.cosyverif.lsv.fr" cli.hardcoded_server = true -- warning end assert (cli.server) -- trim eventuel trailing / http://server/ cli.server = cli.server:gsub("/+$","") assert (cli.server:match "^https?://") -- check is an URI do -- save server name for next cli launch Lfs.mkdir (cosy_dir) local file, err = io.open (data_file,"w") if file then file:write (cli.server) file:close () else print (err) end end -- save server name for next cli launch -- every dowloaded lua package will be saved in ~/.cosy/lua/base64(server_name) local package_dir = cosy_dir .. "/lua/" local server_dir = package_dir .. Mime.b64 (cli.server) Lfs.mkdir (package_dir) Lfs.mkdir (server_dir) local hotswap = Hotswap { storage = server_dir, -- where to save the lua files encode = function (t) local data = Json.encode (t) return { url = cli.server .. "/luaset", method = "POST", headers = { ["Content-Length"] = #data, }, source = Ltn12.source.string (data), } end, decode = function (t) if t.code == 200 then return Json.decode (t.body) end end, } -- In order to download lua modules (required by the client) from the server -- we replace the Lua require function -- by the hotswap.require which will also save lua packages into "server_dir" local ok, factory = pcall (hotswap.require, "cosy.loader.lua") if not ok then print ("Cannot download sources from " .. cli.server .. ".") os.exit (1) end cli.loader = factory { hotswap = hotswap, logto = os.getenv "HOME" .. "/.cosy/client.log", } end function Cli.start (cli) assert (getmetatable (cli) == Cli) cli:configure (_G.arg) local loader = cli.loader local Configuration = loader.load "cosy.configuration" local I18n = loader.load "cosy.i18n" local Library = loader.load "cosy.library" local Arguments = loader.require "argparse" local Colors = loader.require "ansicolors" Configuration.load { "cosy.cli", } local i18n = I18n.load { "cosy.cli", } i18n._locale = Configuration.cli.locale print (Colors ("%{green blackbg}" .. i18n ["client:server"] % { server = cli.server, })) local client = Library.connect (cli.server) if not client then print (Colors ("%{white redbg}" .. i18n ["failure"] % {}), Colors ("%{white redbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end local name = os.getenv "COSY_PREFIX" .. "/bin/cosy" name = name:gsub (os.getenv "HOME", "~") local parser = Arguments () { name = name, description = i18n ["client:command"] % {}, } parser:option "-s" "--server" { description = i18n ["option:server"] % {}, default = cli.server, } parser:option "-l" "--locale" { description = i18n ["option:locale"] % {}, default = Configuration.cli.locale, } local Commands = loader.load "cosy.cli.commands" local commands = Commands.new { parser = parser, client = client, } local ok, result = xpcall (function () Commands.parse (commands) end, function (err) print (Colors ("%{white redbg}" .. i18n ["error:unexpected"] % {})) print (err) print (debug.traceback ()) end) if not ok and result then print (Colors ("%{red blackbg}" .. i18n ["failure"] % {})) print (Colors ("%{white redbg}" .. i18n (result.error).message)) end os.exit (ok and 0 or 1) end function Cli.stop (cli) assert (getmetatable (cli) == Cli) end return Cli
os.remove (os.getenv "HOME" .. "/.cosy/client.log") local Cli = {} Cli.__index = Cli function Cli.new () return setmetatable ({}, Cli) end ----------------------------- -- While not found Cli tries to determine what server it will connect to -- by scanning in that order : -- 1. --server=xxx cmd line option -- 2. ~/.cosy/cli.data config file (ie last server used) -- 3. configuration function Cli.configure (cli, arguments) assert (getmetatable (cli) == Cli) local _ = require "copas" ---- WARNING WE CANNOT WAIT TO GET IT FROM THE SERVER local Lfs = require "lfs" -- C module : won't be reloaded from server local Json = require "cjson" -- lua tables are transcoded into json for server (pkg comes with lua socket) local Ltn12 = require "ltn12" -- to store the content of the requests ( pkgcomes with lua socket) local Mime = require "mime" local Hotswap = require "hotswap.http" -- parse the cmd line arguments to fetch server and/or color options local key = "server" local pattern = "%-%-" .. key .. "=(.*)" local j = 1 while j <= #arguments do local argument = arguments [j] local value = argument:match (pattern) -- value contains only right hand side of equals if value then -- matched assert (not cli [key]) -- (better) nil or false cli [key] = value table.remove (arguments, j) else j = j + 1 end end cli.arguments = arguments -- reads the config local cosy_dir = os.getenv "HOME" .. "/.cosy" local data_file = cosy_dir .. "/cli-server" -- contains last server uri if not cli.server then ---- try to fetch the server from the previously saved config local file = io.open (data_file,"r") if file then cli.server = file:read "*all" -- all the file file:close () end end if not cli.server then ---- still not : -- try to fetch the server from the default config cli.server = "http://public.cosyverif.lsv.fr" cli.hardcoded_server = true -- warning end assert (cli.server) -- trim eventuel trailing / http://server/ cli.server = cli.server:gsub("/+$","") assert (cli.server:match "^https?://") -- check is an URI do -- save server name for next cli launch Lfs.mkdir (cosy_dir) local file, err = io.open (data_file,"w") if file then file:write (cli.server) file:close () else print (err) end end -- save server name for next cli launch -- every dowloaded lua package will be saved in ~/.cosy/lua/base64(server_name) local package_dir = cosy_dir .. "/lua/" local server_dir = package_dir .. Mime.b64 (cli.server) Lfs.mkdir (package_dir) Lfs.mkdir (server_dir) local hotswap = Hotswap { storage = server_dir, -- where to save the lua files encode = function (t) local data = Json.encode (t) return { url = cli.server .. "/luaset", method = "POST", headers = { ["Content-Length"] = #data, }, source = Ltn12.source.string (data), } end, decode = function (t) if t.code == 200 then return Json.decode (t.body) end end, } -- In order to download lua modules (required by the client) from the server -- we replace the Lua require function -- by the hotswap.require which will also save lua packages into "server_dir" local factory = hotswap.require "cosy.loader.lua" local ok, loader = pcall (factory, { hotswap = hotswap, logto = os.getenv "HOME" .. "/.cosy/client.log", }) if not ok then print ("Cannot download sources from " .. cli.server .. ".") os.exit (1) end cli.loader = loader end function Cli.start (cli) assert (getmetatable (cli) == Cli) cli:configure (_G.arg) local loader = cli.loader local Configuration = loader.load "cosy.configuration" local I18n = loader.load "cosy.i18n" local Library = loader.load "cosy.library" local Arguments = loader.require "argparse" local Colors = loader.require "ansicolors" Configuration.load { "cosy.cli", } local i18n = I18n.load { "cosy.cli", } i18n._locale = Configuration.cli.locale print (Colors ("%{green blackbg}" .. i18n ["client:server"] % { server = cli.server, })) local client = Library.connect (cli.server) if not client then print (Colors ("%{white redbg}" .. i18n ["failure"] % {}), Colors ("%{white redbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end local name = os.getenv "COSY_PREFIX" .. "/bin/cosy" name = name:gsub (os.getenv "HOME", "~") local parser = Arguments () { name = name, description = i18n ["client:command"] % {}, } parser:option "-s" "--server" { description = i18n ["option:server"] % {}, default = cli.server, } parser:option "-l" "--locale" { description = i18n ["option:locale"] % {}, default = Configuration.cli.locale, } local Commands = loader.load "cosy.cli.commands" local commands = Commands.new { parser = parser, client = client, } local ok, result = xpcall (function () Commands.parse (commands) end, function (err) print (Colors ("%{white redbg}" .. i18n ["error:unexpected"] % {})) print (err) print (debug.traceback ()) end) if not ok and result then print (Colors ("%{red blackbg}" .. i18n ["failure"] % {})) print (Colors ("%{white redbg}" .. i18n (result.error).message)) end os.exit (ok and 0 or 1) end function Cli.stop (cli) assert (getmetatable (cli) == Cli) end return Cli
Fix error handling in loader creation.
Fix error handling in loader creation.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
445cca235bf9d1272eb91959d46b43334e424fd0
src/train_point_cloud.lua
src/train_point_cloud.lua
require 'torch' require 'cutorch' require 'math' require 'nn' require 'gnuplot' require 'image' require 'optim' require 'point_cloud_model_definition' require 'point_cloud_constants' require 'point_cloud_error_calculation' require 'point_cloud_loader' require 'loader_ffi' torch.manualSeed(10000) cutorch.manualSeed(10000) local opt = define_constants() local optim_method = optim.adadelta local train = load_point_cloud('../data/benchmark/sg28_station4_intensity_rgb_train.txt_aggregated.txt', 1000, opt) print(train.data:size()) print(train.labels:size()) local test = load_point_cloud('../data/benchmark/bildstein_station1_xyz_intensity_rgb_train.txt_aggregated.txt', 1000, opt) print(test.data:size()) print(test.labels:size()) local model local optim_state if opt.kWarmStart then print('warm start!') optim_state = torch.load(opt.kOptimStateDumpName) model = torch.load(opt.kModelDumpName) set_up_loader(optim_state.epoch, opt) else print('creating fresh new model!') optim_state = {} optim_state.epoch = 1 set_up_loader(optim_state.epoch, opt) model = define_model(opt.kSide, opt.n_outputs, opt.number_of_filters, opt.kNumberOfScales, opt.kNumberOfRotations) end local criterion = nn.ClassNLLCriterion() local criterion = criterion:cuda() criterion = cudnn.convert(criterion, cudnn) local parameters, gradParameters = model:getParameters() local batch local batch_feval = function(x) if x ~= parameters then parameters:copy(x) end local batch_inputs = batch.data:cuda() local batch_targets = batch.labels:cuda() gradParameters:zero() local batch_outputs = model:forward(batch_inputs) local batch_loss = criterion:forward(batch_outputs, batch_targets) local dloss_doutput = criterion:backward(batch_outputs, batch_targets) model:backward(batch_inputs, dloss_doutput) return batch_loss, gradParameters end optim_state.test_errors = {} optim_state.train_errors = {} torch.manualSeed(optim_state.epoch) cutorch.manualSeed(optim_state.epoch) local batch_counter = 1 set_up_infinite_streaming() while true do batch = get_next_random_batch(opt) if batch_counter % opt.kLargePrintingInterval ~= 0 then print(batch_counter) batch_counter = batch_counter + 1 local _, minibatch_loss = optim_method(batch_feval, parameters, optim_state) collectgarbage() else batch_counter = 1 torch.save(opt.kModelDumpName, model) torch.save(opt.kOptimStateDumpName, optim_state) optim_state.epoch = optim_state.epoch + 1 optim_state.train_errors[#optim_state.train_errors + 1] = calculate_error(model, train, opt) optim_state.test_errors[#optim_state.test_errors + 1] = calculate_error(model, test, opt) print(string.format("optim_state.epoch: %6s, train_error = %6.6f, test_error = %6.6f", optim_state.epoch, optim_state.train_errors[#optim_state.train_errors], optim_state.test_errors[#optim_state.test_errors])) end end
require 'torch' require 'cutorch' require 'math' require 'nn' require 'gnuplot' require 'image' require 'optim' require 'point_cloud_model_definition' require 'point_cloud_constants' require 'point_cloud_error_calculation' require 'point_cloud_loader' require 'loader_ffi' torch.manualSeed(10000) cutorch.manualSeed(10000) local opt = define_constants() local optim_method = optim.adadelta local train = load_point_cloud('../data/benchmark/sg28_station4_intensity_rgb_train.txt_aggregated.txt', 1000, opt) print(train.data:size()) print(train.labels:size()) local test = load_point_cloud('../data/benchmark/bildstein_station1_xyz_intensity_rgb_train.txt_aggregated.txt', 1000, opt) print(test.data:size()) print(test.labels:size()) local model local optim_state if opt.kWarmStart then print('warm start!') optim_state = torch.load(opt.kOptimStateDumpName) model = torch.load(opt.kModelDumpName) set_up_loader(optim_state.epoch, opt) else print('creating fresh new model!') optim_state = {} optim_state.epoch = 1 set_up_loader(optim_state.epoch, opt) model = define_model(opt.kSide, opt.n_outputs, opt.number_of_filters, opt.kNumberOfScales, opt.kNumberOfRotations) end local criterion = nn.ClassNLLCriterion() local criterion = criterion:cuda() local parameters, gradParameters = model:getParameters() local batch local batch_feval = function(x) if x ~= parameters then parameters:copy(x) end local batch_inputs = batch.data:cuda() local batch_targets = batch.labels:cuda() gradParameters:zero() local batch_outputs = model:forward(batch_inputs) local batch_loss = criterion:forward(batch_outputs, batch_targets) local dloss_doutput = criterion:backward(batch_outputs, batch_targets) model:backward(batch_inputs, dloss_doutput) return batch_loss, gradParameters end optim_state.test_errors = {} optim_state.train_errors = {} torch.manualSeed(optim_state.epoch) cutorch.manualSeed(optim_state.epoch) local batch_counter = 1 set_up_infinite_streaming() while true do batch = get_next_random_batch(opt) if batch_counter % opt.kLargePrintingInterval ~= 0 then print(batch_counter) batch_counter = batch_counter + 1 local _, minibatch_loss = optim_method(batch_feval, parameters, optim_state) collectgarbage() else batch_counter = 1 torch.save(opt.kModelDumpName, model) torch.save(opt.kOptimStateDumpName, optim_state) optim_state.epoch = optim_state.epoch + 1 optim_state.train_errors[#optim_state.train_errors + 1] = calculate_error(model, train, opt) optim_state.test_errors[#optim_state.test_errors + 1] = calculate_error(model, test, opt) print(string.format("optim_state.epoch: %6s, train_error = %6.6f, test_error = %6.6f", optim_state.epoch, optim_state.train_errors[#optim_state.train_errors], optim_state.test_errors[#optim_state.test_errors])) end end
fixed cudnn problem
fixed cudnn problem
Lua
bsd-3-clause
nsavinov/semantic3dnet,nsavinov/semantic3dnet,nsavinov/semantic3dnet,nsavinov/semantic3dnet
8fd9d00c7aad3731d4bdf8695799da39bf033ac6
src/rename.lua
src/rename.lua
local util = require "util" local M = {} M.add = function(self, name) if util.is_file(name) then self[#self+1] = { path = name } end end M.loadscript = function(self, scr) local fn, err = loadstring(scr) if not fn then return string.format("Error in Lua script: %s", err) end local rep = fn() if type(rep) ~= "function" and type(rep) ~= "table" then return "Error: Lua script must return a function or table" end self.repl = rep end M.loadsource = function(self, src) self.src = util.lines(src) end -- FIXME source should be a param, or all the other shit should not be M.match = function(self) local count = 0 local dupes = {} for i, v in ipairs(self) do -- stop processing when no self.src lines are left if self.src and not self.src[i] then self[i] = nil goto skip end local old = util.basename(v.path) local ext if self.noexts then old, ext = old:match("^(.-)%f[.%z]%.?([^.]*)$") -- thx mniip end local src = self.src and self.src[i] or old local ok, new = pcall(string.gsub, src, self.patt, self.repl) if not ok then -- pattern error return nil, "Pattern error: " .. new end new = util.join(".", new, ext) if old ~= new then if dupes[new] then return nil, "Duplicate output filename: " .. new end dupes[new] = true v.new = new count = count + 1 else v.new, v.ext = nil, nil end ::skip:: end return count end M.rename = function(self) local status = true for i, f in ipairs(self) do local ok, err = os.rename(f.path, util.join("/", util.dirname(f.path), f.new)) if ok then goto skip end status = false f.err = err self.errors[#self.errors+1] = i if self.cautious then break end ::skip:: end return status end M.reset = function(self) self.patt = nil self.repl = type(self.rep) ~= "string" and self.repl or nil end return function(...) local out = setmetatable({ errors = {} }, { __index = M }) for i = 1, select('#', ...) do out:add(select(i, ...)) end return out end
local util = require "util" local M = {} M.add = function(self, name) if util.is_file(name) then self[#self+1] = { path = name } end end M.loadscript = function(self, scr) local fn, err = loadstring(scr) if not fn then return string.format("Error in Lua script: %s", err) end local rep = fn() if type(rep) ~= "function" and type(rep) ~= "table" then return "Error: Lua script must return a function or table" end self.repl = rep end M.loadsource = function(self, src) self.src = util.lines(src) end M.match = function(self) local count = 0 local dupes = {} for i, v in ipairs(self) do -- stop processing when no self.src lines are left if self.src and not self.src[i] then self[i] = nil goto skip end local old = util.basename(v.path) local ext if self.noexts then old, ext = old:match("^(.-)%f[.%z]%.?([^.]*)$") -- thx mniip end local src = self.src and self.src[i] or old local ok, new = pcall(string.gsub, src, self.patt, self.repl) if not ok then -- pattern error return nil, "Pattern error: " .. new end new = util.join(".", new, ext) if old ~= new then if dupes[new] then return nil, "Duplicate output filename: " .. new end dupes[new] = true v.new = new count = count + 1 else v.new, v.ext = nil, nil end ::skip:: end return count end M.rename = function(self) local status = true for i, f in ipairs(self) do local ok, err = os.rename(f.path, util.join("/", util.dirname(f.path), f.new)) if ok then goto skip end status = false f.err = err self.errors[#self.errors+1] = i if self.cautious then break end ::skip:: end return status end M.reset = function(self) self.patt = nil self.repl = type(self.repl) ~= "string" and self.repl or nil end return function(...) local out = setmetatable({ errors = {} }, { __index = M }) for i = 1, select('#', ...) do out:add(select(i, ...)) end return out end
typo fix
typo fix
Lua
mit
fur-q/mfr,fur-q/mfr
7a6cf4f244120683c2060eaa325666ac5831f48d
Sum.lua
Sum.lua
local Sum, parent = torch.class('nn.Sum', 'nn.Module') function Sum:__init(dimension) parent.__init(self) dimension = dimension or 1 self.dimension = dimension end function Sum:updateOutput(input) if type(self.output) == 'number' then self.output = input.new() end self.output:sum(input, self.dimension) if self.output:nDimension() > 1 then self.output = self.output:select(self.dimension, 1) end return self.output end function Sum:updateGradInput(input, gradOutput) local size = gradOutput:size():totable() local stride = gradOutput:stride():totable() if input:nDimension() > 1 then table.insert(size, self.dimension, input:size(self.dimension)) table.insert(stride, self.dimension, 0) else size[1] = input:size(1) stride[1] = 0 end self.gradInput:set(gradOutput:storage(), 1, torch.LongStorage(size), torch.LongStorage(stride)) return self.gradInput end
local Sum, parent = torch.class('nn.Sum', 'nn.Module') function Sum:__init(dimension) parent.__init(self) dimension = dimension or 1 self.dimension = dimension end function Sum:updateOutput(input) if type(self.output) == 'number' then self.output = input.new() end self.output:sum(input, self.dimension) if self.output:nDimension() > 1 then self.output = self.output:select(self.dimension, 1) end return self.output end function Sum:updateGradInput(input, gradOutput) -- zero-strides dont work with MKL/BLAS, so -- dont set self.gradInput to zero-stride tensor. -- Instead, do a deepcopy local size = input:size() size[self.dimension] = 1 gradOutput = gradOutput:view(size) self.gradInput:resizeAs(input) self.gradInput:copy(gradOutput:expandAs(input)) return self.gradInput end
[Torch] Fix `Sum:updateGradInput()` in the zero-stride case.
[Torch] Fix `Sum:updateGradInput()` in the zero-stride case.
Lua
bsd-3-clause
eriche2016/nn,jzbontar/nn,hughperkins/nn,colesbury/nn,EnjoyHacking/nn,andreaskoepf/nn,aaiijmrtt/nn,Aysegul/nn,karpathy/nn,kmul00/nn,zchengquan/nn,PraveerSINGH/nn,ominux/nn,diz-vara/nn,sbodenstein/nn,sagarwaghmare69/nn,mlosch/nn,apaszke/nn,GregSatre/nn,lukasc-ch/nn,joeyhng/nn,witgo/nn,adamlerer/nn,lvdmaaten/nn,rotmanmi/nn,zhangxiangxiao/nn,fmassa/nn,PierrotLC/nn,Jeffyrao/nn,noa/nn,forty-2/nn,mys007/nn,clementfarabet/nn,jhjin/nn,elbamos/nn,Djabbz/nn,eulerreich/nn,jonathantompson/nn,ivendrov/nn,szagoruyko/nn,boknilev/nn,caldweln/nn,Moodstocks/nn,xianjiec/nn,rickyHong/nn_lib_torch,davidBelanger/nn,LinusU/nn,douwekiela/nn,hery/nn,bartvm/nn,nicholas-leonard/nn,abeschneider/nn,vgire/nn
cfade58e6822ac7a636dfcf5c42299a4afde39ad
dotfiles/hammerspoon/init.lua
dotfiles/hammerspoon/init.lua
-- constants local applications = {"Google Chrome", "Mail", "Calendar", "Skype", "iTerm"} local laptopScreen = "Color LCD" local windowLayout = { {"Google Chrome", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Mail", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Calendar", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Skype", nil, laptopScreen, hs.layout.right50, nil, nil}, {"iTerm", nil, laptopScreen, hs.layout.maximized, nil, nil}, } switchableHotkeys = {} ----------------------------------------------- -- {"ctrl"} i to show window hints ----------------------------------------------- hs.hints.style = 'vimperator' table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, "i", function() hs.hints.windowHints() end)) ----------------------------------------------- -- {"ctrl"} hjkl to switch window focus ----------------------------------------------- table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'k', function() hs.window.focusedWindow():focusWindowNorth() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'j', function() hs.window.focusedWindow():focusWindowSouth() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'l', function() hs.window.focusedWindow():focusWindowEast() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'h', function() hs.window.focusedWindow():focusWindowWest() end)) if (hs.window.focusedWindow() and hs.window.focusedWindow():isFullScreen()) then hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:disable() end) end -- PUT ALL WINDOWS WHERE THEY BELONG function applyLayout() hs.layout.apply(windowLayout) for _, window in pairs(hs.window.allWindows()) do if (window:application():title() == "iTerm") then if not window:isFullScreen() then window:toggleFullScreen() end end end end -- PUT ALL WINDOWS WHERE THEY BELONG WHEN AN APPLICATION LAUNCHES function applicationWatcherFun(appName, eventType, appObject) if (eventType == hs.application.watcher.activated) then if (appName == "Finder") then -- Bring all Finder windows forward when one gets activated appObject:selectMenuItem({"Window", "Bring All to Front"}) end if (appObject and appObject:focusedWindow() and appObject:focusedWindow():isFullScreen()) then hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:disable() end) else hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:enable() end) end end if (eventType == hs.application.watcher.launching) then for _, application in pairs(applications) do if (appName == application) then applyLayout() end end end end local appWatcher = hs.application.watcher.new(applicationWatcherFun) appWatcher:start() -- PUT ALL WINDOWS WHERE THEY BELONG WHEN SCREENS CHANGE function screenWatcherFun() applyLayout() end local screenWatcher = hs.screen.watcher.new(screenWatcherFun) screenWatcher:start() -- AUTOTEST BINGO ON CHANGES for _, service in pairs({"bingo", "tumbler", "corsa", "kino", "stoker", "chemist", "polis", "lib34", "minitel"}) do hs.pathwatcher.new(os.getenv("HOME") .. "/bingo/" .. service, function(files) for _, file in pairs(files) do if string.find(file, '.py') and not string.find(file, '.pyc') then io.popen(os.getenv("SHELL") .. " -l -i -c 'tmux send -Rt 2 \"make test-" .. service .. "\" enter'", 'r') return end end end):start() end -- AUTORELOAD CONFIG 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() end end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start() -- HOTKEY REPOSITION WINDOWS hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() applyLayout() end) hs.alert.show("Config loaded")
-- constants local applications = {"Google Chrome", "Mail", "Calendar", "Skype", "iTerm"} local laptopScreen = "Color LCD" local windowLayout = { {"Google Chrome", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Mail", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Calendar", nil, laptopScreen, hs.layout.left50, nil, nil}, {"Skype", nil, laptopScreen, hs.layout.right50, nil, nil}, {"iTerm", nil, laptopScreen, hs.layout.maximized, nil, nil}, } switchableHotkeys = {} ----------------------------------------------- -- {"ctrl"} i to show window hints ----------------------------------------------- hs.hints.style = 'vimperator' table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, "i", function() hs.hints.windowHints() end)) ----------------------------------------------- -- {"ctrl"} hjkl to switch window focus ----------------------------------------------- table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'k', function() hs.window.focusedWindow():focusWindowNorth() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'j', function() hs.window.focusedWindow():focusWindowSouth() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'l', function() hs.window.focusedWindow():focusWindowEast() end)) table.insert(switchableHotkeys, hs.hotkey.bind({"ctrl"}, 'h', function() hs.window.focusedWindow():focusWindowWest() end)) if (hs.window.focusedWindow() and hs.window.focusedWindow():isFullScreen()) then hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:disable() end) end -- PUT ALL WINDOWS WHERE THEY BELONG function applyLayout() hs.layout.apply(windowLayout) for _, window in pairs(hs.window.allWindows()) do if (window:application():title() == "iTerm") then if not window:isFullScreen() then window:toggleFullScreen() end end end -- restart nexTab for _, application in pairs(hs.application.runningApplications()) do if (application:title() == 'nexTab') then application:kill() hs.application.launchOrFocus('nexTab') end end end -- PUT ALL WINDOWS WHERE THEY BELONG WHEN AN APPLICATION LAUNCHES function applicationWatcherFun(appName, eventType, appObject) if (eventType == hs.application.watcher.activated) then if (appName == "Finder") then -- Bring all Finder windows forward when one gets activated appObject:selectMenuItem({"Window", "Bring All to Front"}) end if (appObject and appObject:focusedWindow() and appObject:focusedWindow():isFullScreen()) then hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:disable() end) else hs.fnutils.each(switchableHotkeys, function(hotkey) hotkey:enable() end) end end if (eventType == hs.application.watcher.launching) then for _, application in pairs(applications) do if (appName == application) then applyLayout() end end end end local appWatcher = hs.application.watcher.new(applicationWatcherFun) appWatcher:start() -- PUT ALL WINDOWS WHERE THEY BELONG WHEN SCREENS CHANGE function screenWatcherFun() applyLayout() end local screenWatcher = hs.screen.watcher.new(screenWatcherFun) screenWatcher:start() -- AUTOTEST BINGO ON CHANGES for _, service in pairs({"bingo", "tumbler", "corsa", "kino", "stoker", "chemist", "polis", "lib34", "minitel"}) do hs.pathwatcher.new(os.getenv("HOME") .. "/bingo/" .. service, function(files) for _, file in pairs(files) do if string.find(file, '.py') and not string.find(file, '.pyc') then io.popen(os.getenv("SHELL") .. " -l -i -c 'tmux send -Rt 2 \"make test-" .. service .. "\" enter'", 'r') return end end end):start() end -- AUTORELOAD CONFIG 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() end end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start() -- HOTKEY REPOSITION WINDOWS hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() applyLayout() end) hs.alert.show("Config loaded")
restart nexTab on screen change (fixes lots of problems)
restart nexTab on screen change (fixes lots of problems)
Lua
mit
wolfgangpfnuer/dotfiles,wolfgangpfnuer/dotfiles,wolfgangpfnuer/dotfiles
164e35a5fd175d69631d596d322154c6dd77fff2
cherry/store/apple.lua
cherry/store/apple.lua
-------------------------------------------------------------------------------- local analytics = require 'cherry.libs.analytics' -------------------------------------------------------------------------------- local AppleShop = {} -------------------------------------------------------------------------------- function AppleShop:getProductId(nbGems) local id = 'uralys.kodo.gems.' .. nbGems if (nbGems == 100) then id = id .. 'w' end -- ^%$# review + uniqueid return id end function AppleShop:getGemsFromId(id) local nbGems = id:split('uralys.kodo.gems.')[2]:split('w')[1] return tonumber(nbGems) end -------------------------------------------------------------------------------- function AppleShop:initialize() _G.log('[shop][initialize] plugging Apple appStore...') local function storeTransaction(event) local transaction = event.transaction _G.log( '[shop] --> callback storeTransaction | transaction.state:' .. transaction.state ) native.setActivityIndicator(false) if (transaction.state == 'purchased' or transaction.state == 'restored') then local id = transaction.productIdentifier self.buying = false self.nbGemsToAdd = self.getGemsFromId(id) self.yFrom = self.yFrom or self.TOP -- on restore no buy button was pressed analytics.event('shop', transaction.state, id) self:addGems() elseif (transaction.state == 'cancelled') then analytics.event('shop', 'cancelled', App.user:deviceId()) self:cancelTransaction(transaction) elseif (transaction.state == 'failed') then analytics.event( 'shop', 'failed', 'gems: ' .. self.nbGemsToAdd .. ' | error:[' .. transaction.errorString .. '] user:' .. App.user:deviceId() ) self:cancelTransaction(transaction) else local unknownType = transaction and transaction.state or 'no-state' analytics.event( 'shop', 'unknown-transaction-' .. unknownType, App.user:deviceId() ) end self.appStore.finishTransaction(transaction) end native.setActivityIndicator(true) self.appStore = require('store') self.appStore.init(storeTransaction) native.setActivityIndicator(false) self:loadProducts() end -------------------------------------------------------------------------------- function AppleShop:buy(productId) native.setActivityIndicator(true) _G.log('[shop][buy] apple PURCHASING...[' .. productId .. ']') self.appStore.purchase(productId) end -------------------------------------------------------------------------------- return AppleShop
-------------------------------------------------------------------------------- local analytics = require 'cherry.libs.analytics' -------------------------------------------------------------------------------- local AppleShop = {} -------------------------------------------------------------------------------- function AppleShop:getProductId(nbGems) local id = 'uralys.kodo.gems.' .. nbGems if (nbGems == 100) then id = id .. 'w' end -- ^%$# review + uniqueid return id end function AppleShop:getGemsFromId(id) local nbGems = id:split('uralys.kodo.gems.')[2]:split('w')[1] return tonumber(nbGems) end -------------------------------------------------------------------------------- function AppleShop:initialize() _G.log('[shop][initialize] plugging Apple appStore...') local function storeTransaction(event) local transaction = event.transaction _G.log( '[shop] --> callback storeTransaction | transaction.state:' .. transaction.state ) native.setActivityIndicator(false) if (transaction.state == 'purchased' or transaction.state == 'restored') then local id = transaction.productIdentifier _G.log('--->>> purchased: ' .. id) self.buying = false self.nbGemsToAdd = self:getGemsFromId(id) self.yFrom = self.yFrom or self.TOP -- on restore no buy button was pressed analytics.event('shop', transaction.state, id) self:addGems() elseif (transaction.state == 'cancelled') then _G.log('--->>> cancelled') analytics.event('shop', 'cancelled', App.user:deviceId()) self:cancelTransaction(transaction) elseif (transaction.state == 'failed') then _G.log('--->>> failed') local info = 'gems: ' .. self.nbGemsToAdd .. ' | error:[' .. transaction.errorString .. '] user:' .. App.user:deviceId() _G.log({info}) analytics.event('shop', 'failed', info) self:cancelTransaction(transaction) else local unknownType = transaction and transaction.state or 'no-state' _G.log('--->>> unknownType:' .. unknownType) analytics.event( 'shop', 'unknown-transaction-' .. unknownType, App.user:deviceId() ) end self.appStore.finishTransaction(transaction) end self.appStore = require('store') self.appStore.init(storeTransaction) self:loadProducts() end -------------------------------------------------------------------------------- function AppleShop:buy(productId) native.setActivityIndicator(true) _G.log('[shop][buy] apple PURCHASING...[' .. productId .. ']') self.appStore.purchase(productId) end -------------------------------------------------------------------------------- return AppleShop
fixed apple store
fixed apple store
Lua
bsd-3-clause
chrisdugne/cherry
193c4263e4527c28ff9c342edf6e0e2738d0e363
bin/stream_new_against_core.lua
bin/stream_new_against_core.lua
#!/usr/bin/env gt --[[ Copyright (c) 2015 Sascha Steinbiss <ss34@sanger.ac.uk> Copyright (c) 2015 Genome Research Ltd Permission to use, copy, modify, and 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. ]] package.path = gt.script_dir .. "/?.lua;" .. package.path require("lib") local json = require ("dkjson") function usage() io.stderr:write(string.format("Usage: %s <in.gff3> <in.protein.fasta> " .. "<refdir> <speciesprefix> " .. "<reference prefix>\n" , arg[0])) os.exit(1) end if #arg < 5 then usage() end ingff = arg[1] inprots = arg[2] refdir = arg[3] --refgroup = arg[4] speciesprefix = arg[4] refprefix = arg[5] -- load reference info local reffile = io.open(refdir .. "/references.json", "rb") if not reffile then error("invalid reference directory '" .. refdir .. "' -- missing references.json file") end local refcontent = reffile:read("*all") reffile:close() refs = json.decode(refcontent) -- check for reference prefix if not refs.species[refprefix] then error("invalid reference prefix '" .. refprefix .. "' not found in reference directory " .. refdir) end -- parse clusters clindex, clusters = get_clusters(refdir .. "/_all/all_orthomcl.out") -- global core clusters, for tree drawing global_core_clusters = {} -- group core clusters, for gene loss/gain comparison group_core_clusters = {} -- determine core for clustername,cluster in pairs(clusters) do -- collect core clusters from ALL references local is_global_core = true for sp,_ in pairs(refs.species) do if is_global_core and not cluster.specidx[sp] then is_global_core = false end end if is_global_core then table.insert(global_core_clusters, cluster) end for refgroup,_ in pairs(refs.groups) do if not group_core_clusters[refgroup] then group_core_clusters[refgroup] = {} end -- collect group core clusters (those with all species in group) local is_group_core = true for _,sp in ipairs(refs.groups[refgroup]) do if is_group_core and not cluster.specidx[sp] then is_group_core = false end end if is_group_core then table.insert(group_core_clusters[refgroup], cluster) end end end cv = gt.custom_visitor_new() singletons = {} function cv:visit_feature(fn) for n in fn:get_children() do if n:get_type() == 'polypeptide' then local orths = n:get_attribute("orthologous_to") local dfrom = n:get_attribute("Derives_from") local found = false local groups = {} -- collect orthologs for this gene product if orths then for _,orth in ipairs(split(orths,",")) do if clindex[orth] then table.insert(groups, clindex[orth]) end end end -- collect singletons if not n:get_attribute("ortholog_cluster") then singletons[dfrom] = true end if #groups > 0 then groups = table_unique(groups) -- only handle genes with all orthologs in the same cluster if #groups == 1 and dfrom then -- add this gene to cluster local cluster = groups[1] table.insert(cluster.members, {dfrom, speciesprefix}) table.insert(cluster.species, speciesprefix) cluster.specidx[speciesprefix] = true end end end end return 0 end -- visitor to output CC roots with members in its 'nididx' field to a text file -- vor circos visualization circos_visitor = gt.custom_visitor_new() circos_visitor.color = 'green' function circos_visitor:visit_feature(fn) for n in fn:get_children() do local nid = n:get_attribute("ID") if nid and self.nididx[nid] then self.io:write(fn:get_seqid() .. " " .. fn:get_range():get_start() .. " " .. fn:get_range():get_end() .. " color=" .. self.color .. "\n") end end end -- perform core comparison local vstream = visitor_stream_new(gt.gff3_in_stream_new_sorted(ingff), cv) local gn = vstream:next_tree() while (gn) do gn = vstream:next_tree() end -- extract core set for tree drawing prots = {} specseqs = {} for s,v in pairs(refs.species) do local hdr, seq = get_fasta_nosep(refdir .. "/" .. s .. "/proteins.fasta") prots[s] = seq specseqs[s] = "" end _, nseq = get_fasta_nosep(inprots) prots[speciesprefix] = nseq specseqs[speciesprefix] = "" i = 0 treegenes = io.open("tree_selection.genes", "w+") for _,cl in ipairs(global_core_clusters) do local seen_species = {} for _,m in ipairs(cl.members) do if not seen_species[m[2]] then seen_species[m[2]] = true local seq = prots[m[2]][m[1]] treegenes:write(m[1] .. "\t") specseqs[m[2]] = specseqs[m[2]] .. seq end end treegenes:write("\n") i = i + 1 if i == 50 then break end end treeout = io.open("tree_selection.fasta", "w+") for s,seq in pairs(specseqs) do treeout:write(">" .. s .. "\n") print_max_width(seq, treeout, 80) end -- searching for global core clusters with missing members in new species missing = {} local global_outfile = io.open("core_comparison.txt", "w+") for _,cluster in ipairs(global_core_clusters) do if not cluster.specidx[speciesprefix] then for _, v in ipairs(cluster.members) do global_outfile:write("global\t" .. cluster.name .. "\t" .. v[1] .. "\t" .. v[2] .. "\n") if refprefix == v[2] then missing[v[1]] = true end end end end -- searching for group core clusters with missing members in new species for refgroup,members in pairs(refs.groups) do for _,cluster in ipairs(group_core_clusters[refgroup]) do if not cluster.specidx[speciesprefix] then for _, v in ipairs(cluster.members) do global_outfile:write(refgroup .. "\t" .. cluster.name .. "\t" .. v[1] .. "\t" .. v[2] .. "\n") end end end end -- circos output local stream = visitor_stream_new(gt.gff3_in_stream_new_sorted(refs.species[refprefix].gff), circos_visitor) circos_visitor.nididx = missing circos_visitor.io = io.open("core_comp_circos.txt", "w+") local gn = stream:next_tree() while (gn) do gn = stream:next_tree() end local stream = visitor_stream_new(gt.gff3_in_stream_new_sorted(ingff), circos_visitor) circos_visitor.nididx = singletons circos_visitor.color = 'black' circos_visitor.io = io.open("core_comp_circos.txt", "w+") local gn = stream:next_tree() while (gn) do gn = stream:next_tree() end
#!/usr/bin/env gt --[[ Copyright (c) 2015 Sascha Steinbiss <ss34@sanger.ac.uk> Copyright (c) 2015 Genome Research Ltd Permission to use, copy, modify, and 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. ]] package.path = gt.script_dir .. "/?.lua;" .. package.path require("lib") local json = require ("dkjson") function usage() io.stderr:write(string.format("Usage: %s <in.gff3> <in.protein.fasta> " .. "<refdir> <speciesprefix> " .. "<reference prefix>\n" , arg[0])) os.exit(1) end if #arg < 5 then usage() end ingff = arg[1] inprots = arg[2] refdir = arg[3] --refgroup = arg[4] speciesprefix = arg[4] refprefix = arg[5] -- load reference info local reffile = io.open(refdir .. "/references.json", "rb") if not reffile then error("invalid reference directory '" .. refdir .. "' -- missing references.json file") end local refcontent = reffile:read("*all") reffile:close() refs = json.decode(refcontent) -- check for reference prefix if not refs.species[refprefix] then error("invalid reference prefix '" .. refprefix .. "' not found in reference directory " .. refdir) end -- parse clusters clindex, clusters = get_clusters(refdir .. "/_all/all_orthomcl.out") -- global core clusters, for tree drawing global_core_clusters = {} -- group core clusters, for gene loss/gain comparison group_core_clusters = {} -- determine core for clustername,cluster in pairs(clusters) do -- collect core clusters from ALL references local is_global_core = true for sp,_ in pairs(refs.species) do if is_global_core and not cluster.specidx[sp] then is_global_core = false end end if is_global_core then table.insert(global_core_clusters, cluster) end for refgroup,_ in pairs(refs.groups) do if not group_core_clusters[refgroup] then group_core_clusters[refgroup] = {} end -- collect group core clusters (those with all species in group) local is_group_core = true for _,sp in ipairs(refs.groups[refgroup]) do if is_group_core and not cluster.specidx[sp] then is_group_core = false end end if is_group_core then table.insert(group_core_clusters[refgroup], cluster) end end end cv = gt.custom_visitor_new() singletons = {} function cv:visit_feature(fn) for n in fn:get_children() do if n:get_type() == 'polypeptide' then local orths = n:get_attribute("orthologous_to") local dfrom = n:get_attribute("Derives_from") local found = false local groups = {} -- collect orthologs for this gene product if orths then for _,orth in ipairs(split(orths,",")) do if clindex[orth] then table.insert(groups, clindex[orth]) end end end -- collect singletons if not n:get_attribute("ortholog_cluster") then singletons[dfrom] = true end if #groups > 0 then groups = table_unique(groups) -- only handle genes with all orthologs in the same cluster if #groups == 1 and dfrom then -- add this gene to cluster local cluster = groups[1] table.insert(cluster.members, {dfrom, speciesprefix}) table.insert(cluster.species, speciesprefix) cluster.specidx[speciesprefix] = true end end end end return 0 end -- visitor to output CC roots with members in its 'nididx' field to a text file -- vor circos visualization circos_visitor = gt.custom_visitor_new() circos_visitor.color = 'green' function circos_visitor:visit_feature(fn) for n in fn:get_children() do local nid = n:get_attribute("ID") if nid and self.nididx[nid] then self.io:write(fn:get_seqid() .. " " .. fn:get_range():get_start() .. " " .. fn:get_range():get_end() .. " color=" .. self.color .. "\n") end end end -- perform core comparison local vstream = visitor_stream_new(gt.gff3_in_stream_new_sorted(ingff), cv) local gn = vstream:next_tree() while (gn) do gn = vstream:next_tree() end -- extract core set for tree drawing prots = {} specseqs = {} for s,v in pairs(refs.species) do local hdr, seq = get_fasta_nosep(refdir .. "/" .. s .. "/proteins.fasta") prots[s] = seq specseqs[s] = "" end _, nseq = get_fasta_nosep(inprots) prots[speciesprefix] = nseq specseqs[speciesprefix] = "" i = 0 treegenes = io.open("tree_selection.genes", "w+") for _,cl in ipairs(global_core_clusters) do local seen_species = {} for _,m in ipairs(cl.members) do if not seen_species[m[2]] then seen_species[m[2]] = true local seq = prots[m[2]][m[1]] treegenes:write(m[1] .. "\t") specseqs[m[2]] = specseqs[m[2]] .. seq end end treegenes:write("\n") i = i + 1 if i == 50 then break end end treeout = io.open("tree_selection.fasta", "w+") for s,seq in pairs(specseqs) do treeout:write(">" .. s .. "\n") print_max_width(seq, treeout, 80) end -- searching for global core clusters with missing members in new species missing = {} local global_outfile = io.open("core_comparison.txt", "w+") for _,cluster in ipairs(global_core_clusters) do if not cluster.specidx[speciesprefix] then for _, v in ipairs(cluster.members) do global_outfile:write("global\t" .. cluster.name .. "\t" .. v[1] .. "\t" .. v[2] .. "\n") if refprefix == v[2] then missing[v[1]] = true end end end end -- searching for group core clusters with missing members in new species for refgroup,members in pairs(refs.groups) do for _,cluster in ipairs(group_core_clusters[refgroup]) do if not cluster.specidx[speciesprefix] then for _, v in ipairs(cluster.members) do global_outfile:write(refgroup .. "\t" .. cluster.name .. "\t" .. v[1] .. "\t" .. v[2] .. "\n") end end end end -- circos output local stream = visitor_stream_new(gt.gff3_in_stream_new_sorted(refdir .. "/" ... refprefix .. "/annotation.gff3"), circos_visitor) circos_visitor.nididx = missing circos_visitor.io = io.open("core_comp_circos.txt", "w+") local gn = stream:next_tree() while (gn) do gn = stream:next_tree() end local stream = visitor_stream_new(gt.gff3_in_stream_new_sorted(ingff), circos_visitor) circos_visitor.nididx = singletons circos_visitor.color = 'black' circos_visitor.io = io.open("core_comp_circos.txt", "w+") local gn = stream:next_tree() while (gn) do gn = stream:next_tree() end
fix reference input
fix reference input
Lua
isc
satta/companion,satta/annot-nf,sanger-pathogens/companion,sanger-pathogens/annot-nf,sanger-pathogens/companion,fw1121/annot-nf,sanger-pathogens/annot-nf,fw1121/annot-nf,satta/companion,fw1121/annot-nf,satta/annot-nf,sanger-pathogens/annot-nf,satta/companion,sanger-pathogens/companion,satta/annot-nf
b56023113bdc2957a87409c4985c524645c17425
src/common/http.lua
src/common/http.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Http = newclass "Http" function Http:init(loader) self.loader = loader end function Http:get(url, headers, extra) local response, result, code = http.get(url, { headers = self:_convertHeaders(headers) }) return response end function Http:download(url, outFile, headers, showProgress) local mayWrite = true function progress(total, current) local ratio = current / total; ratio = math.min(math.max(ratio, 0), 1); local percent = math.floor(ratio * 100); if mayWrite then io.write("\rDownload progress (" .. percent .. "%/100%)") end if percent == 100.0 and mayWrite then io.write("\n") mayWrite = false end end local response, code = http.download(url, outFile, { headers = self:_convertHeaders(headers), progress = iif(showProgress, progress, nil) }) return response end function Http:downloadFromArchive(url, pattern, iszip) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) if url:contains(".zip") or iszip then return self:downloadFromZip(url, pattern) end return self:downloadFromTarGz(url, pattern) end function Http:downloadFromZipTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) destination = iif(destination == nil or type(destination) == "boolean", path.join(self.loader.temp, os.uuid()), destination) local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip") self:download(url, zipFile) zip.extract(zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromTarGzTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz") self:download(url, zipFile) os.executef("tar xzf %s -C %s", zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromZip(url, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromZipTo(url, dest, pattern) end function Http:downloadFromTarGz(url, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromTarGzTo(url, dest, pattern) end function Http:_convertHeaders(headers) headers = iif(headers == nil, { }, headers) if not zpm.util.isArray(t) then local nheaders = {} for k, v in pairs(headers) do table.insert(nheaders, string.format("%s: %s", k, v)) end return nheaders end return headers end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Http = newclass "Http" function Http:init(loader) self.loader = loader end function Http:get(url, headers, extra) local response, result, code = http.get(url, { headers = self:_convertHeaders(headers) }) return response end function Http:download(url, outFile, headers, showProgress) local mayWrite = true function progress(total, current) local ratio = current / total; ratio = math.min(math.max(ratio, 0), 1); local percent = math.floor(ratio * 100); if mayWrite then io.write("\rDownload progress (" .. percent .. "%/100%)") end if percent == 100.0 and mayWrite then io.write("\n") mayWrite = false end end local response, code = http.download(url, outFile, { headers = self:_convertHeaders(headers), progress = iif(showProgress, progress, nil) }) return response end function Http:downloadFromArchive(url, pattern, iszip) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) if url:contains(".zip") or iszip then return self:downloadFromZip(url, pattern) end return self:downloadFromTarGz(url, pattern) end function Http:downloadFromZipTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) destination = iif(destination == nil or type(destination) == "boolean", path.join(self.loader.temp, os.uuid()), destination) local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip") self:download(url, zipFile) zip.extract(zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromTarGzTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) destination = iif(destination == nil or type(destination) == "boolean", path.join(self.loader.temp, os.uuid()), destination) local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz") self:download(url, zipFile) os.executef("tar xzf %s -C %s", zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromZip(url, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromZipTo(url, dest, pattern) end function Http:downloadFromTarGz(url, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromTarGzTo(url, dest, pattern) end function Http:_convertHeaders(headers) headers = iif(headers == nil, { }, headers) if not zpm.util.isArray(t) then local nheaders = {} for k, v in pairs(headers) do table.insert(nheaders, string.format("%s: %s", k, v)) end return nheaders end return headers end
Fix tar.gz destination
Fix tar.gz destination
Lua
mit
Zefiros-Software/ZPM
4fa52d07f34c7199a2da6114b5f78ea3f37f0e69
includes/theme.lua
includes/theme.lua
local theme_name local slash, tinsert, tconcat = settings.slash, table.insert, table.concat local pcall, settings, empty = pcall, settings, seawolf.variable.empty local assert, error, setfenv = assert, error, setfenv local currentdir = lfs.currentdir() .. slash local base, l = base, l if settings.mobile and (mobile.detect.isMobile() or _SERVER 'HTTP_HOST' == settings.mobile.domain_name) then theme_name = settings.mobile.theme else theme_name = settings.theme end function theme_print(v) if type(v) == 'function' then v() else return print(v) end end --[[ Render theme template. ]] local function theme_render(f, env) file = ('%sthemes%s%s%s%s.tpl.html'):format(currentdir, slash, theme_name, slash, f) local attr, err = lfs.attributes(file) if err then return ("template '%s': %s"):format(file, err) end if attr ~= nil and attr.mode == 'file' then -- read file contents local fh = assert(io.open(file)) local src = ('print [[%s]]'):format(fh:read('*a')) fh:close() -- translate lua template tag src = src:gsub('(<%?lua)(.-)(%?>)', "]]; %2 print[[") -- load source code local prog, err = loadstring(src, file) if not prog then return ("template '%s': %s"):format(file, err) end -- extend env if not empty(settings.template_env) then for k, v in pairs(settings.template_env) do if env[k] == nil then env[k] = v end end end -- jail env.print = theme_print env.settings = settings env.echo = echo env.base = base env.theme = theme env.mobile = mobile env.print_t = print_t env.print_f = print_f env.debug = debug env.l = l env.arg = arg env.request_path = request_path env.path_to_theme = path_to_theme env.pairs = pairs env._SERVER = _SERVER env.mobile = mobile setfenv(prog, env) -- execute local status, result = pcall(prog) if status then return '' -- TODO: return a buffered output of the template else return ("template '%s': %s"):format(file, result) end end end --[[ Execute theme function. ]] local function theme_execute(f, arg) local status, result = pcall(theme[f], arg) if status then if type(result) == 'function' then status, result = pcall(result) if status then return result end else return result end end return ("theme function %s: '%s'"):format(f, result) end --[[ Theme metatable. ]] setmetatable(theme, { __call = function(t, arg) if not arg then arg = {} end local f = arg[1] arg[1] = nil -- clean-up theme environment if t[f] == nil then return theme_render(f, arg) else return theme_execute(f, arg) end end }) --[[ Translate given table key-value pairs to attr="value". ]] function render_attributes(options, default_options) if default_options == nil then default_options = {} end -- Merge default_options into options if type(options) ~= 'table' then options = default_options else for k, v in pairs(default_options) do if options[k] == nil then options[k] = default_options[k] end end end local attr = {} for k, v in pairs(options) do tinsert(attr, ('%s="%s"'):format(k, v)) end return tconcat(attr, " ") end --[[ Translate given table key-value pairs to "val1 val2". ]] function render_classes(classes, default_classes) if default_classes == nil then default_classes = {} end if type(classes) ~= 'table' then classes = default_classes else for k, v in pairs(default_classes) do if classes[k] == nil and not empty(classes[k]) then classes[k] = default_classes[k] end end end local output = {} for k, _ in pairs(classes) do tinsert(output, k) end return tconcat(output, '') end --[[ Print output of given theme function and parameters. ]] function print_t(...) print(theme(...) or '') end --[[ Print output of given theme function and parameters. ]] function print_f(text, ...) print(text:format(...)) end function theme.json(variables) local json = require 'dkjson' local content = variables.content header('content-type', 'application/json; charset=utf-8') theme_print(json.encode(content)) end function path_to_theme() return ('themes/%s'):format(theme_name) end --[[ Anchor theme function. ]] function theme.a(variables) if variables == nil then variables = {} end local attributes = variables.attributes variables.attributes = nil -- Support HTML5 download attribute local download = attributes.download attributes.download = nil if download == true then download = ' download' elseif type(download) == 'string' then download = (' download="%s"'):format(download) end return ('<a href="%s"%s %s>%s</a>'):format(variables.route, download or '', render_attributes(attributes), variables.text) end --[[ Image theme function. ]] function theme.img(variables) local path = variables.path or '' local options = variables.options if options and options.external then options.external = nil else path = base.route .. path end return ('<img src="%s" %s />'):format(path, render_attributes(options)) end --[[ Logo theme function. ]] function theme.logo() local site = settings.site local logo_path = ('%s/%s'):format(path_to_theme(), site.logo_path) return l(theme{'img', path = logo_path, options = {alt = site.logo_title, title = site.logo_title, border = 0}}, '', {absolute = true, attributes = {id = 'logo'}}) end --[[ Items list function theme function. ]] function theme.item_list(variables) if variables == nil then variables = {} end local list = variables.list variables.list = nil local output = {('<ul%s>'):format(list ~= nil and ' ' .. render_attributes(variables) or '')} for _, v in pairs(list) do tinsert(output, ('<li>%s</li>'):format(v)) end tinsert(output, '</ul>') return tconcat(output) end
local theme_name local slash, tinsert, tconcat = settings.slash, table.insert, table.concat local pcall, settings, empty = pcall, settings, seawolf.variable.empty local assert, error, setfenv = assert, error, setfenv local currentdir = lfs.currentdir() .. slash local base, l = base, l if settings.mobile and (mobile.detect.isMobile() or _SERVER 'HTTP_HOST' == settings.mobile.domain_name) then theme_name = settings.mobile.theme else theme_name = settings.theme end function theme_print(v) if type(v) == 'function' then v() else return print(v) end end --[[ Render theme template. ]] local function theme_render(f, env) file = ('%sthemes%s%s%s%s.tpl.html'):format(currentdir, slash, theme_name, slash, f) local attr, err = lfs.attributes(file) if err then return ("template '%s': %s"):format(file, err) end if attr ~= nil and attr.mode == 'file' then -- read file contents local fh = assert(io.open(file)) local src = ('print [[%s]]'):format(fh:read('*a')) fh:close() -- translate lua template tag src = src:gsub('(<%?lua)(.-)(%?>)', "]]; %2 print[[") -- load source code local prog, err = loadstring(src, file) if not prog then return ("template '%s': %s"):format(file, err) end -- extend env if not empty(settings.template_env) then for k, v in pairs(settings.template_env) do if env[k] == nil then env[k] = v end end end -- jail env.print = theme_print env.settings = settings env.echo = echo env.base = base env.theme = theme env.mobile = mobile env.print_t = print_t env.print_f = print_f env.debug = debug env.l = l env.arg = arg env.request_path = request_path env.path_to_theme = path_to_theme env.pairs = pairs env._SERVER = _SERVER env.mobile = mobile setfenv(prog, env) -- execute local status, result = pcall(prog) if status then return '' -- TODO: return a buffered output of the template else return ("template '%s': %s"):format(file, result) end end end --[[ Execute theme function. ]] local function theme_execute(f, arg) local status, result = pcall(theme[f], arg) if status then if type(result) == 'function' then status, result = pcall(result) if status then return result end else return result end end return ("theme function %s: '%s'"):format(f, result) end --[[ Theme metatable. ]] setmetatable(theme, { __call = function(t, arg) if not arg then arg = {} end local f = arg[1] arg[1] = nil -- clean-up theme environment if t[f] == nil then return theme_render(f, arg) else return theme_execute(f, arg) end end }) --[[ Translate given table key-value pairs to attr="value". ]] function render_attributes(options, default_options) if default_options == nil then default_options = {} end -- Merge default_options into options if type(options) ~= 'table' then options = default_options else for k, v in pairs(default_options) do if options[k] == nil then options[k] = default_options[k] end end end local attr = {} for k, v in pairs(options) do tinsert(attr, ('%s="%s"'):format(k, v)) end return tconcat(attr, " ") end --[[ Translate given table key-value pairs to "val1 val2". ]] function render_classes(classes, default_classes) if default_classes == nil then default_classes = {} end if type(classes) ~= 'table' then classes = default_classes else for k, v in pairs(default_classes) do if classes[k] == nil and not empty(classes[k]) then classes[k] = default_classes[k] end end end local output = {} for k, _ in pairs(classes) do tinsert(output, k) end return tconcat(output, '') end --[[ Print output of given theme function and parameters. ]] function print_t(...) print(theme(...) or '') end --[[ Print output of given theme function and parameters. ]] function print_f(text, ...) print(text:format(...)) end function theme.json(variables) local json = require 'dkjson' local content = variables.content local output = json.encode(content) header('content-type', 'application/json; charset=utf-8') header('content-length', (output or ''):len()) theme_print(output) end function path_to_theme() return ('themes/%s'):format(theme_name) end --[[ Anchor theme function. ]] function theme.a(variables) if variables == nil then variables = {} end local attributes = variables.attributes variables.attributes = nil -- Support HTML5 download attribute local download = attributes.download attributes.download = nil if download == true then download = ' download' elseif type(download) == 'string' then download = (' download="%s"'):format(download) end return ('<a href="%s"%s %s>%s</a>'):format(variables.route, download or '', render_attributes(attributes), variables.text) end --[[ Image theme function. ]] function theme.img(variables) local path = variables.path or '' local options = variables.options if options and options.external then options.external = nil else path = base.route .. path end return ('<img src="%s" %s />'):format(path, render_attributes(options)) end --[[ Logo theme function. ]] function theme.logo() local site = settings.site local logo_path = ('%s/%s'):format(path_to_theme(), site.logo_path) return l(theme{'img', path = logo_path, options = {alt = site.logo_title, title = site.logo_title, border = 0}}, '', {absolute = true, attributes = {id = 'logo'}}) end --[[ Items list function theme function. ]] function theme.item_list(variables) if variables == nil then variables = {} end local list = variables.list variables.list = nil local output = {('<ul%s>'):format(list ~= nil and ' ' .. render_attributes(variables) or '')} for _, v in pairs(list) do tinsert(output, ('<li>%s</li>'):format(v)) end tinsert(output, '</ul>') return tconcat(output) end
Bug fix #6: Apache: Missing content-length HTTP throws error on json output.
Bug fix #6: Apache: Missing content-length HTTP throws error on json output.
Lua
agpl-3.0
ophal/core,coinzen/coinage,coinzen/coinage,coinzen/coinage,ophal/core,ophal/core
69946d431b4cc4d2010f6ddf59aca46281f987c2
classes/book.lua
classes/book.lua
local plain = SILE.require("classes/plain"); local book = plain { id = "book" }; book:loadPackage("masters") book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = {left = "8.3%", right = "86%", top = "11.6%", bottom = "top(footnotes)" }, folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%",bottom = "bottom(footnotes)+5%" }, runningHead = {left = "left(content)", right = "right(content)", top = "top(content) - 8%", bottom = "top(content)-3%" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%"} }}) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") book:loadPackage("tableofcontents") if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end book.pageTemplate = SILE.scratch.masters["right"] book.init = function(self) book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } ) return plain.init(self) end book.newPage = function(self) book:switchPage() return plain.newPage(self) end book.finish = function () book:writeToc() return plain:finish() end book.endPage = function(self) book:outputInsertions() book:moveTocNodes() book:newPageInfo() if (book:oddPage() and SILE.scratch.headers.right) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) -- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.right) SILE.call("par") end) elseif (not(book:oddPage()) and SILE.scratch.headers.left) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) -- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.left) SILE.call("par") end) end return plain.endPage(book); end; SILE.registerCommand("left-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.left = function () closure(content) end end, "Text to appear on the top of the left page"); SILE.registerCommand("right-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.right = function () closure(content) end end, "Text to appear on the top of the right page"); SILE.registerCommand("chapter", function (options, content) SILE.call("open-double-page") SILE.call("noindent") SILE.scratch.headers.right = nil SILE.call("increment-multilevel-counter", {id = "sectioning", level = 1}) SILE.call("tocentry", {level = 1}, content) SILE.call("set-counter", {id = "footnote", value = 1}) if options.numbering == nil or options.numbering == "yes" then SILE.Commands["book:chapterfont"]({}, function() SILE.typesetter:typeset("Chapter ") SILE.call("show-multilevel-counter", {id="sectioning"}) SILE.typesetter:leaveHmode() end) end SILE.Commands["book:chapterfont"]({}, content); SILE.Commands["left-running-head"]({}, content) SILE.call("bigskip") SILE.call("nofoliosthispage") end, "Begin a new chapter"); SILE.registerCommand("section", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("bigskip") SILE.call("noindent") SILE.call("increment-multilevel-counter", {id = "sectioning", level = 2}) SILE.call("tocentry", {level = 2}, content) SILE.Commands["book:sectionfont"]({}, function() SILE.call("show-multilevel-counter", {id="sectioning", level = 2}) SILE.typesetter:typeset(" ") SILE.process(content) end) if not SILE.scratch.counters.folio.off then SILE.Commands["right-running-head"]({}, function() SILE.call("rightalign", {}, function () SILE.settings.temporarily(function() SILE.settings.set("font.style", "italic") SILE.call("show-multilevel-counter", {id="sectioning", level =2}) SILE.typesetter:typeset(" ") SILE.process(content) end) end) end); end SILE.call("novbreak") SILE.call("bigskip") SILE.call("novbreak") end, "Begin a new section") SILE.registerCommand("subsection", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("medskip") SILE.call("increment-multilevel-counter", {id = "sectioning", level = 3}) SILE.call("tocentry", {level = 3}, content) SILE.Commands["book:subsectionfont"]({}, function() SILE.call("show-multilevel-counter", {id="sectioning"}) SILE.typesetter:typeset(" ") SILE.process(content) end) SILE.typesetter:leaveHmode() SILE.call("novbreak") SILE.call("medskip") SILE.call("novbreak") end, "Begin a new subsection") SILE.registerCommand("book:chapterfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="22pt"}, content) end) end) SILE.registerCommand("book:sectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="15pt"}, content) end) end) SILE.registerCommand("book:subsectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="12pt"}, content) end) end) SILE.registerCommand("open-double-page", function() SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); if book:oddPage() then SILE.typesetter:typeset("") SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); end end) return book
local plain = SILE.require("classes/plain"); local book = plain { id = "book" }; book:loadPackage("masters") book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = {left = "8.3%", right = "86%", top = "11.6%", bottom = "top(footnotes)" }, folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%",bottom = "bottom(footnotes)+5%" }, runningHead = {left = "left(content)", right = "right(content)", top = "top(content) - 8%", bottom = "top(content)-3%" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%"} }}) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") book:loadPackage("tableofcontents") if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end book.pageTemplate = SILE.scratch.masters["right"] book.init = function(self) book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } ) return plain.init(self) end book.newPage = function(self) book:switchPage() return plain.newPage(self) end book.finish = function () book:writeToc() return plain:finish() end book.endPage = function(self) book:outputInsertions() book:moveTocNodes() book:newPageInfo() if (book:oddPage() and SILE.scratch.headers.right) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) -- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.right) SILE.call("par") end) elseif (not(book:oddPage()) and SILE.scratch.headers.left) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) -- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.left) SILE.call("par") end) end return plain.endPage(book); end; SILE.registerCommand("left-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.left = function () closure(content) end end, "Text to appear on the top of the left page"); SILE.registerCommand("right-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.right = function () closure(content) end end, "Text to appear on the top of the right page"); SILE.registerCommand("book:sectioning", function (options, content) local level = SU.required(options, "level", "book:sectioning") SILE.call("increment-multilevel-counter", {id = "sectioning", level = options.level}) SILE.call("tocentry", {level = options.level}, content) if options.numbering == nil or options.numbering == "yes" then if options.prenumber then SILE.call(options.prenumber) end SILE.call("show-multilevel-counter", {id="sectioning"}) if options.postnumber then SILE.call(options.postnumber) end end end) book.registerCommands = function() plain.registerCommands() SILE.doTexlike([[% \define[command=book:chapter:pre]{Chapter }% \define[command=book:chapter:post]{\par}% \define[command=book:section:post]{ }% \define[command=book:subsection:post]{ }% ]]) end SILE.registerCommand("chapter", function (options, content) SILE.call("open-double-page") SILE.call("noindent") SILE.scratch.headers.right = nil SILE.call("set-counter", {id = "footnote", value = 1}) SILE.call("book:chapterfont", {}, function() SILE.call("book:sectioning", { numbering = options.numbering, level = 1, prenumber = "book:chapter:pre", postnumber = "book:chapter:post" }, content) end) SILE.Commands["book:chapterfont"]({}, content); SILE.Commands["left-running-head"]({}, content) SILE.call("bigskip") SILE.call("nofoliosthispage") end, "Begin a new chapter"); SILE.registerCommand("section", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("bigskip") SILE.call("noindent") SILE.Commands["book:sectionfont"]({}, function() SILE.call("book:sectioning", { numbering = options.numbering, level = 2, postnumber = "book:section:post" }, content) SILE.process(content) end) if not SILE.scratch.counters.folio.off then SILE.Commands["right-running-head"]({}, function() SILE.call("rightalign", {}, function () SILE.settings.temporarily(function() SILE.settings.set("font.style", "italic") SILE.call("show-multilevel-counter", {id="sectioning", level =2}) SILE.typesetter:typeset(" ") SILE.process(content) end) end) end); end SILE.call("novbreak") SILE.call("bigskip") SILE.call("novbreak") end, "Begin a new section") SILE.registerCommand("subsection", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("medskip") SILE.Commands["book:subsectionfont"]({}, function() SILE.call("book:sectioning", { numbering = options.numbering, level = 3, postnumber = "book:subsection:post" }, content) SILE.process(content) end) SILE.typesetter:leaveHmode() SILE.call("novbreak") SILE.call("medskip") SILE.call("novbreak") end, "Begin a new subsection") SILE.registerCommand("book:chapterfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="22pt"}, content) end) end) SILE.registerCommand("book:sectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="15pt"}, content) end) end) SILE.registerCommand("book:subsectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="12pt"}, content) end) end) SILE.registerCommand("open-double-page", function() SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); if book:oddPage() then SILE.typesetter:typeset("") SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); end end) return book
Rework sectioning. Fixes #46.
Rework sectioning. Fixes #46.
Lua
mit
anthrotype/sile,WAKAMAZU/sile_fe,alerque/sile,neofob/sile,simoncozens/sile,neofob/sile,simoncozens/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,shirat74/sile,alerque/sile,alerque/sile,anthrotype/sile,shirat74/sile,neofob/sile,neofob/sile,simoncozens/sile,shirat74/sile,simoncozens/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,anthrotype/sile,shirat74/sile
04775dc8a410d1ac493a9f9bcafa1c3da6381c12
scripts/bgfx.lua
scripts/bgfx.lua
-- -- Copyright 2010-2015 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- function bgfxProject(_name, _kind, _defines) project ("bgfx" .. _name) uuid (os.uuid("bgfx" .. _name)) kind (_kind) if _kind == "SharedLib" then defines { "BGFX_SHARED_LIB_BUILD=1", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "mingw*" } linkoptions { "-shared", } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} end includedirs { path.join(BGFX_DIR, "3rdparty"), path.join(BGFX_DIR, "3rdparty/dxsdk/include"), path.join(BGFX_DIR, "../bx/include"), } defines { _defines, } if _OPTIONS["with-glfw"] then defines { "BGFX_CONFIG_MULTITHREADED=0", } end if _OPTIONS["with-ovr"] then defines { "BGFX_CONFIG_USE_OVR=1", } includedirs { "$(OVR_DIR)/LibOVR/Include", } end configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "android*" } links { "EGL", "GLESv2", } configuration { "winphone8* or winstore8*" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } configuration { "*clang*" } buildoptions { "-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int' "-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension } configuration { "osx" } links { "Cocoa.framework", } configuration { "not nacl" } includedirs { --nacl has GLES2 headers modified... path.join(BGFX_DIR, "3rdparty/khronos"), } configuration {} includedirs { path.join(BGFX_DIR, "include"), } files { path.join(BGFX_DIR, "include/**.h"), path.join(BGFX_DIR, "src/**.cpp"), path.join(BGFX_DIR, "src/**.h"), } removefiles { path.join(BGFX_DIR, "src/**.bin.h"), } if _OPTIONS["with-amalgamated"] then excludes { path.join(BGFX_DIR, "src/bgfx.cpp"), path.join(BGFX_DIR, "src/glcontext_egl.cpp"), path.join(BGFX_DIR, "src/glcontext_glx.cpp"), path.join(BGFX_DIR, "src/glcontext_ppapi.cpp"), path.join(BGFX_DIR, "src/glcontext_wgl.cpp"), path.join(BGFX_DIR, "src/image.cpp"), path.join(BGFX_DIR, "src/ovr.cpp"), path.join(BGFX_DIR, "src/renderdoc.cpp"), path.join(BGFX_DIR, "src/renderer_d3d9.cpp"), path.join(BGFX_DIR, "src/renderer_d3d11.cpp"), path.join(BGFX_DIR, "src/renderer_d3d12.cpp"), path.join(BGFX_DIR, "src/renderer_null.cpp"), path.join(BGFX_DIR, "src/renderer_gl.cpp"), path.join(BGFX_DIR, "src/renderer_vk.cpp"), path.join(BGFX_DIR, "src/shader_dx9bc.cpp"), path.join(BGFX_DIR, "src/shader_dxbc.cpp"), path.join(BGFX_DIR, "src/shader_spirv.cpp"), path.join(BGFX_DIR, "src/vertexdecl.cpp"), } configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/amalgamated.mm"), } excludes { path.join(BGFX_DIR, "src/glcontext_eagl.mm"), path.join(BGFX_DIR, "src/glcontext_nsgl.mm"), path.join(BGFX_DIR, "src/renderer_mtl.mm"), path.join(BGFX_DIR, "src/amalgamated.cpp"), } configuration {} else configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/glcontext_eagl.mm"), path.join(BGFX_DIR, "src/glcontext_nsgl.mm"), path.join(BGFX_DIR, "src/renderer_mtl.mm"), } configuration {} excludes { path.join(BGFX_DIR, "src/amalgamated.**"), } end configuration {} copyLib() end
-- -- Copyright 2010-2015 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- function bgfxProject(_name, _kind, _defines) project ("bgfx" .. _name) uuid (os.uuid("bgfx" .. _name)) kind (_kind) if _kind == "SharedLib" then defines { "BGFX_SHARED_LIB_BUILD=1", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "mingw*" } linkoptions { "-shared", } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} end includedirs { path.join(BGFX_DIR, "3rdparty"), path.join(BGFX_DIR, "3rdparty/dxsdk/include"), path.join(BGFX_DIR, "../bx/include"), } defines { _defines, } if _OPTIONS["with-glfw"] then defines { "BGFX_CONFIG_MULTITHREADED=0", } end if _OPTIONS["with-ovr"] then defines { "BGFX_CONFIG_USE_OVR=1", } includedirs { "$(OVR_DIR)/LibOVR/Include", } end configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "android*" } links { "EGL", "GLESv2", } configuration { "winphone8* or winstore8*" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } configuration { "*clang*" } buildoptions { "-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int' "-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension } configuration { "osx" } linkoptions { "-framework Cocoa", "-framework Metal", "-framework QuartzCore", "-framework OpenGL", } configuration { "not nacl" } includedirs { --nacl has GLES2 headers modified... path.join(BGFX_DIR, "3rdparty/khronos"), } configuration {} includedirs { path.join(BGFX_DIR, "include"), } files { path.join(BGFX_DIR, "include/**.h"), path.join(BGFX_DIR, "src/**.cpp"), path.join(BGFX_DIR, "src/**.h"), } removefiles { path.join(BGFX_DIR, "src/**.bin.h"), } if _OPTIONS["with-amalgamated"] then excludes { path.join(BGFX_DIR, "src/bgfx.cpp"), path.join(BGFX_DIR, "src/glcontext_egl.cpp"), path.join(BGFX_DIR, "src/glcontext_glx.cpp"), path.join(BGFX_DIR, "src/glcontext_ppapi.cpp"), path.join(BGFX_DIR, "src/glcontext_wgl.cpp"), path.join(BGFX_DIR, "src/image.cpp"), path.join(BGFX_DIR, "src/ovr.cpp"), path.join(BGFX_DIR, "src/renderdoc.cpp"), path.join(BGFX_DIR, "src/renderer_d3d9.cpp"), path.join(BGFX_DIR, "src/renderer_d3d11.cpp"), path.join(BGFX_DIR, "src/renderer_d3d12.cpp"), path.join(BGFX_DIR, "src/renderer_null.cpp"), path.join(BGFX_DIR, "src/renderer_gl.cpp"), path.join(BGFX_DIR, "src/renderer_vk.cpp"), path.join(BGFX_DIR, "src/shader_dx9bc.cpp"), path.join(BGFX_DIR, "src/shader_dxbc.cpp"), path.join(BGFX_DIR, "src/shader_spirv.cpp"), path.join(BGFX_DIR, "src/vertexdecl.cpp"), } configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/amalgamated.mm"), } excludes { path.join(BGFX_DIR, "src/glcontext_eagl.mm"), path.join(BGFX_DIR, "src/glcontext_nsgl.mm"), path.join(BGFX_DIR, "src/renderer_mtl.mm"), path.join(BGFX_DIR, "src/amalgamated.cpp"), } configuration {} else configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/glcontext_eagl.mm"), path.join(BGFX_DIR, "src/glcontext_nsgl.mm"), path.join(BGFX_DIR, "src/renderer_mtl.mm"), } configuration {} excludes { path.join(BGFX_DIR, "src/amalgamated.**"), } end configuration {} copyLib() end
Fixed issue #549.
Fixed issue #549.
Lua
bsd-2-clause
jdryg/bgfx,bkaradzic/bgfx,aonorin/bgfx,andr3wmac/bgfx,emoon/bgfx,mendsley/bgfx,LWJGL-CI/bgfx,jpcy/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,Synxis/bgfx,cuavas/bgfx,LSBOSS/bgfx,emoon/bgfx,fluffyfreak/bgfx,fluffyfreak/bgfx,cuavas/bgfx,jdryg/bgfx,elmindreda/bgfx,Synxis/bgfx,v3n/bgfx,aonorin/bgfx,jdryg/bgfx,marco-we/bgfx,jpcy/bgfx,jpcy/bgfx,mmicko/bgfx,cuavas/bgfx,mendsley/bgfx,attilaz/bgfx,0-wiz-0/bgfx,mendsley/bgfx,fluffyfreak/bgfx,MikePopoloski/bgfx,andr3wmac/bgfx,attilaz/bgfx,mmicko/bgfx,aonorin/bgfx,fluffyfreak/bgfx,0-wiz-0/bgfx,LSBOSS/bgfx,v3n/bgfx,jpcy/bgfx,kondrak/bgfx,septag/bgfx,LWJGL-CI/bgfx,kondrak/bgfx,LWJGL-CI/bgfx,v3n/bgfx,elmindreda/bgfx,Synxis/bgfx,elmindreda/bgfx,0-wiz-0/bgfx,septag/bgfx,LSBOSS/bgfx,septag/bgfx,MikePopoloski/bgfx,bkaradzic/bgfx,kondrak/bgfx,marco-we/bgfx,emoon/bgfx,darkimage/bgfx,darkimage/bgfx,darkimage/bgfx,andr3wmac/bgfx,jdryg/bgfx,mmicko/bgfx,MikePopoloski/bgfx,attilaz/bgfx,marco-we/bgfx,bkaradzic/bgfx
4a497cfcfb98c2462ccecc4d16640b503e206adb
frontend/device/kobo/device.lua
frontend/device/kobo/device.lua
local Generic = require("device/generic/device") local lfs = require("libs/libkoreader-lfs") local Geom = require("ui/geometry") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, } -- TODO: hasKeys for some devices? -- Kobo Touch: local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", touch_switch_xy = false, } -- Kobo Mini: local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, } -- Kobo Aura H2O: local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- bezel: viewport = Geom:new{x=0, y=10, w=1080, h=1430}, } -- Kobo Aura HD: local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } -- Kobo Glo: local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } -- Kobo Aura: local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212, -- the bezel covers 12 pixels at the bottom: viewport = Geom:new{x=0, y=0, w=758, h=1012}, } function Kobo:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [116] = "Power", } } Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. if self.touch_switch_xy and not KOBO_TOUCH_MIRRORED or not self.touch_switch_xy and KOBO_TOUCH_MIRRORED then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, self.screen:getScreenWidth() ) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end end function Kobo:getCodeName() local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") local codename = std_out:read() std_out:close() return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:Suspend() os.execute("./suspend.sh") end function Kobo:Resume() os.execute("echo 0 > /sys/power/state-extended") if self.powerd then if KOBO_LIGHT_ON_START and tonumber(KOBO_LIGHT_ON_START) > -1 then self.powerd:setIntensity(math.max(math.min(KOBO_LIGHT_ON_START,100),0)) elseif self.powerd.fl ~= nil then self.powerd.fl:restore() end end Generic.Resume(self) end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie else error("unrecognized Kobo model "..codename) end
local Generic = require("device/generic/device") local lfs = require("libs/libkoreader-lfs") local Geom = require("ui/geometry") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, } -- TODO: hasKeys for some devices? -- Kobo Touch: local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", touch_switch_xy = false, } -- Kobo Mini: local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, } -- Kobo Aura H2O: local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- bezel: viewport = Geom:new{x=0, y=10, w=1080, h=1430}, } -- Kobo Aura HD: local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } -- Kobo Glo: local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } -- Kobo Aura: local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212, -- the bezel covers 12 pixels at the bottom: viewport = Geom:new{x=0, y=0, w=758, h=1012}, } function Kobo:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [116] = "Power", } } -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. if self.touch_switch_xy and not KOBO_TOUCH_MIRRORED or not self.touch_switch_xy and KOBO_TOUCH_MIRRORED then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, self.screen:getScreenWidth() ) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") end function Kobo:getCodeName() local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") local codename = std_out:read() std_out:close() return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:Suspend() os.execute("./suspend.sh") end function Kobo:Resume() os.execute("echo 0 > /sys/power/state-extended") if self.powerd then if KOBO_LIGHT_ON_START and tonumber(KOBO_LIGHT_ON_START) > -1 then self.powerd:setIntensity(math.max(math.min(KOBO_LIGHT_ON_START,100),0)) elseif self.powerd.fl ~= nil then self.powerd.fl:restore() end end Generic.Resume(self) end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie else error("unrecognized Kobo model "..codename) end
fix initialization order on Kobos
fix initialization order on Kobos notably, this will set up input offsets for viewport stuff after the input rotation has been set up.
Lua
agpl-3.0
noname007/koreader,lgeek/koreader,koreader/koreader,Markismus/koreader,robert00s/koreader,houqp/koreader,chihyang/koreader,Frenzie/koreader,mwoz123/koreader,poire-z/koreader,NiLuJe/koreader,Hzj-jie/koreader,chrox/koreader,NiLuJe/koreader,koreader/koreader,ashang/koreader,ashhher3/koreader,apletnev/koreader,mihailim/koreader,poire-z/koreader,pazos/koreader,Frenzie/koreader,NickSavage/koreader,frankyifei/koreader
19d70f27191569fce59fb6f6433ad339e99016a8
frontend/ui/widget/inputtext.lua
frontend/ui/widget/inputtext.lua
require "ui/graphics" require "ui/widget/text" require "ui/widget/keyboard" require "ui/widget/container" InputText = InputContainer:new{ text = "", hint = "demo hint", charlist = {}, -- table to store input string charpos = 1, input_type = nil, width = nil, height = nil, face = Font:getFace("cfont", 22), padding = 5, margin = 5, bordersize = 2, parent = nil, -- parent dialog that will be set dirty scroll = false, } function InputText:init() self:StringToCharlist(self.text) self:initTextBox() self:initKeyboard() end function InputText:initTextBox() local bgcolor = nil local fgcolor = nil if self.text == "" then self.text = self.hint bgcolor = 0.0 fgcolor = 0.5 else bgcolor = 0.0 fgcolor = 1.0 end local text_widget = nil if self.scroll then text_widget = ScrollTextWidget:new{ text = self.text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } else text_widget = TextBoxWidget:new{ text = self.text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } end self[1] = FrameContainer:new{ bordersize = self.bordersize, padding = self.padding, margin = self.margin, text_widget, } self.dimen = self[1]:getSize() end function InputText:initKeyboard() local keyboard_layout = 2 if self.input_type == "number" then keyboard_layout = 3 end self.keyboard = VirtualKeyboard:new{ layout = keyboard_layout, inputbox = self, width = Screen:getWidth(), height = math.max(Screen:getWidth(), Screen:getHeight())*0.33, } end function InputText:onShowKeyboard() UIManager:show(self.keyboard) end function InputText:onCloseKeyboard() UIManager:close(self.keyboard) end function InputText:getKeyboardDimen() return self.keyboard.dimen end function InputText:addChar(char) table.insert(self.charlist, self.charpos, char) self.charpos = self.charpos + 1 self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:delChar() self.charpos = self.charpos - 1 table.remove(self.charlist, self.charpos) self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:getText() return self.text end function InputText:StringToCharlist(text) if text == nil then return end -- clear self.charlist = {} self.charpos = 1 local prevcharcode, charcode = 0 for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do charcode = util.utf8charcode(uchar) if prevcharcode then -- utf8 self.charlist[#self.charlist+1] = uchar end prevcharcode = charcode end self.text = self:CharlistToString() self.charpos = #self.charlist+1 end function InputText:CharlistToString() local s, i = "" for i=1, #self.charlist do s = s .. self.charlist[i] end return s end
require "ui/graphics" require "ui/widget/text" require "ui/widget/keyboard" require "ui/widget/container" InputText = InputContainer:new{ text = "", hint = "demo hint", charlist = {}, -- table to store input string charpos = 1, input_type = nil, width = nil, height = nil, face = Font:getFace("cfont", 22), padding = 5, margin = 5, bordersize = 2, parent = nil, -- parent dialog that will be set dirty scroll = false, } function InputText:init() self:StringToCharlist(self.text) self:initTextBox() self:initKeyboard() end function InputText:initTextBox() local bgcolor = nil local fgcolor = nil if self.text == "" then self.text = self.hint bgcolor = 0.0 fgcolor = 0.5 else bgcolor = 0.0 fgcolor = 1.0 end local text_widget = nil if self.scroll then text_widget = ScrollTextWidget:new{ text = self.text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } else text_widget = TextBoxWidget:new{ text = self.text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } end self[1] = FrameContainer:new{ bordersize = self.bordersize, padding = self.padding, margin = self.margin, text_widget, } self.dimen = self[1]:getSize() end function InputText:initKeyboard() local keyboard_layout = 2 if self.input_type == "number" then keyboard_layout = 3 end self.keyboard = VirtualKeyboard:new{ layout = keyboard_layout, inputbox = self, width = Screen:getWidth(), height = math.max(Screen:getWidth(), Screen:getHeight())*0.33, } end function InputText:onShowKeyboard() UIManager:show(self.keyboard) end function InputText:onCloseKeyboard() UIManager:close(self.keyboard) end function InputText:getKeyboardDimen() return self.keyboard.dimen end function InputText:addChar(char) table.insert(self.charlist, self.charpos, char) self.charpos = self.charpos + 1 self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:delChar() if self.charpos == 1 then return end self.charpos = self.charpos - 1 table.remove(self.charlist, self.charpos) self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:getText() return self.text end function InputText:StringToCharlist(text) if text == nil then return end -- clear self.charlist = {} self.charpos = 1 local prevcharcode, charcode = 0 for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do charcode = util.utf8charcode(uchar) if prevcharcode then -- utf8 self.charlist[#self.charlist+1] = uchar end prevcharcode = charcode end self.text = self:CharlistToString() self.charpos = #self.charlist+1 end function InputText:CharlistToString() local s, i = "" for i=1, #self.charlist do s = s .. self.charlist[i] end return s end
fix delChar decreasing charpos on blank charlist
fix delChar decreasing charpos on blank charlist
Lua
agpl-3.0
poire-z/koreader,Markismus/koreader,Frenzie/koreader,noname007/koreader,koreader/koreader,chrox/koreader,NiLuJe/koreader,ashang/koreader,pazos/koreader,mihailim/koreader,robert00s/koreader,NickSavage/koreader,houqp/koreader,mwoz123/koreader,lgeek/koreader,ashhher3/koreader,frankyifei/koreader,chihyang/koreader,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,apletnev/koreader,Frenzie/koreader,poire-z/koreader
7c0bebb208c2c400baa1d80b7be73a57c8bfa395
lib/px/pxnginx.lua
lib/px/pxnginx.lua
-- Copyright © 2016 PerimeterX, Inc. -- Permission is hereby granted, free of charge, to any -- person obtaining a copy of this software and associated -- documentation files (the "Software"), to deal in the -- Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the -- Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice -- shall be included in all copies or substantial portions of -- the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY -- KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS -- OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR -- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. local _M = {} function _M.application(file_name) -- Support for multiple apps - each app file should be named "pxconfig-<appname>.lua" local config_file = ((file_name == nil or file_name == '') and "px.pxconfig" or "px.pxconfig-" .. file_name) local px_config = require (config_file) local px_filters = require ("px.utils.pxfilters").load(config_file) local px_client = require ("px.utils.pxclient").load(config_file) local px_cookie = require ("px.utils.pxcookie").load(config_file) local px_captcha = require ("px.utils.pxcaptcha").load(config_file) local px_block = require ("px.block.pxblock").load(config_file) local px_api = require ("px.utils.pxapi").load(config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local px_headers = require ("px.utils.pxheaders").load(config_file) local auth_token = px_config.auth_token local enable_server_calls = px_config.enable_server_calls local risk_api_path = px_config.risk_api_path local enabled_routes = px_config.enabled_routes local remote_addr = ngx.var.remote_addr or "" local user_agent = ngx.var.http_user_agent or "" local string_sub = string.sub local string_len = string.len local pcall = pcall if not px_config.px_enabled then return true end local valid_route = false -- Enable module only on configured routes for i = 1, #enabled_routes do if string_sub(ngx.var.uri, 1, string_len(enabled_routes[i])) == enabled_routes[i] then px_logger.debug("Checking for enabled routes. " .. enabled_routes[i]) valid_route = true end end if not valid_route and #enabled_routes > 0 then px_headers.set_score_header(0) return true end -- Validate if request is from internal redirect to avoid duplicate processing if px_headers.validate_internal_request() then return true end -- Clean any protected headers from the request. -- Prevents header spoofing to upstream application px_headers.clear_protected_headers() -- run filter and whitelisting logic if (px_filters.process()) then px_headers.set_score_header(0) return true end px_logger.debug("New request process. IP: " .. remote_addr .. ". UA: " .. user_agent) -- process _px cookie if present local _px = ngx.var.cookie__px local _pxCaptcha = ngx.var.cookie__pxCaptcha if px_config.captcha_enabled and _pxCaptcha then local success, result = pcall(px_captcha.process, _pxCaptcha) -- validating captcha value and if reset was successful then pass the request if success and result == 0 then ngx.header["Content-Type"] = nil ngx.header["Set-Cookie"] = "_pxCaptcha=; Expires=Thu, 01 Jan 1970 00:00:00 GMT;" return true end end local success, result = pcall(px_cookie.process, _px) local details = {}; details["px_cookie"] = ngx.ctx.px_cookie; -- cookie verification passed - checking result. if success then -- score crossed threshold if result == false then return px_block.block('cookie_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested", details) return true end -- cookie verification failed/cookie does not exist. performing s2s query elseif enable_server_calls == true then local request_data = px_api.new_request_object(result.message) local success, response = pcall(px_api.call_s2s, request_data, risk_api_path, auth_token) local result if success then result = px_api.process(response) -- score crossed threshold if result == false then px_logger.error("blocking s2s") return px_block.block('s2s_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested", details) return true end else -- server2server call failed, passing traffic px_client.send_to_perimeterx("page_requested", details) return true end else px_client.send_to_perimeterx("page_requested", details) return true end end return _M
-- Copyright © 2016 PerimeterX, Inc. -- Permission is hereby granted, free of charge, to any -- person obtaining a copy of this software and associated -- documentation files (the "Software"), to deal in the -- Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the -- Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice -- shall be included in all copies or substantial portions of -- the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY -- KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS -- OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR -- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. local _M = {} function _M.application(file_name) -- Support for multiple apps - each app file should be named "pxconfig-<appname>.lua" local config_file = ((file_name == nil or file_name == '') and "px.pxconfig" or "px.pxconfig-" .. file_name) local px_config = require (config_file) local px_filters = require ("px.utils.pxfilters").load(config_file) local px_client = require ("px.utils.pxclient").load(config_file) local px_cookie = require ("px.utils.pxcookie").load(config_file) local px_captcha = require ("px.utils.pxcaptcha").load(config_file) package.loaded[ 'px.block.pxblock' ] = nil local px_block = require ("px.block.pxblock").load(config_file) local px_api = require ("px.utils.pxapi").load(config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local px_headers = require ("px.utils.pxheaders").load(config_file) local auth_token = px_config.auth_token local enable_server_calls = px_config.enable_server_calls local risk_api_path = px_config.risk_api_path local enabled_routes = px_config.enabled_routes local remote_addr = ngx.var.remote_addr or "" local user_agent = ngx.var.http_user_agent or "" local string_sub = string.sub local string_len = string.len local pcall = pcall if not px_config.px_enabled then return true end local valid_route = false -- Enable module only on configured routes for i = 1, #enabled_routes do if string_sub(ngx.var.uri, 1, string_len(enabled_routes[i])) == enabled_routes[i] then px_logger.debug("Checking for enabled routes. " .. enabled_routes[i]) valid_route = true end end if not valid_route and #enabled_routes > 0 then px_headers.set_score_header(0) return true end -- Validate if request is from internal redirect to avoid duplicate processing if px_headers.validate_internal_request() then return true end -- Clean any protected headers from the request. -- Prevents header spoofing to upstream application px_headers.clear_protected_headers() -- run filter and whitelisting logic if (px_filters.process()) then px_headers.set_score_header(0) return true end px_logger.debug("New request process. IP: " .. remote_addr .. ". UA: " .. user_agent) -- process _px cookie if present local _px = ngx.var.cookie__px local _pxCaptcha = ngx.var.cookie__pxCaptcha if px_config.captcha_enabled and _pxCaptcha then local success, result = pcall(px_captcha.process, _pxCaptcha) -- validating captcha value and if reset was successful then pass the request if success and result == 0 then ngx.header["Content-Type"] = nil ngx.header["Set-Cookie"] = "_pxCaptcha=; Expires=Thu, 01 Jan 1970 00:00:00 GMT;" return true end end local success, result = pcall(px_cookie.process, _px) local details = {}; details["px_cookie"] = ngx.ctx.px_cookie; -- cookie verification passed - checking result. if success then -- score crossed threshold if result == false then return px_block.block('cookie_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested", details) return true end -- cookie verification failed/cookie does not exist. performing s2s query elseif enable_server_calls == true then local request_data = px_api.new_request_object(result.message) local success, response = pcall(px_api.call_s2s, request_data, risk_api_path, auth_token) local result if success then result = px_api.process(response) -- score crossed threshold if result == false then px_logger.error("blocking s2s") return px_block.block('s2s_high_score') -- score did not cross the blocking threshold else px_client.send_to_perimeterx("page_requested", details) return true end else -- server2server call failed, passing traffic px_client.send_to_perimeterx("page_requested", details) return true end else px_client.send_to_perimeterx("page_requested", details) return true end end return _M
Fixed multiapp-support race condition with multiple configurtion files
Fixed multiapp-support race condition with multiple configurtion files
Lua
mit
PerimeterX/perimeterx-nginx-plugin
faf30597a14bd77753d92bb26bdb267664498fb5
cnt.lua
cnt.lua
-- cnt.lua -- -- Simple counter. -- -- -- Increment counter identified by primary key. -- Create counter if not exists. -- Returns updated value of the counter. -- function cnt_inc(space, ...) local key = {...} local cnt_index = #key local tuple while true do tuple = box.update(space, key, '+p', cnt_index, 1) if tuple ~= nil then break end local data = {...} table.insert(data, 1) tuple = box.insert(space, unpack(data)) if tuple ~= nil then break end end return tuple[cnt_index] end -- -- Decrement counter identified by primary key. -- Delete counter if it decreased to zero. -- Returns updated value of the counter. -- function cnt_dec(space, ...) local key = {...} local cnt_index = #key local tuple = box.select(space, 0, ...) if tuple == nil then return 0 end if tuple[cnt_index] == 1 then box.delete(space, ...) return 0 else tuple = box.update(space, key, '-p', cnt_index, 1) return tuple[cnt_index] end end
-- cnt.lua -- -- Simple counter. -- -- -- Increment counter identified by primary key. -- Create counter if not exists. -- Returns updated value of the counter. -- function cnt_inc(space, ...) local key = {...} local cnt_index = #key local tuple while true do tuple = box.update(space, key, '+p', cnt_index, 1) if tuple ~= nil then break end local data = {...} table.insert(data, 1) tuple = box.insert(space, unpack(data)) if tuple ~= nil then break end end return box.unpack('i', tuple[cnt_index]) end -- -- Decrement counter identified by primary key. -- Delete counter if it decreased to zero. -- Returns updated value of the counter. -- function cnt_dec(space, ...) local key = {...} local cnt_index = #key local tuple = box.select(space, 0, ...) if tuple == nil then return 0 end if box.unpack('i', tuple[cnt_index]) == 1 then box.delete(space, ...) return 0 else tuple = box.update(space, key, '-p', cnt_index, 1) return box.unpack('i', tuple[cnt_index]) end end
cnt.lua: fix
cnt.lua: fix
Lua
bsd-2-clause
mailru/tntlua,derElektrobesen/tntlua,grechkin-pogrebnyakov/tntlua,spectrec/tntlua,BHYCHIK/tntlua
5f9e9b7eb39fc98cdacba52d081fe2b559fcfb33
ffi/harfbuzz.lua
ffi/harfbuzz.lua
local coverage = require("ffi/harfbuzz_coverage") local ffi = require("ffi") local hb = ffi.load("libs/libharfbuzz." .. (ffi.os == "OSX" and "0.dylib" or "so.0")) local HB = setmetatable({}, {__index = hb}) require("ffi/harfbuzz_h") local hb_face_t = {} hb_face_t.__index = hb_face_t ffi.metatype("hb_face_t", hb_face_t) -- Dump contents of OT name fields function hb_face_t:getNames(maxlen) maxlen = maxlen or 256 local n = ffi.new("unsigned[1]") local list = hb.hb_ot_name_list_names(self, n) if list == nil then return end local buf = ffi.new("char[?]", maxlen) local res = {} for i=0, n[0]-1 do local hb_lang = list[i].language local name_id = list[i].name_id local got = hb.hb_ot_name_get_utf8(self, name_id, hb_lang, ffi.new("unsigned[1]", maxlen), buf) hb_lang = ffi.string(hb.hb_language_to_string(hb_lang)) if got > 0 then res[hb_lang] = res[hb_lang] or {} res[hb_lang][name_id] = ffi.string(buf) end end return res end -- Alphabets are subset of a larger script - just enough for a specific language. -- This is used to mark face as eligibile to speak some tongue in particular. -- Later on the results are sorted by best ratio still, when multiple choices are available. -- TODO: These numbers are ballkpark, tweak this to more real-world defaults local coverage_thresholds = { -- nglyph coverage % 0, 100, -- Simple alphabets of 0-100 glyphs. Be strict, all glyphs are typically in use. 100, 99, -- 100-250 glyphs. abundant diacritics, allow for 1% missing, typically some archaisms 250, 98, -- 250-1000 glyphs. even more diacritics (eg cyrillic dialects), allow for 2% missing 1000, 85, -- 1000 and more = CJK, allow for 15% missing } -- Get script and language coverage function hb_face_t:getCoverage() local set, tmp = hb.hb_set_create(), hb.hb_set_create() local scripts = {} local langs = {} hb.hb_face_collect_unicodes(self, set) local function intersect(tab) hb.hb_set_set(tmp, set) hb.hb_set_intersect(tmp, tab) return hb.hb_set_get_population(tmp), hb.hb_set_get_population(tab) end for script_id, tab in ipairs(coverage.scripts) do local hit, total = intersect(tab) -- for scripts, we do only rough majority hit if 2*hit > total then scripts[script_id] = hit / total end end for lang_id, tab in pairs(coverage.langs) do local found local hit, total = intersect(tab) -- for languages, consider predefined threshold by glyph count for i=1, #coverage_thresholds, 2 do if total > coverage_thresholds[i] then found = i+1 end end if hit*100/total >= coverage_thresholds[found] then langs[lang_id] = hit/total end end hb.hb_set_destroy(set) hb.hb_set_destroy(tmp) return scripts, langs end function hb_face_t:destroy() hb.hb_face_destroy(self) end -- private -- preprocess the script/language tables to HB range sets local function make_set(tab) local set = hb.hb_set_create() local first = 0 local seen = 0 for i=1,#tab,2 do first = first + tab[i] local count = tab[i+1] seen = seen + count local last = first + count - 1 hb.hb_set_add_range(set, first, last) first = last end assert(hb.hb_set_get_population(set) == seen, "invalid coverage table") return set end for ucd_id, ranges in ipairs(coverage.scripts) do coverage.scripts[ucd_id] = make_set(ranges) end for lang_id, ranges in pairs(coverage.langs) do coverage.langs[lang_id] = make_set(ranges) end return HB
local coverage = require("ffi/harfbuzz_coverage") local ffi = require("ffi") local hb = ffi.load("libs/libharfbuzz." .. (ffi.os == "OSX" and "0.dylib" or "so.0")) local HB = setmetatable({}, {__index = hb}) require("ffi/harfbuzz_h") local hb_face_t = {} hb_face_t.__index = hb_face_t ffi.metatype("hb_face_t", hb_face_t) -- Dump contents of OT name fields function hb_face_t:getNames(maxlen) maxlen = maxlen or 256 local n = ffi.new("unsigned[1]") local list = hb.hb_ot_name_list_names(self, n) if list == nil then return end local buf = ffi.new("char[?]", maxlen) local res = {} for i=0, n[0]-1 do local name_id = list[i].name_id local hb_lang = list[i].language local lang = hb.hb_language_to_string(hb_lang) if lang ~= nil then lang = ffi.string(lang) local got = hb.hb_ot_name_get_utf8(self, name_id, hb_lang, ffi.new("unsigned[1]", maxlen), buf) name_id = tonumber(name_id) if got > 0 then res[lang] = res[lang] or {} res[lang][name_id] = ffi.string(buf) end end end return res end -- Alphabets are subset of a larger script - just enough for a specific language. -- This is used to mark face as eligibile to speak some tongue in particular. -- Later on the results are sorted by best ratio still, when multiple choices are available. -- TODO: These numbers are ballkpark, tweak this to more real-world defaults local coverage_thresholds = { -- nglyph coverage % 0, 100, -- Simple alphabets of 0-100 glyphs. Be strict, all glyphs are typically in use. 100, 99, -- 100-250 glyphs. abundant diacritics, allow for 1% missing, typically some archaisms 250, 98, -- 250-1000 glyphs. even more diacritics (eg cyrillic dialects), allow for 2% missing 1000, 85, -- 1000 and more = CJK, allow for 15% missing } -- Get script and language coverage function hb_face_t:getCoverage() local set, tmp = hb.hb_set_create(), hb.hb_set_create() local scripts = {} local langs = {} hb.hb_face_collect_unicodes(self, set) local function intersect(tab) hb.hb_set_set(tmp, set) hb.hb_set_intersect(tmp, tab) return hb.hb_set_get_population(tmp), hb.hb_set_get_population(tab) end for script_id, tab in ipairs(coverage.scripts) do local hit, total = intersect(tab) -- for scripts, we do only rough majority hit if 2*hit > total then scripts[script_id] = hit / total end end for lang_id, tab in pairs(coverage.langs) do local found local hit, total = intersect(tab) -- for languages, consider predefined threshold by glyph count for i=1, #coverage_thresholds, 2 do if total > coverage_thresholds[i] then found = i+1 end end if hit*100/total >= coverage_thresholds[found] then langs[lang_id] = hit/total end end hb.hb_set_destroy(set) hb.hb_set_destroy(tmp) return scripts, langs end function hb_face_t:destroy() hb.hb_face_destroy(self) end -- private -- preprocess the script/language tables into HB range sets local function make_set(tab) local set = hb.hb_set_create() local first = 0 local seen = 0 for i=1,#tab,2 do first = first + tab[i] local count = tab[i+1] seen = seen + count local last = first + count - 1 hb.hb_set_add_range(set, first, last) first = last end assert(hb.hb_set_get_population(set) == seen, "invalid coverage table") return set end for ucd_id, ranges in ipairs(coverage.scripts) do coverage.scripts[ucd_id] = make_set(ranges) end for lang_id, ranges in pairs(coverage.langs) do coverage.langs[lang_id] = make_set(ranges) end return HB
harfbuzz: Don't crash on invalid language tags. (#1223)
harfbuzz: Don't crash on invalid language tags. (#1223) Fixes https://github.com/koreader/koreader/issues/6806
Lua
agpl-3.0
koreader/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base
d3d9557fff94dd8943cbda9e242f40dcaae25ab1
lib/px/utils/pxclient.lua
lib/px/utils/pxclient.lua
--------------------------------------------- -- PerimeterX(www.perimeterx.com) Nginx plugin -- Version 1.1.4 -- Release date: 07.11.2016 ---------------------------------------------- local _M = {} function _M.load(config_file) local http = require "resty.http" local px_config = require (config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local buffer = require "px.utils.pxbuffer" local ngx_time = ngx.time local tostring = tostring local auth_token = px_config.auth_token -- Submit is the function to create the HTTP connection to the PX collector and POST the data function _M.submit(data, path) local px_server = px_config.px_server local px_port = px_config.px_port local ssl_enabled = px_config.ssl_enabled local px_debug = px_config.px_debug -- timeout in milliseconds local timeout = 2000 -- create new HTTP connection local httpc = http.new() httpc:set_timeout(timeout) local ok, err = httpc:connect(px_server, px_port) if not ok then px_logger.error("HTTPC connection error: " .. err) end -- Perform SSL/TLS handshake if ssl_enabled == true then local session, err = httpc:ssl_handshake() if not session then px_logger.error("HTTPC SSL handshare error: " .. err) end end -- Perform the HTTP requeset local res, err = httpc:request({ path = path, method = "POST", body = data, headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. auth_token } }) if not res then px_logger.error("Failed to make HTTP POST: " .. err) error("Failed to make HTTP POST: " .. err) elseif res.status ~= 200 then px_logger.error("Non 200 response code: " .. res.status) error("Non 200 response code: " .. res.status) else px_logger.debug("POST response status: " .. res.status) end -- Must read the response body to clear the buffer in order for set keepalive to work properly. -- Check for connection reuse if px_debug == true then local times, err = httpc:get_reused_times() if not times then px_logger.debug("Error getting reuse times: " .. err) else px_logger.debug("Reused conn times: " .. times) end end -- set keepalive to ensure connection pooling local ok, err = httpc:set_keepalive() if not ok then px_logger.error("Failed to set keepalive: " .. err) end end function _M.send_to_perimeterx(event_type, details) local buflen = buffer.getBufferLength(); local maxbuflen = px_config.px_maxbuflen; local full_url = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri; if event_type == 'page_requested' and not px_config.send_page_requested_activity then return end local pxdata = {}; pxdata['type'] = event_type; pxdata['headers'] = ngx.req.get_headers() pxdata['url'] = full_url; pxdata['px_app_id'] = px_config.px_appId; pxdata['timestamp'] = tostring(ngx_time()); pxdata['socket_ip'] = ngx.var.remote_addr; pxdata['details'] = details; if event_type == 'page_requested' then px_logger.debug("Sent page requested acitvity") end -- Experimental Buffer Support -- buffer.addEvent(pxdata) -- Perform the HTTP action if buflen >= maxbuflen then _M.submit(buffer.dumpEvents(), px_config.nginx_collector_path); end end return _M end return _M
--------------------------------------------- -- PerimeterX(www.perimeterx.com) Nginx plugin -- Version 1.1.4 -- Release date: 07.11.2016 ---------------------------------------------- local _M = {} function _M.load(config_file) local http = require "resty.http" local px_config = require (config_file) local px_logger = require ("px.utils.pxlogger").load(config_file) local buffer = require "px.utils.pxbuffer" local ngx_time = ngx.time local tostring = tostring local auth_token = px_config.auth_token -- Submit is the function to create the HTTP connection to the PX collector and POST the data function _M.submit(data, path) local px_server = px_config.px_server local px_port = px_config.px_port local ssl_enabled = px_config.ssl_enabled local px_debug = px_config.px_debug -- timeout in milliseconds local timeout = 2000 -- create new HTTP connection local httpc = http.new() httpc:set_timeout(timeout) local ok, err = httpc:connect(px_server, px_port) if not ok then px_logger.error("HTTPC connection error: " .. err) end -- Perform SSL/TLS handshake if ssl_enabled == true then local session, err = httpc:ssl_handshake() if not session then px_logger.error("HTTPC SSL handshare error: " .. err) end end -- Perform the HTTP requeset local res, err = httpc:request({ path = path, method = "POST", body = data, headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. auth_token } }) if not res then px_logger.error("Failed to make HTTP POST: " .. err) error("Failed to make HTTP POST: " .. err) elseif res.status ~= 200 then px_logger.error("Non 200 response code: " .. res.status) error("Non 200 response code: " .. res.status) else px_logger.debug("POST response status: " .. res.status) end -- Must read the response body to clear the buffer in order for set keepalive to work properly. local body = res:read_body() -- Check for connection reuse if px_debug == true then local times, err = httpc:get_reused_times() if not times then px_logger.debug("Error getting reuse times: " .. err) else px_logger.debug("Reused conn times: " .. times) end end -- set keepalive to ensure connection pooling local ok, err = httpc:set_keepalive() if not ok then px_logger.error("Failed to set keepalive: " .. err) end end function _M.send_to_perimeterx(event_type, details) local buflen = buffer.getBufferLength(); local maxbuflen = px_config.px_maxbuflen; local full_url = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri; if event_type == 'page_requested' and not px_config.send_page_requested_activity then return end local pxdata = {}; pxdata['type'] = event_type; pxdata['headers'] = ngx.req.get_headers() pxdata['url'] = full_url; pxdata['px_app_id'] = px_config.px_appId; pxdata['timestamp'] = tostring(ngx_time()); pxdata['socket_ip'] = ngx.var.remote_addr; pxdata['details'] = details; if event_type == 'page_requested' then px_logger.debug("Sent page requested acitvity") end -- Experimental Buffer Support -- buffer.addEvent(pxdata) -- Perform the HTTP action if buflen >= maxbuflen then _M.submit(buffer.dumpEvents(), px_config.nginx_collector_path); end end return _M end return _M
fix removal of read_body for keepalive
fix removal of read_body for keepalive Added px_cookie to Page Requested Activity
Lua
mit
PerimeterX/perimeterx-nginx-plugin
5338cba51953ba560e9f51c6696b17498cdf3e76
lua/settings/autocmds.lua
lua/settings/autocmds.lua
-- luacheck: globals unpack vim local nvim = require'nvim' local has = nvim.has local plugins = nvim.plugins local set_autocmd = nvim.autocmds.set_autocmd -- local set_command = nvim.commands.set_command -- local set_mapping = nvim.mappings.set_mapping if plugins['completor.vim'] == nil then set_autocmd{ event = {'BufNewFile', 'BufReadPre', 'BufEnter'}, pattern = '*', cmd = "if !exists('b:trim') | let b:trim = v:true | endif", group = 'CleanFile' } set_autocmd{ event = 'BufWritePre', pattern = '*', cmd = 'lua require"tools".files.clean_file()', group = 'CleanFile' } end if has('nvim-0.5') then set_autocmd{ event = 'TextYankPost', pattern = '*', cmd = [[silent! lua require'vim.highlight'.on_yank("IncSearch", 3000)]], group = 'YankHL' } end if require'sys'.name ~= 'windows' then set_autocmd{ event = 'BufNewFile', pattern = '*', cmd = [[lua require'settings.functions'.make_executable()]], group = 'LuaAutocmds', } set_autocmd{ event = 'Filetype', pattern = 'python,lua,sh,bash,zsh,tcsh,csh,ruby,perl', cmd = [[lua require'settings.functions'.make_executable()]], group = 'LuaAutocmds', } end set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'setlocal noswapfile nobackup noundofile bufhidden=', group = 'TerminalAutocmds' } set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'setlocal norelativenumber nonumber nocursorline', group = 'TerminalAutocmds' } set_autocmd{ event = 'VimResized', pattern = '*', cmd = 'wincmd =', group = 'AutoResize' } set_autocmd{ event = 'BufRead', pattern = '*', cmd = 'lua require"tools".buffers.last_position()', group = 'LastEditPosition' } set_autocmd{ event = 'BufNewFile', pattern = '*', cmd = 'lua require"tools".files.skeleton_filename()', group = 'Skeletons' } set_autocmd{ event = {'DirChanged', 'BufNewFile', 'BufReadPre', 'BufEnter', 'VimEnter'}, pattern = '*', cmd = 'lua require"tools".helpers.project_config(require"nvim".fn.deepcopy(require"nvim".v.event))', group = 'ProjectConfig' } set_autocmd{ event = 'CmdwinEnter', pattern = '*', cmd = 'nnoremap <CR> <CR>', group = 'LocalCR' } set_autocmd{ event = {'BufEnter','BufReadPost'}, pattern = '__LanguageClient__', cmd = 'nnoremap <silent> <nowait> <buffer> q :q!<CR>', group = 'QuickQuit' } set_autocmd{ event = {'BufEnter','BufWinEnter'}, pattern = '*', cmd = 'if &previewwindow | nnoremap <silent> <nowait> <buffer> q :q!<CR>| endif', group = 'QuickQuit' } set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'nnoremap <silent><nowait><buffer> q :q!<CR>', group = 'QuickQuit' } set_autocmd{ event = {'BufNewFile', 'BufReadPre', 'BufEnter'}, pattern = '/tmp/*', cmd = 'setlocal noswapfile nobackup noundofile', group = 'DisableTemps' } set_autocmd{ event = {'InsertLeave', 'CompleteDone'}, pattern = '*', cmd = 'if pumvisible() == 0 | pclose | endif', group = 'CloseMenu' } set_autocmd{ event = 'Filetype', pattern = 'lua', cmd = [[nnoremap <buffer><silent> <leader><leader>r :luafile %<cr>:echo "File reloaded"<cr>]], group = 'Reload', }
-- luacheck: globals unpack vim local nvim = require'nvim' local has = nvim.has local plugins = nvim.plugins local set_autocmd = nvim.autocmds.set_autocmd -- local set_command = nvim.commands.set_command -- local set_mapping = nvim.mappings.set_mapping if plugins['completor.vim'] == nil then set_autocmd{ event = {'BufNewFile', 'BufReadPre', 'BufEnter'}, pattern = '*', cmd = "if !exists('b:trim') | let b:trim = v:true | endif", group = 'CleanFile' } set_autocmd{ event = 'BufWritePre', pattern = '*', cmd = 'lua require"tools".files.clean_file()', group = 'CleanFile' } end if has('nvim-0.5') then set_autocmd{ event = 'TextYankPost', pattern = '*', cmd = [[lua vim.highlight.on_yank{higroup = "IncSearch", timeout = 2000}]], group = 'YankHL' } end if require'sys'.name ~= 'windows' then set_autocmd{ event = 'BufNewFile', pattern = '*', cmd = [[lua require'settings.functions'.make_executable()]], group = 'LuaAutocmds', } set_autocmd{ event = 'Filetype', pattern = 'python,lua,sh,bash,zsh,tcsh,csh,ruby,perl', cmd = [[lua require'settings.functions'.make_executable()]], group = 'LuaAutocmds', } end set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'setlocal noswapfile nobackup noundofile bufhidden=', group = 'TerminalAutocmds' } set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'setlocal norelativenumber nonumber nocursorline', group = 'TerminalAutocmds' } set_autocmd{ event = 'VimResized', pattern = '*', cmd = 'wincmd =', group = 'AutoResize' } set_autocmd{ event = 'BufRead', pattern = '*', cmd = 'lua require"tools".buffers.last_position()', group = 'LastEditPosition' } set_autocmd{ event = 'BufNewFile', pattern = '*', cmd = 'lua require"tools".files.skeleton_filename()', group = 'Skeletons' } set_autocmd{ event = {'DirChanged', 'BufNewFile', 'BufReadPre', 'BufEnter', 'VimEnter'}, pattern = '*', cmd = 'lua require"tools".helpers.project_config(require"nvim".fn.deepcopy(require"nvim".v.event))', group = 'ProjectConfig' } set_autocmd{ event = 'CmdwinEnter', pattern = '*', cmd = 'nnoremap <CR> <CR>', group = 'LocalCR' } set_autocmd{ event = {'BufEnter','BufReadPost'}, pattern = '__LanguageClient__', cmd = 'nnoremap <silent> <nowait> <buffer> q :q!<CR>', group = 'QuickQuit' } set_autocmd{ event = {'BufEnter','BufWinEnter'}, pattern = '*', cmd = 'if &previewwindow | nnoremap <silent> <nowait> <buffer> q :q!<CR>| endif', group = 'QuickQuit' } set_autocmd{ event = 'TermOpen', pattern = '*', cmd = 'nnoremap <silent><nowait><buffer> q :q!<CR>', group = 'QuickQuit' } set_autocmd{ event = {'BufNewFile', 'BufReadPre', 'BufEnter'}, pattern = '/tmp/*', cmd = 'setlocal noswapfile nobackup noundofile', group = 'DisableTemps' } set_autocmd{ event = {'InsertLeave', 'CompleteDone'}, pattern = '*', cmd = 'if pumvisible() == 0 | pclose | endif', group = 'CloseMenu' } set_autocmd{ event = 'Filetype', pattern = 'lua', cmd = [[nnoremap <buffer><silent> <leader><leader>r :luafile %<cr>:echo "File reloaded"<cr>]], group = 'Reload', }
fix: on_yack autocmd
fix: on_yack autocmd
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
7f3e311f73a80be96ae72c9ee75d7a416337bb86
mod_smacks/mod_smacks.lua
mod_smacks/mod_smacks.lua
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.clone(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = st.reply(queue[i]); if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, reply); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local timer = require "util.timer"; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local resume_timeout = 300; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.clone(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = st.reply(queue[i]); if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, reply); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then if not session.resumption_token then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end else session.hibernating = true; timer.add_task(resume_timeout, function () if session.hibernating then session.resumption_token = nil; sessionmanager.destroy_session(session); -- Re-destroy end end); return; -- Postpone destruction for now end end return _destroy_session(session, err); end
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
92432ec276e6e62101769ac305971531eb5a0163
share/lua/modules/simplexml.lua
share/lua/modules/simplexml.lua
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype = reader:next_node() while nodetype > 0 do --print(nodetype, reader:name()) if nodetype == 1 then local name = reader:name() local node = { name= '', attributes= {}, children= {} } node.name = name while reader:next_attr() == 0 do node.attributes[reader:name()] = reader:value() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local name = reader:name() local tmp = {} --print(name, tree.name, #parents) while name ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, reader:value()) end end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr = reader:next_attr() while attr ~= nil do node.attributes[attr] = reader:value() attr = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, reader:value()) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
Lua: fix module simplexml using the new API
Lua: fix module simplexml using the new API
Lua
lgpl-2.1
jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc
15c4ab632ab235fbad4e7055b6b767f2a9c95191
vi_motion.lua
vi_motion.lua
-- Support for motion key sequences local M = {} -- Implementations of the movements local vi_motions = require 'vi_motions' -- Wrap a possibly nested table, returning a proxy which modifies any value -- which isn't a nested table. A nested table is considered one with no -- integer keys (so #t == 0, or t[1] == nil). This allows storing values -- such as { 1,2,3 }. -- Parameters: -- tab: the table to wrap -- f: function to modify the value from tab. local function wrap_table(tab, f) result = setmetatable({wrapped=1, tt=tab}, { __index = function(t, k) local m = tab[k] if m == nil then return nil elseif type(m) == 'table' and m[1] == nil then return wrap_table(m, f) else -- Return a (possibly modified) value. return f(m) end end, }) return result end M.wrap_table = wrap_table -- Valid movement types MOV_LINE = 'linewise' MOV_INC = 'inclusive' MOV_EXC = 'exclusive' -- Postponed movement. The movement isn't complete (eg a search needs entering), and should -- be called with a continuation function, which will be called back later with the actual -- movement. MOV_LATER = 'later' -- Wrap a simple movement (eg word right) into one which takes a repeat -- count. local function r(f) return function(rep) if rep==nil or rep < 1 then rep = 1 end for i=1,rep do f() end end end M.r = r -- Table of register keys, returning true. local registers = setmetatable({splogde=123}, { __index = function(t, key) if string.match(key, "^%a$") then return key else return nil end end, }) local function restore_mark(reg) return { MOV_LINE, function() newpos = vi_mode.state.marks[reg] newpos = buffer:position_from_line(buffer:line_from_position(newpos)) if newpos ~= nil then buffer:goto_pos(newpos) end end, 1 } end -- Table of basic motion commands. Each is a list: -- { type, f, count } -- where f is a function to do the movement, type is one of -- MOV_LINE, MOV_EXC, MOV_INC for linewise, exclusive or inclusive, -- and count is the prefix count. This may be modified when wrapped. local motions = { h = { MOV_EXC, r(vi_motions.char_left), 1 }, l = { MOV_EXC, r(vi_motions.char_right), 1 }, j = { MOV_LINE, r(vi_motions.line_down), 1 }, k = { MOV_LINE, r(vi_motions.line_up), 1 }, w = { MOV_EXC, r(vi_motions.word_right), 1 }, b = { MOV_EXC, r(vi_motions.word_left), 1 }, e = { MOV_INC, r(vi_motions.word_end), 1 }, ['$'] = { MOV_INC, vi_motions.line_end, 1 }, ['^'] = { MOV_EXC, vi_motions.line_beg, 1 }, G = { MOV_LINE, vi_motions.goto_line, -1}, ["'"] = wrap_table(registers, restore_mark), ['%'] = { MOV_INC, vi_motions.match_brace, 1 }, -- Search motions n = { MOV_EXC, r(vi_motions.search_next), 1 }, N = { MOV_EXC, r(vi_motions.search_prev), 1 }, ['*'] = { MOV_EXC, r(vi_motions.search_word_next), 1 }, ['#'] = { MOV_EXC, r(vi_motions.search_word_prev), 1 }, ['/'] = { MOV_LATER, vi_motions.search_fwd, 1 }, ['?'] = { MOV_LATER, vi_motions.search_back, 1 }, } local MOTION_ZERO = { MOV_EXC, vi_motions.line_start, 1 } local digits = {} for i=0,9 do digits[i..''] = true end local PREFIX_COUNT = 'laksdjfasdlf' --{} -- unique table key local function index_digits(t, k) -- Intercept numbers to return an wrapped version. if digits[k] then local precount = t[PREFIX_COUNT] if precount == nil and k == '0' then return MOTION_ZERO -- special case - 0 is a motion by itself. end -- Rely on the master table never having PREFIX_COUNT. if precount == nil then local wrapped = t -- If this is the first digit, return a wrapped table local newtab = setmetatable({}, { --__index=wrapped, __index = function(wt, k) -- We already have a prefix count, so increment it. if digits[k] then wt[PREFIX_COUNT] = wt[PREFIX_COUNT] * 10 + (k+0) return t else local res = wrapped[k] if type(res)=='table' and res[1] then -- This is a motion, so apply the multiple res = { res[1], res[2], wt[PREFIX_COUNT] } end return res end end}) t = newtab precount = 0 end -- Update the count in the (possibly new) wrapper table precount = (precount * 10) + (k+0) t[PREFIX_COUNT] = precount -- Return the wrapper return t else -- not found return nil end end setmetatable(motions, { __index = index_digits, }) M.motions = motions -- Convert a simple movement desc into a selection movdesc function M.movf_to_self(movedesc) local movtype, mov_f, rep = table.unpack(movedesc) -- Convert simple movement into a range return { movtype, function(rep) local pos1 = buffer.current_pos mov_f(rep) local pos2 = buffer.current_pos if pos1 > pos2 then pos1, pos2 = pos2, pos1 end return pos1, pos2 end, rep } end -- Table of select (range) motions, used after some commands (eg d{motion}). -- Each entry is a function returning (start, end) positions. local sel_motions = setmetatable({ a = { w = { MOV_EXC, function() local pos = buffer.current_pos local s = buffer:word_start_position(pos, true) buffer:search_anchor() local e = buffer:search_next(buffer.FIND_REGEXP, "\\s\\w") + 1 return s, e end, 1}, -- W = function() return 'WORD' end, }, i = { w = { MOV_EXC, function() local pos = buffer.current_pos local s = buffer:word_start_position(pos, true) local e = buffer:word_end_position(pos) return s, e end, 1}, -- W = function() return 'WORD' end, }, }, { __index=wrap_table(motions, M.movf_to_self), }) M.sel_motions = sel_motions -- Return an entry suitable for the keys table which implements the vi motion -- commands. -- actions: a table of overrides (subcommands which aren't motions), eg for -- a 'd' handler, this would include 'd' (for 'dd', which deletes the current -- line). -- handler: Is called with a movdesc, and should return a no-parameter -- function which will implement the action. function M.bind_motions(actions, handler) local keyseq = {} setmetatable(actions, { __index=sel_motions }) return wrap_table(actions, handler) end return M
-- Support for motion key sequences local M = {} -- Implementations of the movements local vi_motions = require 'vi_motions' -- Wrap a possibly nested table, returning a proxy which modifies any value -- which isn't a nested table. A nested table is considered one with no -- integer keys (so #t == 0, or t[1] == nil). This allows storing values -- such as { 1,2,3 }. -- Parameters: -- tab: the table to wrap -- f: function to modify the value from tab. local function wrap_table(tab, f) result = setmetatable({wrapped=1, tt=tab}, { __index = function(t, k) local m = tab[k] if m == nil then return nil elseif type(m) == 'table' and m[1] == nil then return wrap_table(m, f) else -- Return a (possibly modified) value. return f(m) end end, }) return result end M.wrap_table = wrap_table -- Valid movement types MOV_LINE = 'linewise' MOV_INC = 'inclusive' MOV_EXC = 'exclusive' -- Postponed movement. The movement isn't complete (eg a search needs entering), and should -- be called with a continuation function, which will be called back later with the actual -- movement. MOV_LATER = 'later' -- Wrap a simple movement (eg word right) into one which takes a repeat -- count. local function r(f) return function(rep) if rep==nil or rep < 1 then rep = 1 end for i=1,rep do f() end end end M.r = r -- Table of register keys, returning true. local registers = setmetatable({splogde=123}, { __index = function(t, key) if string.match(key, "^%a$") then return key else return nil end end, }) local function restore_mark(reg) return { MOV_LINE, function() newpos = vi_mode.state.marks[reg] if newpos ~= nil then newpos = buffer:position_from_line(buffer:line_from_position(newpos)) end if newpos ~= nil then buffer:goto_pos(newpos) end end, 1 } end -- Table of basic motion commands. Each is a list: -- { type, f, count } -- where f is a function to do the movement, type is one of -- MOV_LINE, MOV_EXC, MOV_INC for linewise, exclusive or inclusive, -- and count is the prefix count. This may be modified when wrapped. local motions = { h = { MOV_EXC, r(vi_motions.char_left), 1 }, l = { MOV_EXC, r(vi_motions.char_right), 1 }, j = { MOV_LINE, r(vi_motions.line_down), 1 }, k = { MOV_LINE, r(vi_motions.line_up), 1 }, w = { MOV_EXC, r(vi_motions.word_right), 1 }, b = { MOV_EXC, r(vi_motions.word_left), 1 }, e = { MOV_INC, r(vi_motions.word_end), 1 }, ['$'] = { MOV_INC, vi_motions.line_end, 1 }, ['^'] = { MOV_EXC, vi_motions.line_beg, 1 }, G = { MOV_LINE, vi_motions.goto_line, -1}, ["'"] = wrap_table(registers, restore_mark), ['%'] = { MOV_INC, vi_motions.match_brace, 1 }, -- Search motions n = { MOV_EXC, r(vi_motions.search_next), 1 }, N = { MOV_EXC, r(vi_motions.search_prev), 1 }, ['*'] = { MOV_EXC, r(vi_motions.search_word_next), 1 }, ['#'] = { MOV_EXC, r(vi_motions.search_word_prev), 1 }, ['/'] = { MOV_LATER, vi_motions.search_fwd, 1 }, ['?'] = { MOV_LATER, vi_motions.search_back, 1 }, } local MOTION_ZERO = { MOV_EXC, vi_motions.line_start, 1 } local digits = {} for i=0,9 do digits[i..''] = true end local PREFIX_COUNT = 'laksdjfasdlf' --{} -- unique table key local function index_digits(t, k) -- Intercept numbers to return an wrapped version. if digits[k] then local precount = t[PREFIX_COUNT] if precount == nil and k == '0' then return MOTION_ZERO -- special case - 0 is a motion by itself. end -- Rely on the master table never having PREFIX_COUNT. if precount == nil then local wrapped = t -- If this is the first digit, return a wrapped table local newtab = setmetatable({}, { --__index=wrapped, __index = function(wt, k) -- We already have a prefix count, so increment it. if digits[k] then wt[PREFIX_COUNT] = wt[PREFIX_COUNT] * 10 + (k+0) return t else local res = wrapped[k] if type(res)=='table' and res[1] then -- This is a motion, so apply the multiple res = { res[1], res[2], wt[PREFIX_COUNT] } end return res end end}) t = newtab precount = 0 end -- Update the count in the (possibly new) wrapper table precount = (precount * 10) + (k+0) t[PREFIX_COUNT] = precount -- Return the wrapper return t else -- not found return nil end end setmetatable(motions, { __index = index_digits, }) M.motions = motions -- Convert a simple movement desc into a selection movdesc function M.movf_to_self(movedesc) local movtype, mov_f, rep = table.unpack(movedesc) -- Convert simple movement into a range return { movtype, function(rep) local pos1 = buffer.current_pos mov_f(rep) local pos2 = buffer.current_pos if pos1 > pos2 then pos1, pos2 = pos2, pos1 end return pos1, pos2 end, rep } end -- Table of select (range) motions, used after some commands (eg d{motion}). -- Each entry is a function returning (start, end) positions. local sel_motions = setmetatable({ a = { w = { MOV_EXC, function() local pos = buffer.current_pos local s = buffer:word_start_position(pos, true) buffer:search_anchor() local e = buffer:search_next(buffer.FIND_REGEXP, "\\s\\w") + 1 return s, e end, 1}, -- W = function() return 'WORD' end, }, i = { w = { MOV_EXC, function() local pos = buffer.current_pos local s = buffer:word_start_position(pos, true) local e = buffer:word_end_position(pos) return s, e end, 1}, -- W = function() return 'WORD' end, }, }, { __index=wrap_table(motions, M.movf_to_self), }) M.sel_motions = sel_motions -- Return an entry suitable for the keys table which implements the vi motion -- commands. -- actions: a table of overrides (subcommands which aren't motions), eg for -- a 'd' handler, this would include 'd' (for 'dd', which deletes the current -- line). -- handler: Is called with a movdesc, and should return a no-parameter -- function which will implement the action. function M.bind_motions(actions, handler) local keyseq = {} setmetatable(actions, { __index=sel_motions }) return wrap_table(actions, handler) end return M
Fix error when trying to jump to a mark that hasn't been saved.
Fix error when trying to jump to a mark that hasn't been saved.
Lua
mit
jugglerchris/textadept-vi,erig0/textadept-vi,jugglerchris/textadept-vi
7291aa3ee5999bc09c9fd3bee0bb85ec018ba608
build/Helpers.lua
build/Helpers.lua
-- This module checks for the all the project dependencies. action = _ACTION or "" depsdir = path.getabsolute("../deps"); srcdir = path.getabsolute("../src"); incdir = path.getabsolute("../include"); bindir = path.getabsolute("../bin"); examplesdir = path.getabsolute("../examples"); testsdir = path.getabsolute("../tests"); builddir = path.getabsolute("./" .. action); libdir = path.join(builddir, "lib"); gendir = path.join(builddir, "gen"); common_flags = { "Unicode", "Symbols" } msvc_buildflags = { } -- "/wd4190", "/wd4996", "/wd4530" gcc_buildflags = { "-std=c++11" } msvc_cpp_defines = { } function string.starts(str, start) return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function SetupNativeProject() location (path.join(builddir, "projects")) c = configuration "Debug" defines { "DEBUG" } targetsuffix "_d" configuration "Release" defines { "NDEBUG" } optimize "On" -- Compiler-specific options configuration "vs*" buildoptions { msvc_buildflags } defines { msvc_cpp_defines } configuration { "gmake" } buildoptions { gcc_buildflags } configuration { "macosx" } buildoptions { gcc_buildflags, "-stdlib=libc++", "-fvisibility-inlines-hidden" } -- OS-specific options configuration "Windows" defines { "WIN32", "_WINDOWS" } configuration(c) end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then print(string.format(" including %s", dep)) include(dep) end end end
-- This module checks for the all the project dependencies. action = _ACTION or "" depsdir = path.getabsolute("../deps"); srcdir = path.getabsolute("../src"); incdir = path.getabsolute("../include"); bindir = path.getabsolute("../bin"); examplesdir = path.getabsolute("../examples"); testsdir = path.getabsolute("../tests"); builddir = path.getabsolute("./" .. action); libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}"); gendir = path.join(builddir, "gen"); common_flags = { "Unicode", "Symbols" } msvc_buildflags = { } -- "/wd4190", "/wd4996", "/wd4530" gcc_buildflags = { "-std=c++11" } msvc_cpp_defines = { } function string.starts(str, start) return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function SetupNativeProject() location (path.join(builddir, "projects")) c = configuration "Debug" defines { "DEBUG" } configuration "Release" defines { "NDEBUG" } optimize "On" -- Compiler-specific options configuration "vs*" buildoptions { msvc_buildflags } defines { msvc_cpp_defines } configuration { "gmake" } buildoptions { gcc_buildflags } configuration { "macosx" } buildoptions { gcc_buildflags, "-stdlib=libc++", "-fvisibility-inlines-hidden" } -- OS-specific options configuration "Windows" defines { "WIN32", "_WINDOWS" } configuration(c) end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then print(string.format(" including %s", dep)) include(dep) end end end
Changed the output folder to be based on separate folders rather than name suffixes.
Changed the output folder to be based on separate folders rather than name suffixes.
Lua
mit
nalkaro/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,mono/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,Samana/CppSharp,mono/CppSharp,ddobrev/CppSharp,txdv/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,mono/CppSharp,ddobrev/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,txdv/CppSharp,xistoso/CppSharp,nalkaro/CppSharp,genuinelucifer/CppSharp,nalkaro/CppSharp,mono/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,imazen/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,u255436/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,u255436/CppSharp,Samana/CppSharp,mono/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,ddobrev/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,xistoso/CppSharp,zillemarco/CppSharp,imazen/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,inordertotest/CppSharp
dbc1e9e079a99c73821fe6391efca966a01e270d
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
#!/usr/bin/lua local config = require("lime.config") local network = require("lime.network") local utils = require("lime.utils") local libuci = require("uci") local fs = require("nixio.fs") local iwinfo = require("iwinfo") wireless = {} wireless.limeIfNamePrefix="lm_" wireless.wifiModeSeparator="-" function wireless.get_phy_mac(phy) local path = "/sys/class/ieee80211/"..phy.."/macaddress" local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","") return utils.split(mac, ":") end function wireless.clean() print("Clearing wireless config...") local uci = libuci:cursor() uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end) uci:save("wireless") end function wireless.scandevices() local devices = {} local uci = libuci:cursor() uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end) return devices end function wireless.is5Ghz(radio) local devModes = iwinfo.nl80211.hwmodelist(radio) return devModes.a or devModes.ac end wireless.availableModes = { adhoc=true, ap=true, apname=true, ieee80211s=true } function wireless.isMode(m) return wireless.availableModes[m] end function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras) --! checks("table", "string", "?string", "?table") --! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks nameSuffix = nameSuffix or "" local radioName = radio[".name"] local phyIndex = radioName:match("%d+") local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix --! sanitize generated ifname for constructing uci section name --! because only alphanumeric and underscores are allowed local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_") local uci = libuci:cursor() uci:set("wireless", wirelessInterfaceName, "wifi-iface") uci:set("wireless", wirelessInterfaceName, "mode", mode) uci:set("wireless", wirelessInterfaceName, "device", radioName) uci:set("wireless", wirelessInterfaceName, "ifname", ifname) uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName) if extras then for key, value in pairs(extras) do uci:set("wireless", wirelessInterfaceName, key, value) end end uci:save("wireless") return uci:get_all("wireless", wirelessInterfaceName) end function wireless.configure() local specificRadios = {} config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end) local allRadios = wireless.scandevices() for _,radio in pairs(allRadios) do local radioName = radio[".name"] local specRadio = specificRadios[radioName] local modes = config.get("wifi", "modes") local options = config.get_all("wifi") if specRadio then modes = specRadio["modes"] options = specRadio end --! If manual mode is used toghether with other modes it results in an --! unpredictable behaviour if modes[1] ~= "manual" then local freqSuffix = "_2ghz" local ignoredSuffix = "_5ghz" if wireless.is5Ghz(radioName) then freqSuffix = "_5ghz" ignoredSuffix = "_2ghz" end --! up to 10km links by default local distance = options["distance"..freqSuffix] or options["distance"] or 10000 local htmode = options["htmode"..freqSuffix] or options["htmode"] local uci = libuci:cursor() uci:set("wireless", radioName, "disabled", 0) uci:set("wireless", radioName, "distance", distance) uci:set("wireless", radioName, "noscan", 1) uci:set("wireless", radioName, "channel", options["channel"..freqSuffix]) if options["country"] then uci:set("wireless", radioName, "country", options["country"]) end if htmode then uci:set("wireless", radioName, "htmode", htmode) end uci:save("wireless") for _,modeName in pairs(modes) do local args = {} local mode = require("lime.mode."..modeName) for key,value in pairs(options) do local keyPrefix = utils.split(key, "_")[1] local isGoodOption = ( (key ~= "modes") and (not key:match("^%.")) and (not key:match("channel")) and (not key:match("country")) and (not key:match("htmode")) and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName)) and (not key:match(ignoredSuffix)) ) if isGoodOption then local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "") if nk == "ssid" then value = utils.applyHostnameTemplate(value) value = utils.applyMacTemplate16(value, network.primary_mac()) value = string.sub(value, 1, 32) end args[nk] = value end end mode.setup_radio(radio, args) end end end end return wireless
#!/usr/bin/lua local config = require("lime.config") local network = require("lime.network") local utils = require("lime.utils") local libuci = require("uci") local fs = require("nixio.fs") local iwinfo = require("iwinfo") wireless = {} wireless.limeIfNamePrefix="lm_" wireless.wifiModeSeparator="-" function wireless.get_phy_mac(phy) local path = "/sys/class/ieee80211/"..phy.."/macaddress" local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","") return utils.split(mac, ":") end function wireless.clean() print("Clearing wireless config...") local uci = libuci:cursor() uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end) uci:save("wireless") end function wireless.scandevices() local devices = {} local uci = libuci:cursor() uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end) return devices end function wireless.is5Ghz(radio) local devModes = iwinfo.nl80211.hwmodelist(radio) return devModes.a or devModes.ac end wireless.availableModes = { adhoc=true, ap=true, apname=true, ieee80211s=true } function wireless.isMode(m) return wireless.availableModes[m] end function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras) --! checks("table", "string", "?string", "?table") --! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks nameSuffix = nameSuffix or "" local radioName = radio[".name"] local phyIndex = radioName:match("%d+") local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix --! sanitize generated ifname for constructing uci section name --! because only alphanumeric and underscores are allowed local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_") local uci = libuci:cursor() uci:set("wireless", wirelessInterfaceName, "wifi-iface") uci:set("wireless", wirelessInterfaceName, "mode", mode) uci:set("wireless", wirelessInterfaceName, "device", radioName) uci:set("wireless", wirelessInterfaceName, "ifname", ifname) uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName) if extras then for key, value in pairs(extras) do uci:set("wireless", wirelessInterfaceName, key, value) end end uci:save("wireless") return uci:get_all("wireless", wirelessInterfaceName) end function wireless.configure() local specificRadios = {} config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end) local allRadios = wireless.scandevices() for _,radio in pairs(allRadios) do local radioName = radio[".name"] local specRadio = specificRadios[radioName] local modes = config.get("wifi", "modes") local options = config.get_all("wifi") if specRadio then modes = specRadio["modes"] options = specRadio end --! If manual mode is used toghether with other modes it results in an --! unpredictable behaviour if modes[1] ~= "manual" then local freqSuffix = "_2ghz" local ignoredSuffix = "_5ghz" if wireless.is5Ghz(radioName) then freqSuffix = "_5ghz" ignoredSuffix = "_2ghz" end --! up to 10km links by default local distance = options["distance"..freqSuffix] or options["distance"] or 10000 local htmode = options["htmode"..freqSuffix] or options["htmode"] local channel = options["channel"..freqSuffix] or options["channel"] local uci = libuci:cursor() uci:set("wireless", radioName, "disabled", 0) uci:set("wireless", radioName, "distance", distance) uci:set("wireless", radioName, "noscan", 1) uci:set("wireless", radioName, "channel", channel) if options["country"] then uci:set("wireless", radioName, "country", options["country"]) end if htmode then uci:set("wireless", radioName, "htmode", htmode) end uci:save("wireless") for _,modeName in pairs(modes) do local args = {} local mode = require("lime.mode."..modeName) for key,value in pairs(options) do local keyPrefix = utils.split(key, "_")[1] local isGoodOption = ( (key ~= "modes") and (not key:match("^%.")) and (not key:match("channel")) and (not key:match("country")) and (not key:match("htmode")) and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName)) and (not key:match(ignoredSuffix)) ) if isGoodOption then local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "") if nk == "ssid" then value = utils.applyHostnameTemplate(value) value = utils.applyMacTemplate16(value, network.primary_mac()) value = string.sub(value, 1, 32) end args[nk] = value end end mode.setup_radio(radio, args) end end end end return wireless
wireless.lua: fallback channel option
wireless.lua: fallback channel option If specific radio information are set without a suffix the current configuration fails. To fix this if *channel_<suffix>* ins't found it will fall back to *channel*
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
2dd7d5feb27d2df27db12ba20d70aff61fd941c8
vstreamers.lua
vstreamers.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 == "video" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "/"..item_value.."[^0-9]") then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if item_type == "video" then if string.match(url, "vstreamers%.com/v/[0-9]+") then local newurl = "http://vstreamers.com/js/load_comms.php" if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then table.insert(urls, { url=newurl, post_data="page=1&u_id="..item_value.."&ch_cm_left=false&type=v" }) addedtolist[newurl] = true end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local 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 == "video" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if (string.match(url, "/"..item_value) and not string.match(url, "/"..item_value.."[0-9]+") then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if item_type == "video" then if string.match(url, "vstreamers%.com/v/[0-9]+") then local newurl = "http://vstreamers.com/js/load_comms.php" if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then table.insert(urls, { url=newurl, post_data="page=1&u_id="..item_value.."&ch_cm_left=false&type=v" }) addedtolist[newurl] = true end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
vstreamers.lua: little fix
vstreamers.lua: little fix
Lua
unlicense
ArchiveTeam/vstreamers-grab,ArchiveTeam/vstreamers-grab
701e1cc1e6bee7e3560a9b27f635de3c76c03b46
put.lua
put.lua
-- Put(1, queue, jid, klass, data, now, delay, [priority, p], [tags, t], [retries, r], [depends, '[...]']) -- ------------------------------------------------------------------------------------------------------- -- This script takes the name of the queue and then the -- info about the work item, and makes sure that it's -- enqueued. -- -- At some point, I'd like to able to provide functionality -- that enables this to generate a unique ID for this piece -- of work. As such, client libraries should not expose -- setting the id from the user, as this is an implementation -- detail that's likely to change and users should not grow -- to depend on it. -- -- Keys: -- 1) queue name -- Args: -- 1) jid -- 2) klass -- 3) data -- 4) now -- 5) delay -- *) [priority, p], [tags, t], [retries, r], [depends, '[...]'] if #KEYS ~= 1 then if #KEYS < 1 then error('Put(): Expected 1 KEYS argument') else error('Put(): Got ' .. #KEYS .. ', expected 1 KEYS argument') end end local queue = assert(KEYS[1] , 'Put(): Key "queue" missing') local jid = assert(ARGV[1] , 'Put(): Arg "jid" missing') local klass = assert(ARGV[2] , 'Put(): Arg "klass" missing') local data = assert(cjson.decode(ARGV[3]) , 'Put(): Arg "data" missing or not JSON: ' .. tostring(ARGV[3])) local now = assert(tonumber(ARGV[4]) , 'Put(): Arg "now" missing or not a number: ' .. tostring(ARGV[4])) local delay = assert(tonumber(ARGV[5]) , 'Put(): Arg "delay" not a number: ' .. tostring(ARGV[5])) -- Read in all the optional parameters local options = {} for i = 6, #ARGV, 2 do options[ARGV[i]] = ARGV[i + 1] end -- Let's see what the old priority, history and tags were local history, priority, tags, oldqueue, state, failure, retries, worker = unpack(redis.call('hmget', 'ql:j:' .. jid, 'history', 'priority', 'tags', 'queue', 'state', 'failure', 'retries', 'worker')) -- Sanity check on optional args retries = assert(tonumber(options['retries'] or retries or 5) , 'Put(): Arg "retries" not a number: ' .. tostring(options['retries'])) tags = assert(cjson.decode(options['tags'] or tags or '[]' ), 'Put(): Arg "tags" not JSON' .. tostring(options['tags'])) priority = assert(tonumber(options['priority'] or priority or 0), 'Put(): Arg "priority" not a number' .. tostring(options['priority'])) local depends = assert(cjson.decode(options['depends'] or '[]') , 'Put(): Arg "depends" not JSON: ' .. tostring(options['depends'])) -- Delay and depends are not allowed together if delay > 0 and #depends > 0 then error('Put(): "delay" and "depends" are not allowed to be used together') end -- Update the history to include this new change local history = cjson.decode(history or '{}') table.insert(history, { q = queue, put = math.floor(now) }) -- If this item was previously in another queue, then we should remove it from there if oldqueue then redis.call('zrem', 'ql:q:' .. oldqueue .. '-work', jid) redis.call('zrem', 'ql:q:' .. oldqueue .. '-locks', jid) redis.call('zrem', 'ql:q:' .. oldqueue .. '-scheduled', jid) end -- If this had previously been given out to a worker, -- make sure to remove it from that worker's jobs if worker then redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) end -- If the job was previously in the 'completed' state, then we should remove -- it from being enqueued for destructination if state == 'complete' then redis.call('zrem', 'ql:completed', jid) end -- Add this job to the list of jobs tagged with whatever tags were supplied for i, tag in ipairs(tags) do redis.call('zadd', 'ql:t:' .. tag, now, jid) redis.call('zincrby', 'ql:tags', 1, tag) end -- If we're in the failed state, remove all of our data if state == 'failed' then failure = cjson.decode(failure) -- We need to make this remove it from the failed queues redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end -- The bin is midnight of the provided day -- 24 * 60 * 60 = 86400 local bin = failure.when - (failure.when % 86400) -- We also need to decrement the stats about the queue on -- the day that this failure actually happened. redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed' , -1) end -- First, let's save its data redis.call('hmset', 'ql:j:' .. jid, 'jid' , jid, 'klass' , klass, 'data' , cjson.encode(data), 'priority' , priority, 'tags' , cjson.encode(tags), 'state' , ((delay > 0) and 'scheduled') or 'waiting', 'worker' , '', 'expires' , 0, 'queue' , queue, 'retries' , retries, 'remaining', retries, 'history' , cjson.encode(history)) -- These are the jids we legitimately have to wait on for i, j in ipairs(depends) do -- Make sure it's something other than 'nil' or complete. local state = redis.call('hget', 'ql:j:' .. j, 'state') if (state and state ~= 'complete') then redis.call('sadd', 'ql:j:' .. j .. '-dependents' , jid) redis.call('sadd', 'ql:j:' .. jid .. '-dependencies', j) end end -- Now, if a delay was provided, and if it's in the future, -- then we'll have to schedule it. Otherwise, we're just -- going to add it to the work queue. if delay > 0 then redis.call('zadd', 'ql:q:' .. queue .. '-scheduled', now + delay, jid) else if redis.call('scard', 'ql:j:' .. jid .. '-dependencies') > 0 then redis.call('zadd', 'ql:q:' .. queue .. '-depends', now, jid) redis.call('hset', 'ql:j:' .. jid, 'state', 'depends') else redis.call('zadd', 'ql:q:' .. queue .. '-work', priority + (now / 10000000000), jid) end end -- Lastly, we're going to make sure that this item is in the -- set of known queues. We should keep this sorted by the -- order in which we saw each of these queues if redis.call('zscore', 'ql:queues', queue) == false then redis.call('zadd', 'ql:queues', now, queue) end return jid
-- Put(1, queue, jid, klass, data, now, delay, [priority, p], [tags, t], [retries, r], [depends, '[...]']) -- ------------------------------------------------------------------------------------------------------- -- This script takes the name of the queue and then the -- info about the work item, and makes sure that it's -- enqueued. -- -- At some point, I'd like to able to provide functionality -- that enables this to generate a unique ID for this piece -- of work. As such, client libraries should not expose -- setting the id from the user, as this is an implementation -- detail that's likely to change and users should not grow -- to depend on it. -- -- Keys: -- 1) queue name -- Args: -- 1) jid -- 2) klass -- 3) data -- 4) now -- 5) delay -- *) [priority, p], [tags, t], [retries, r], [depends, '[...]'] if #KEYS ~= 1 then if #KEYS < 1 then error('Put(): Expected 1 KEYS argument') else error('Put(): Got ' .. #KEYS .. ', expected 1 KEYS argument') end end local queue = assert(KEYS[1] , 'Put(): Key "queue" missing') local jid = assert(ARGV[1] , 'Put(): Arg "jid" missing') local klass = assert(ARGV[2] , 'Put(): Arg "klass" missing') local data = assert(cjson.decode(ARGV[3]) , 'Put(): Arg "data" missing or not JSON: ' .. tostring(ARGV[3])) local now = assert(tonumber(ARGV[4]) , 'Put(): Arg "now" missing or not a number: ' .. tostring(ARGV[4])) local delay = assert(tonumber(ARGV[5]) , 'Put(): Arg "delay" not a number: ' .. tostring(ARGV[5])) -- Read in all the optional parameters local options = {} for i = 6, #ARGV, 2 do options[ARGV[i]] = ARGV[i + 1] end -- Let's see what the old priority, history and tags were local history, priority, tags, oldqueue, state, failure, retries, worker = unpack(redis.call('hmget', 'ql:j:' .. jid, 'history', 'priority', 'tags', 'queue', 'state', 'failure', 'retries', 'worker')) -- Sanity check on optional args retries = assert(tonumber(options['retries'] or retries or 5) , 'Put(): Arg "retries" not a number: ' .. tostring(options['retries'])) tags = assert(cjson.decode(options['tags'] or tags or '[]' ), 'Put(): Arg "tags" not JSON' .. tostring(options['tags'])) priority = assert(tonumber(options['priority'] or priority or 0), 'Put(): Arg "priority" not a number' .. tostring(options['priority'])) local depends = assert(cjson.decode(options['depends'] or '[]') , 'Put(): Arg "depends" not JSON: ' .. tostring(options['depends'])) -- Delay and depends are not allowed together if delay > 0 and #depends > 0 then error('Put(): "delay" and "depends" are not allowed to be used together') end -- Update the history to include this new change local history = cjson.decode(history or '{}') table.insert(history, { q = queue, put = math.floor(now) }) -- If this item was previously in another queue, then we should remove it from there if oldqueue then redis.call('zrem', 'ql:q:' .. oldqueue .. '-work', jid) redis.call('zrem', 'ql:q:' .. oldqueue .. '-locks', jid) redis.call('zrem', 'ql:q:' .. oldqueue .. '-scheduled', jid) redis.call('zrem', 'ql:q:' .. oldqueue .. '-depends', jid) end -- If this had previously been given out to a worker, -- make sure to remove it from that worker's jobs if worker then redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) end -- If the job was previously in the 'completed' state, then we should remove -- it from being enqueued for destructination if state == 'complete' then redis.call('zrem', 'ql:completed', jid) end -- Add this job to the list of jobs tagged with whatever tags were supplied for i, tag in ipairs(tags) do redis.call('zadd', 'ql:t:' .. tag, now, jid) redis.call('zincrby', 'ql:tags', 1, tag) end -- If we're in the failed state, remove all of our data if state == 'failed' then failure = cjson.decode(failure) -- We need to make this remove it from the failed queues redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end -- The bin is midnight of the provided day -- 24 * 60 * 60 = 86400 local bin = failure.when - (failure.when % 86400) -- We also need to decrement the stats about the queue on -- the day that this failure actually happened. redis.call('hincrby', 'ql:s:stats:' .. bin .. ':' .. queue, 'failed' , -1) end -- First, let's save its data redis.call('hmset', 'ql:j:' .. jid, 'jid' , jid, 'klass' , klass, 'data' , cjson.encode(data), 'priority' , priority, 'tags' , cjson.encode(tags), 'state' , ((delay > 0) and 'scheduled') or 'waiting', 'worker' , '', 'expires' , 0, 'queue' , queue, 'retries' , retries, 'remaining', retries, 'history' , cjson.encode(history)) -- These are the jids we legitimately have to wait on for i, j in ipairs(depends) do -- Make sure it's something other than 'nil' or complete. local state = redis.call('hget', 'ql:j:' .. j, 'state') if (state and state ~= 'complete') then redis.call('sadd', 'ql:j:' .. j .. '-dependents' , jid) redis.call('sadd', 'ql:j:' .. jid .. '-dependencies', j) end end -- Now, if a delay was provided, and if it's in the future, -- then we'll have to schedule it. Otherwise, we're just -- going to add it to the work queue. if delay > 0 then redis.call('zadd', 'ql:q:' .. queue .. '-scheduled', now + delay, jid) else if redis.call('scard', 'ql:j:' .. jid .. '-dependencies') > 0 then redis.call('zadd', 'ql:q:' .. queue .. '-depends', now, jid) redis.call('hset', 'ql:j:' .. jid, 'state', 'depends') else redis.call('zadd', 'ql:q:' .. queue .. '-work', priority + (now / 10000000000), jid) end end -- Lastly, we're going to make sure that this item is in the -- set of known queues. We should keep this sorted by the -- order in which we saw each of these queues if redis.call('zscore', 'ql:queues', queue) == false then redis.call('zadd', 'ql:queues', now, queue) end return jid
Bug fix around dependents reporting.
Bug fix around dependents reporting. If a job has a dependency, but then is moved queues, it was still getting reported under the original queue's jobs with dependencies.
Lua
mit
seomoz/qless-core,backupify/qless-core,seomoz/qless-core
2470970644b344786ef803948d31f9b186cfa094
src_trunk/resources/admin-system/c_overlay.lua
src_trunk/resources/admin-system/c_overlay.lua
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do local level = getElementData( value, "adminlevel" ) if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end if getElementData( localPlayer, "adminlevel" ) > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false )
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do local level = getElementData( value, "adminlevel" ) if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end local adminlevel = getElementData( localPlayer, "adminlevel" ) if adminlevel > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false )
Fixed a comparison error in admin overlay
Fixed a comparison error in admin overlay git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1572 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
59d3c32e3571dd65851006bae0c405747551057f
lexers/lua.lua
lexers/lua.lua
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- Lua LPeg lexer. -- Original written by Peter Odding, 2007/04/04. local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) local longstring = #('[[' + ('[' * P('=')^0 * '[')) local longstring = longstring * P(function(input, index) local level = input:match('^%[(=*)%[', index) if level then local _, stop = input:find(']'..level..']', index, true) return stop and stop + 1 or #input + 1 end end) -- Comments. local line_comment = '--' * l.nonnewline^0 local block_comment = '--' * longstring local comment = token(l.COMMENT, block_comment + line_comment) -- Strings. local sq_str = l.delimited_range("'", '\\', true) local dq_str = l.delimited_range('"', '\\', true) local string = token(l.STRING, sq_str + dq_str) + token('longstring', longstring) -- Numbers. local lua_integer = P('-')^-1 * (l.hex_num + l.dec_num) local number = token(l.NUMBER, l.float + lua_integer) -- Keywords. local keyword = token(l.KEYWORD, word_match { 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' }) -- Functions. local func = token(l.FUNCTION, word_match { 'assert', 'collectgarbage', 'dofile', 'error', 'getfenv', 'getmetatable', 'ipairs', 'load', 'loadfile', 'loadstring', 'module', 'next', 'pairs', 'pcall', 'print', 'rawequal', 'rawget', 'rawset', 'require', 'setfenv', 'setmetatable', 'tonumber', 'tostring', 'type', 'unpack', 'xpcall' }) -- Constants. local constant = token(l.CONSTANT, word_match { '_G', '_VERSION' }) -- Identifiers. local word = (R('AZ', 'az', '\127\255') + '_') * (l.alnum + '_')^0 local identifier = token(l.IDENTIFIER, word) -- Operators. local operator = token(l.OPERATOR, '~=' + S('+-*/%^#=<>;:,.{}[]()')) _rules = { { 'whitespace', ws }, { 'keyword', keyword }, { 'function', func }, { 'constant', constant }, { 'identifier', identifier }, { 'string', string }, { 'comment', comment }, { 'number', number }, { 'operator', operator }, { 'any_char', l.any_char }, } _tokenstyles = { { 'longstring', l.style_string } } _foldsymbols = { _patterns = { '%l+', '[%({%)}%[%]]' }, [l.KEYWORD] = { ['if'] = 1, ['do'] = 1, ['function'] = 1, ['end'] = -1, ['repeat'] = 1, ['until'] = -1 }, [l.COMMENT] = { ['['] = 1, [']'] = -1 }, longstring = { ['['] = 1, [']'] = -1 }, [l.OPERATOR] = { ['('] = 1, ['{'] = 1, [')'] = -1, ['}'] = -1 } }
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- Lua LPeg lexer. -- Original written by Peter Odding, 2007/04/04. local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) local longstring = #('[[' + ('[' * P('=')^0 * '[')) * P(function(input, index) local level = input:match('^%[(=*)%[', index) if level then local _, stop = input:find(']'..level..']', index, true) return stop and stop + 1 or #input + 1 end end) -- Comments. local line_comment = '--' * l.nonnewline^0 local block_comment = '--' * longstring local comment = token(l.COMMENT, block_comment + line_comment) -- Strings. local sq_str = l.delimited_range("'", '\\', true) local dq_str = l.delimited_range('"', '\\', true) local string = token(l.STRING, sq_str + dq_str) + token('longstring', longstring) -- Numbers. local lua_integer = P('-')^-1 * (l.hex_num + l.dec_num) local number = token(l.NUMBER, l.float + lua_integer) -- Keywords. local keyword = token(l.KEYWORD, word_match { 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' }) -- Functions. local func = token(l.FUNCTION, word_match { 'assert', 'collectgarbage', 'dofile', 'error', 'getfenv', 'getmetatable', 'ipairs', 'load', 'loadfile', 'loadstring', 'module', 'next', 'pairs', 'pcall', 'print', 'rawequal', 'rawget', 'rawset', 'require', 'setfenv', 'setmetatable', 'tonumber', 'tostring', 'type', 'unpack', 'xpcall' }) -- Constants. local constant = token(l.CONSTANT, word_match { '_G', '_VERSION' }) -- Identifiers. local word = (R('AZ', 'az', '\127\255') + '_') * (l.alnum + '_')^0 local identifier = token(l.IDENTIFIER, word) -- Operators. local operator = token(l.OPERATOR, '~=' + S('+-*/%^#=<>;:,.{}[]()')) _rules = { { 'whitespace', ws }, { 'keyword', keyword }, { 'function', func }, { 'constant', constant }, { 'identifier', identifier }, { 'string', string }, { 'comment', comment }, { 'number', number }, { 'operator', operator }, { 'any_char', l.any_char }, } _tokenstyles = { { 'longstring', l.style_string } } local function fold_longcomment(text, pos, line, s, match) if match == '[' then if line:find('^%[=*%[', s) then return 1 end elseif match == ']' then if line:find('^%]=*%]', s) then return -1 end end return 0 end _foldsymbols = { _patterns = { '%l+', '[%({%)}]', '[%[%]]' }, [l.KEYWORD] = { ['if'] = 1, ['do'] = 1, ['function'] = 1, ['end'] = -1, ['repeat'] = 1, ['until'] = -1 }, [l.COMMENT] = { ['['] = fold_longcomment, [']'] = fold_longcomment }, longstring = { ['['] = 1, [']'] = -1 }, [l.OPERATOR] = { ['('] = 1, ['{'] = 1, [')'] = -1, ['}'] = -1 } }
Fixed bug with folding longcomments; lexers/lua.lua
Fixed bug with folding longcomments; lexers/lua.lua
Lua
mit
rgieseke/scintillua
6dd0495ad347256bc164d29d27c9ac89c7b8c347
src/lluv/pg/converter.lua
src/lluv/pg/converter.lua
local prequire = function(m) local ok, m = pcall(require, m) if ok then return m end end local struct = require "lluv.pg.utils.bin" local cjson = prequire"cjson" local function unpack_int(n) local fmt = '>i' .. n return function(data) return (struct.unpack(fmt, data)) end; end local function pack_int(n) local fmt = '>i' .. n return function(value) return struct.pack(fmt, value) end; end local function fail(msg) return function() error(msg, 3) end end local function pass(data) return data end local decode_int = function(n) return { [0] = tonumber; [1] = unpack_int(n) } end local encode_int = function(n) return { [0] = tostring; [1] = pack_int(n); } end local decode_float = function(n) assert( (n == 4) or (n == 8) ) --[[ local fmt if n == struct.size('f') then fmt = 'f' elseif n == struct.size('d') then fmt = 'f' end --]] local bin if not fmt then bin = fail(string.format('Unsupported binary mode for float%d type', n)) else bin = function(data) return struct.unpack(fmt, data) end; end return { [0] = tonumber; [1] = bin; } end local encode_float = function(n) assert( (n == 4) or (n == 8) ) --[[ local fmt if n == struct.size('f') then fmt = 'f' elseif n == struct.size('d') then fmt = 'f' end --]] local bin if not fmt then bin = fail(string.format('Unsupported binary mode for float%d type', n)) else bin = function(value) return struct.pack(fmt, value) end; end return { [0] = tostring; [1] = bin; } end local decode_bool = function() return { [0] = function(data) return data ~= 'f' end; [1] = function(data) return data ~= '\0' end; } end local encode_bool = function() return { [0] = function(value) return value and 't' or 'f' end; [1] = function(value) return value and '\1' or '\0' end; } end local decode_bin = function() return {[0] = pass; [1] = pass;} end local encode_bin = function() return {[0] = pass; [1] = pass;} end local decode_json = function() return {[0] = cjson.decode; [1] = cjson.decode;} end local encode_json = function() return {[0] = cjson.encode; [1] = cjson.encode;} end local function decode_numeric_bin(data) local ndigits, weight, sign, dscale, pos = struct.unpack('>i2i2i2i2', data ) local r = sign == 0 and '' or '-' for i = 1, ndigits do local d d, pos = struct.unpack('>i2', data, pos) r = r .. tostring(d) end if dscale > 0 then r = string.sub(r, 1, -dscale - 1) .. '.' .. string.sub(r, -dscale) end return r end local decode_numeric = function() return { [0] = pass; [1] = decode_numeric_bin; } end local encode_numeric = function(n) return { [0] = tostring; [1] = fail('Unsupported binary mode for numeric type'); } end local decode_date = function(n) return { [0] = pass; [1] = n == 12 and decode_int(n); } end local encode_date = function(n) return { [0] = tostring; [1] = fail('Unsupported binary mode for numeric type'); } end local function int(n) return { encode = encode_int(n); decode = decode_int(n); } end local function float(n) return { encode = encode_float(n); decode = decode_float(n); } end local function bool() return { encode = encode_bool(); decode = decode_bool(); } end local function bin() return { encode = encode_bin(); decode = decode_bin(); } end local function json() if not cjson then return end return { encode = encode_json(); decode = decode_json(); } end local function numeric() return { encode = encode_numeric(); decode = decode_numeric(); } end local function date(n) return { encode = encode_date(n); decode = decode_date(n); } end local converters = { bool = bool(); int2 = int(2); int4 = int(4); int8 = int(8); regproc = int(4); oid = int(4); tid = int(4); xid = int(4); cid = int(4); json = json(); jsonb = json(); float4 = float(4); float8 = float(8); numeric = numeric(); abstime = date(4); date = date(4); time = date(8); timestamp = date(8); timestamptz = date(8); time_stamp = date(8); -- timetz = date(12); -- interval = date(16); -- tinterval = date(12); text = bin(); bytea = bin(); char = bin(); name = bin(); xml = bin(); -- point -- lseg -- path -- box -- polygon -- line -- cidr -- abstime -- reltime -- tinterval -- unknown -- circle -- money -- macaddr -- inet -- aclitem -- bpchar -- varchar -- bit -- varbit -- refcursor -- regprocedure -- regoper -- regoperator -- regclass -- regtype -- record -- cstring -- uuid -- txid_snapshot -- pg_lsn -- tsvector -- tsquery -- gtsvector -- regconfig -- regdictionary -- int4range -- numrange -- tsrange -- tstzrange -- daterange -- int8range -- regnamespace -- regrole }; for k, v in pairs(converters) do if not k:find('array::') then converters['array::' .. k] = v end end local function get_decoder(typ) local tname, mode = typ[1], typ[3] local converter = converters[tname] if not converter then return end return converter.decode and converter.decode[mode] end local function get_encoder(typ) local tname, mode = typ[1], typ[3] local converter = converters[tname] if not converter then return end return converter.encode and converter.encode[mode] end return { encoder = get_encoder; decoder = get_decoder; }
local prequire = function(m) local ok, m = pcall(require, m) if ok then return m end end local struct = require "lluv.pg.utils.bin" local cjson = prequire"cjson" local function unpack_int(n) local fmt = '>i' .. n return function(data) return (struct.unpack(fmt, data)) end; end local function pack_int(n) local fmt = '>i' .. n return function(value) return struct.pack(fmt, value) end; end local function fail(msg) return function() error(msg, 3) end end local function pass(data) return data end local decode_int = function(n) return { [0] = tonumber; [1] = unpack_int(n) } end local encode_int = function(n) return { [0] = tostring; [1] = pack_int(n); } end local decode_float = function(n) assert( (n == 4) or (n == 8) ) --[[ local fmt if n == struct.size('f') then fmt = 'f' elseif n == struct.size('d') then fmt = 'f' end --]] local bin if not fmt then bin = fail(string.format('Unsupported binary mode for float%d type', n)) else bin = function(data) return struct.unpack(fmt, data) end; end return { [0] = tonumber; [1] = bin; } end local encode_float = function(n) assert( (n == 4) or (n == 8) ) --[[ local fmt if n == struct.size('f') then fmt = 'f' elseif n == struct.size('d') then fmt = 'f' end --]] local bin if not fmt then bin = fail(string.format('Unsupported binary mode for float%d type', n)) else bin = function(value) return struct.pack(fmt, value) end; end return { [0] = tostring; [1] = bin; } end local decode_bool = function() return { [0] = function(data) return data ~= 'f' end; [1] = function(data) return data ~= '\0' end; } end local encode_bool = function() return { [0] = function(value) return value and 't' or 'f' end; [1] = function(value) return value and '\1' or '\0' end; } end local decode_bin = function() return {[0] = pass; [1] = pass;} end local encode_bin = function() return {[0] = pass; [1] = pass;} end local decode_json = function() return {[0] = cjson.decode; [1] = cjson.decode;} end local encode_json = function() return {[0] = cjson.encode; [1] = cjson.encode;} end local function decode_numeric_bin(data) local ndigits, weight, sign, dscale, pos = struct.unpack('>i2i2i2i2', data ) local r = sign == 0 and '' or '-' for i = 1, ndigits do local d d, pos = struct.unpack('>i2', data, pos) r = r .. tostring(d) end if dscale > 0 then r = string.sub(r, 1, -dscale - 1) .. '.' .. string.sub(r, -dscale) end return r end local decode_numeric = function() return { [0] = pass; [1] = decode_numeric_bin; } end local encode_numeric = function(n) return { [0] = tostring; [1] = fail('Unsupported binary mode for numeric type'); } end local decode_date = function(n) return { [0] = pass; [1] = n == 12 and decode_int(n); } end local encode_date = function(n) return { [0] = tostring; [1] = fail('Unsupported binary mode for numeric type'); } end local function int(n) return { encode = encode_int(n); decode = decode_int(n); } end local function float(n) return { encode = encode_float(n); decode = decode_float(n); } end local function bool() return { encode = encode_bool(); decode = decode_bool(); } end local function bin() return { encode = encode_bin(); decode = decode_bin(); } end local function json() if not cjson then return end return { encode = encode_json(); decode = decode_json(); } end local function numeric() return { encode = encode_numeric(); decode = decode_numeric(); } end local function date(n) return { encode = encode_date(n); decode = decode_date(n); } end local converters = { bool = bool(); int2 = int(2); int4 = int(4); int8 = int(8); regproc = int(4); oid = int(4); tid = int(4); xid = int(4); cid = int(4); json = json(); jsonb = json(); float4 = float(4); float8 = float(8); numeric = numeric(); abstime = date(4); date = date(4); time = date(8); timestamp = date(8); timestamptz = date(8); time_stamp = date(8); -- timetz = date(12); -- interval = date(16); -- tinterval = date(12); text = bin(); bytea = bin(); char = bin(); name = bin(); xml = bin(); -- point -- lseg -- path -- box -- polygon -- line -- cidr -- abstime -- reltime -- tinterval -- unknown -- circle -- money -- macaddr -- inet -- aclitem -- bpchar -- varchar -- bit -- varbit -- refcursor -- regprocedure -- regoper -- regoperator -- regclass -- regtype -- record -- cstring -- uuid -- txid_snapshot -- pg_lsn -- tsvector -- tsquery -- gtsvector -- regconfig -- regdictionary -- int4range -- numrange -- tsrange -- tstzrange -- daterange -- int8range -- regnamespace -- regrole }; do local array_converters = {} for k, v in pairs(converters) do if not k:find('array::') then array_converters['array::' .. k] = v end end for type_name, converter in pairs(array_converters) do converters[type_name] = converter; end end local function get_decoder(typ) local tname, mode = typ[1], typ[3] local converter = converters[tname] if not converter then return end return converter.decode and converter.decode[mode] end local function get_encoder(typ) local tname, mode = typ[1], typ[3] local converter = converters[tname] if not converter then return end return converter.encode and converter.encode[mode] end return { encoder = get_encoder; decoder = get_decoder; }
Fix. UB when build type converters for arrays
Fix. UB when build type converters for arrays
Lua
mit
moteus/lua-lluv-pg
c76a9ed409a63504cf99adb4c1f8716b79f2b2e6
templates/etc/trafficserver/remap.lua
templates/etc/trafficserver/remap.lua
function do_remap() ts.client_request.set_url_host(ts.client_request.header["X-Api-Umbrella-Backend-Server-Host"]) ts.client_request.set_url_port(ts.client_request.header["X-Api-Umbrella-Backend-Server-Port"]) ts.client_request.set_url_scheme(ts.client_request.header["X-Api-Umbrella-Backend-Server-Scheme"]) local cache_key = { -- Include the HTTP method (GET, POST, etc) in the cache key. This prevents -- delayed processing when long-running GET and POSTs are running against -- the same URL: https://issues.apache.org/jira/browse/TS-3431 ts.client_request.get_method(), -- Note that by default, the cache key doesn't include the backend host -- port, so by re-setting the cache key based on the full URL here, this -- also helps ensure the backend port is included (so backends running on -- separate ports are kept separate). ts.client_request.get_url(), } ts.http.set_cache_lookup_url(table.concat(cache_key, "/")) return TS_LUA_REMAP_DID_REMAP end
function do_remap() ts.client_request.set_url_host(ts.client_request.header["X-Api-Umbrella-Backend-Server-Host"]) ts.client_request.set_url_port(ts.client_request.header["X-Api-Umbrella-Backend-Server-Port"]) ts.client_request.set_url_scheme(ts.client_request.header["X-Api-Umbrella-Backend-Server-Scheme"]) -- For cache key purposes, allow HEAD requests to re-use the cache key for -- GET requests (since HEAD queries can be answered from cached GET data). -- But since HEAD requests by themselves aren't cacheable, we don't have to -- worry about GET requests re-using the HEAD response. local method_key = ts.client_request.get_method() if method_key == "HEAD" then method_key = "GET" end local cache_key = { -- Include the HTTP method (GET, POST, etc) in the cache key. This prevents -- delayed processing when long-running GET and POSTs are running against -- the same URL: https://issues.apache.org/jira/browse/TS-3431 method_key, -- Include the Host header in the cache key, since this may differ from the -- underlying server host/IP being connected to (for virtual hosts). The -- underlying server host is included in get_url() below, but we need both -- to be part of the cache key to keep underling servers and virtual hosts -- cached separately. ts.client_request.header["Host"], -- Note that by default, the cache key doesn't include the backend server -- port, so by re-setting the cache key based on the full URL here, this -- also helps ensure the backend port is included (so backends running on -- separate ports are kept separate). ts.client_request.get_url(), } ts.http.set_cache_lookup_url(table.concat(cache_key, "/")) return TS_LUA_REMAP_DID_REMAP end
Fix cache key to account for different HTTP hosts and HEAD requests.
Fix cache key to account for different HTTP hosts and HEAD requests.
Lua
mit
NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella
99665b0ca4233f7bb97c682c75f50dbf6aec4c58
scen_edit/view/file_dialog.lua
scen_edit/view/file_dialog.lua
FileDialog = Observable:extends{} local function ExtractFileName(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(pos+1) end end function FileDialog:init(dir) self.dir = dir or nil self.confirmDialogCallback = nil --[[ self.panel = LayoutPanel:New { autosize = true, autoArrangeH = false, autoArrangeV = false, centerItems = false, iconX = 64, iconY = 64, itemMargin = {1, 1, 1, 1}, selectable = true, multiSelect = true, items = {}, }-]] local buttonPanel = MakeComponentPanel() self.fileEditBox = EditBox:New { width = "40%", x = "30%", y = 1, height = "100%", } local okButton = Button:New { height = SCEN_EDIT.model.B_HEIGHT, bottom = 5, width = "20%", x = "10", caption = "OK", } local cancelButton = Button:New { height = SCEN_EDIT.model.B_HEIGHT, bottom = 5, width = "20%", x = "22%", caption = "Cancel", } self.filePanel = FilePanel:New { x = 10, y = 10, width = "100%", height = "100%", dir = self.dir, multiselect = false, } self.filePanel.OnSelectItem = { function (obj, itemIdx, selected) if selected and itemIdx > self.filePanel._dirsNum+1 then local fullPath = tostring(obj.items[itemIdx]) local fileName = ExtractFileName(fullPath) self.fileEditBox:SetText(fileName) end end } self.window = Window:New { x = 500, y = 200, width = 600, height = 600, parent = Screen0, caption = "File dialog", children = { ScrollPanel:New { width = "100%", y = 10, bottom = 80, children = { self.filePanel, }, }, StackPanel:New { x = 1, width = "100%", height = SCEN_EDIT.model.B_HEIGHT, bottom = SCEN_EDIT.model.B_HEIGHT + 5 + 5, padding = {0, 0, 0, 0}, itemMarging = {0, 0, 0, 0}, resizeItems = false, orientation = "horizontal", children = { Label:New { width = "5%", x = 1, caption = "File name: ", }, self.fileEditBox, }, }, okButton, cancelButton, }, } okButton.OnClick = { function() self:confirmDialog() self.window:Dispose() end } cancelButton.OnClick = { function() self.window:Dispose() end } -- self:SetDir(self.dir) end function FileDialog:setConfirmDialogCallback(func) self.confirmDialogCallback = func end function FileDialog:getSelectedFilePath() local path = self.filePanel.dir .. self.fileEditBox.text return path end function FileDialog:confirmDialog() local path = self:getSelectedFilePath() if self.confirmDialogCallback then self.confirmDialogCallback(path) end end
FileDialog = Observable:extends{} local function ExtractFileName(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(pos+1) end end function FileDialog:init(dir) self.dir = dir or nil self.confirmDialogCallback = nil local buttonPanel = MakeComponentPanel() self.fileEditBox = EditBox:New { width = "40%", x = "30%", y = 1, height = "100%", } local okButton = Button:New { height = SCEN_EDIT.model.B_HEIGHT, bottom = 5, width = "20%", x = "10", caption = "OK", } local cancelButton = Button:New { height = SCEN_EDIT.model.B_HEIGHT, bottom = 5, width = "20%", x = "22%", caption = "Cancel", } self.filePanel = FilePanel:New { x = 10, y = 10, width = "100%", height = "100%", dir = self.dir, multiselect = false, } self.filePanel.OnSelectItem = { function (obj, itemIdx, selected) if selected and itemIdx > self.filePanel._dirsNum+1 then local fullPath = tostring(obj.items[itemIdx]) local fileName = ExtractFileName(fullPath) self.fileEditBox:SetText(fileName) end end } self.window = Window:New { x = 500, y = 200, width = 600, height = 600, parent = screen0, caption = "File dialog", children = { ScrollPanel:New { width = "100%", y = 10, bottom = 80, children = { self.filePanel, }, }, StackPanel:New { x = 1, width = "100%", height = SCEN_EDIT.model.B_HEIGHT, bottom = SCEN_EDIT.model.B_HEIGHT + 5 + 5, padding = {0, 0, 0, 0}, itemMarging = {0, 0, 0, 0}, resizeItems = false, orientation = "horizontal", children = { Label:New { width = "5%", x = 1, caption = "File name: ", }, self.fileEditBox, }, }, okButton, cancelButton, }, } okButton.OnClick = { function() self:confirmDialog() self.window:Dispose() end } cancelButton.OnClick = { function() self.window:Dispose() end } -- self:SetDir(self.dir) end function FileDialog:setConfirmDialogCallback(func) self.confirmDialogCallback = func end function FileDialog:getSelectedFilePath() local path = self.filePanel.dir .. self.fileEditBox.text return path end function FileDialog:confirmDialog() local path = self:getSelectedFilePath() if self.confirmDialogCallback then self.confirmDialogCallback(path) end end
fix in file_dialog
fix in file_dialog
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
5921c8e4207a9c7f8818865f2a08ba31b44a27e2
modules/client_exit/exit.lua
modules/client_exit/exit.lua
Exit = {} local exitWindow local exitButton function Exit.init() if not g_game.isOnline() then exitButton = TopMenu.addRightButton('exitButton', tr('Exit Client'), 'exit.png', Exit.tryExit) end connect(g_game, { onGameStart = Exit.hide, onGameEnd = Exit.show }) end function Exit.terminate() disconnect(g_game, { onGameStart = Exit.hide, onGameEnd = Exit.show }) if exitWindow then exitWindow:destroy() exitWindow = nil end if exitButton then exitButton:destroy() exitButton = nil end Exit = nil end function Exit.hide() if exitWindow then exitWindow:destroy() end exitButton:hide() end function Exit.show() exitButton:show() end function Exit.tryExit() if exitWindow then return true end local yesFunc = function() scheduleEvent(exit, 10) end local noFunc = function() exitWindow:destroy() exitWindow = nil end exitWindow = displayGeneralBox('Exit', tr("Do you really want to exit?"), { { text='Yes', callback=yesFunc }, { text='No', callback=noFunc }, anchor=AnchorHorizontalCenter }, yesFunc, noFunc) return true end
Exit = {} local exitWindow local exitButton function Exit.init() exitButton = TopMenu.addRightButton('exitButton', tr('Exit Client'), 'exit.png', Exit.tryExit) if g_game.isOnline() then exitButton:hide() else exitButton:show() end connect(g_game, { onGameStart = Exit.hide, onGameEnd = Exit.show }) end function Exit.terminate() disconnect(g_game, { onGameStart = Exit.hide, onGameEnd = Exit.show }) if exitWindow then exitWindow:destroy() exitWindow = nil end if exitButton then exitButton:destroy() exitButton = nil end Exit = nil end function Exit.hide() if exitWindow then exitWindow:destroy() end exitButton:hide() end function Exit.show() exitButton:show() end function Exit.tryExit() if exitWindow then return true end local yesFunc = function() scheduleEvent(exit, 10) end local noFunc = function() exitWindow:destroy() exitWindow = nil end exitWindow = displayGeneralBox('Exit', tr("Do you really want to exit?"), { { text='Yes', callback=yesFunc }, { text='No', callback=noFunc }, anchor=AnchorHorizontalCenter }, yesFunc, noFunc) return true end
Fixed Exit button not being created
Fixed Exit button not being created It will now show/hide appropriately instead of not being created and thus throwing errors.
Lua
mit
dreamsxin/otclient,Radseq/otclient,gpedro/otclient,dreamsxin/otclient,dreamsxin/otclient,Radseq/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient,gpedro/otclient,kwketh/otclient,gpedro/otclient,kwketh/otclient,Cavitt/otclient_mapgen
5a19e06f99b1dc2993275ce3d945e0b3cab5aaf2
share/lua/playlist/youtube.lua
share/lua/playlist/youtube.lua
--[[ $Id$ Copyright © 2007-2011 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) local _, _, res = string.find( url, "[&?]"..name.."=([^&]*)" ) return res end function get_arturl() -- FIXME: vlc.strings() is not a function, it should probably be -- vlc.strings.decode_uri() --if string.match( vlc.path, "iurl=" ) then -- return vlc.strings( get_url_param( vlc.path, "iurl" ) ) --end video_id = get_url_param( vlc.path, "v" ) if not video_id then return nil end return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end function get_prefres() local prefres = -1 if vlc.var and vlc.var.inherit then prefres = vlc.var.inherit(nil, "preferred-resolution") if prefres == nil then prefres = -1 end end return prefres end -- Probe function. function probe() if vlc.access ~= "http" and vlc.access ~= "https" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "/watch%?" ) -- the html page or string.match( vlc.path, "/v/" ) -- video in swf player or string.match( vlc.path, "/player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "/watch%?" ) then -- This is the HTML page's URL -- fmt is the format of the video -- (cf. http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs) fmt = get_url_param( vlc.path, "fmt" ) while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) name = vlc.strings.resolve_xml_special_chars( name ) end if string.match( line, "<meta name=\"description\"" ) then -- Don't ask me why they double encode ... _,_,description = string.find( line, "content=\"(.-)\"" ) description = vlc.strings.resolve_xml_special_chars( description ) description = vlc.strings.resolve_xml_special_chars( description ) end if string.match( line, "<meta property=\"og:image\"" ) then _,_,arturl = string.find( line, "content=\"(.-)\"" ) end if string.match( line, " rel=\"author\"" ) then _,_,artist = string.find( line, "href=\"/user/([^\"]*)\"" ) end -- JSON parameters, also formerly known as "swfConfig", -- "SWF_ARGS", "swfArgs" ... if string.match( line, "PLAYER_CONFIG" ) then if not fmt then prefres = get_prefres() if prefres >= 0 then fmt_list = string.match( line, "\"fmt_list\": \"(.-)\"" ) if fmt_list then for itag,height in string.gmatch( fmt_list, "(%d+)\\/%d+x(%d+)\\/[^,]+" ) do -- Apparently formats are listed in quality -- order, so we take the first one that works, -- or fallback to the lowest quality fmt = itag if tonumber(height) <= prefres then break end end end end end url_map = string.match( line, "\"url_encoded_fmt_stream_map\": \"(.-)\"" ) if url_map then -- FIXME: do this properly url_map = string.gsub( url_map, "\\u0026", "&" ) for url,itag in string.gmatch( url_map, "url=([^&,]+).-&itag=(%d+)" ) do -- Apparently formats are listed in quality order, -- so we can afford to simply take the first one if not fmt or tonumber( itag ) == tonumber( fmt ) then url = vlc.strings.decode_uri( url ) path = url break end end end -- There is also another version of the parameters, encoded -- differently, as an HTML attribute of an <object> or <embed> -- tag; but we don't need it now end end if not path then vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" ) return { } end if not arturl then arturl = get_arturl() end return { { path = path; name = name; description = description; artist = artist; arturl = arturl } } else -- This is the flash player's URL video_id = get_url_param( vlc.path, "video_id" ) if not video_id then _,_,video_id = string.find( vlc.path, "/v/([^?]*)" ) end if not video_id then vlc.msg.err( "Couldn't extract youtube video URL" ) return { } end fmt = get_url_param( vlc.path, "fmt" ) if fmt then format = "&fmt=" .. fmt else format = "" end return { { path = "http://www.youtube.com/watch?v="..video_id..format } } end end
--[[ $Id$ Copyright © 2007-2011 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) local _, _, res = string.find( url, "[&?]"..name.."=([^&]*)" ) return res end function get_arturl() local iurl = get_url_param( vlc.path, "iurl" ) if iurl then return iurl end local video_id = get_url_param( vlc.path, "v" ) if not video_id then return nil end return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end function get_prefres() local prefres = -1 if vlc.var and vlc.var.inherit then prefres = vlc.var.inherit(nil, "preferred-resolution") if prefres == nil then prefres = -1 end end return prefres end -- Probe function. function probe() if vlc.access ~= "http" and vlc.access ~= "https" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "/watch%?" ) -- the html page or string.match( vlc.path, "/v/" ) -- video in swf player or string.match( vlc.path, "/player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "/watch%?" ) then -- This is the HTML page's URL -- fmt is the format of the video -- (cf. http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs) fmt = get_url_param( vlc.path, "fmt" ) while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) name = vlc.strings.resolve_xml_special_chars( name ) end if string.match( line, "<meta name=\"description\"" ) then -- Don't ask me why they double encode ... _,_,description = string.find( line, "content=\"(.-)\"" ) description = vlc.strings.resolve_xml_special_chars( description ) description = vlc.strings.resolve_xml_special_chars( description ) end if string.match( line, "<meta property=\"og:image\"" ) then _,_,arturl = string.find( line, "content=\"(.-)\"" ) end if string.match( line, " rel=\"author\"" ) then _,_,artist = string.find( line, "href=\"/user/([^\"]*)\"" ) end -- JSON parameters, also formerly known as "swfConfig", -- "SWF_ARGS", "swfArgs" ... if string.match( line, "PLAYER_CONFIG" ) then if not fmt then prefres = get_prefres() if prefres >= 0 then fmt_list = string.match( line, "\"fmt_list\": \"(.-)\"" ) if fmt_list then for itag,height in string.gmatch( fmt_list, "(%d+)\\/%d+x(%d+)\\/[^,]+" ) do -- Apparently formats are listed in quality -- order, so we take the first one that works, -- or fallback to the lowest quality fmt = itag if tonumber(height) <= prefres then break end end end end end url_map = string.match( line, "\"url_encoded_fmt_stream_map\": \"(.-)\"" ) if url_map then -- FIXME: do this properly url_map = string.gsub( url_map, "\\u0026", "&" ) for url,itag in string.gmatch( url_map, "url=([^&,]+).-&itag=(%d+)" ) do -- Apparently formats are listed in quality order, -- so we can afford to simply take the first one if not fmt or tonumber( itag ) == tonumber( fmt ) then url = vlc.strings.decode_uri( url ) path = url break end end end -- There is also another version of the parameters, encoded -- differently, as an HTML attribute of an <object> or <embed> -- tag; but we don't need it now end end if not path then vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" ) return { } end if not arturl then arturl = get_arturl() end return { { path = path; name = name; description = description; artist = artist; arturl = arturl } } else -- This is the flash player's URL video_id = get_url_param( vlc.path, "video_id" ) if not video_id then _,_,video_id = string.find( vlc.path, "/v/([^?]*)" ) end if not video_id then vlc.msg.err( "Couldn't extract youtube video URL" ) return { } end fmt = get_url_param( vlc.path, "fmt" ) if fmt then format = "&fmt=" .. fmt else format = "" end return { { path = "http://www.youtube.com/watch?v="..video_id..format } } end end
youtube.lua: fix commit 9a746cfa3078c53eed57d2102002b39c283c6ab4
youtube.lua: fix commit 9a746cfa3078c53eed57d2102002b39c283c6ab4
Lua
lgpl-2.1
vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc
31c43d91270079e5beb2f0580ee8fd0e6745b4bc
MMOCoreORB/bin/scripts/screenplays/quest_tasks/patrol.lua
MMOCoreORB/bin/scripts/screenplays/quest_tasks/patrol.lua
local ObjectManager = require("managers.object.object_manager") local QuestManager = require("managers.quest.quest_manager") local Logger = require("utils.logger") Patrol = Task:new { -- Task properties taskName = "", -- Patrol properties waypointName = "", numPoints = 0, areaSize = 0, originX = 0, originY = 0, forceSpawn = false, onPlayerKilled = nil, onEnteredActiveArea = nil } function Patrol:setupPatrolPoints(pCreature) local playerID = SceneObject(pCreature):getObjectID() local radius = 1024 -- Default radius local curQuest = QuestManager.getCurrentQuestID(pCreature) local pQuest = getQuestInfo(curQuest) if (pQuest ~= nil) then local questRadius = LuaQuestInfo(pQuest):getQuestParameter() if (questRadius ~= "" and questRadius ~= nil) then radius = tonumber(questRadius) end end for i = 1, self.numPoints, 1 do local offsetX = getRandomNumber(-75, 75) local offsetY = getRandomNumber(-75, 75) local offsetTheta = getRandomNumber(-2, 2) local theta = (i * 45 + offsetTheta) * 0.0175; local x = (self.originX + offsetX) + (radius * math.cos(theta)) local y = (self.originY + offsetY) + (radius * math.sin(theta)) local planetName = SceneObject(pCreature):getZoneName() local spawnPoint = getSpawnPoint(planetName, x, y, 0, 200, self.forceSpawn) local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", spawnPoint[1], spawnPoint[2], spawnPoint[3], self.areaSize, 0) if (pActiveArea == nil) then return nil end local areaID = SceneObject(pActiveArea):getObjectID() writeData(areaID .. self.taskName .. "ownerID", playerID) writeData(areaID .. self.taskName .. "waypointNum", i) writeData(playerID .. self.taskName .. "waypointNum" .. i, areaID) createObserver(ENTEREDAREA, self.taskName, "handleEnteredAreaEvent", pActiveArea) ObjectManager.withCreaturePlayerObject(pCreature, function(ghost) local waypointID = ghost:addWaypoint(planetName, self.waypointName, "", spawnPoint[1], spawnPoint[3], WAYPOINTYELLOW, true, true, 0, 0) writeData(areaID .. self.taskName .. "waypointID", waypointID) end) end end function Patrol:handleEnteredAreaEvent(pActiveArea, pCreature) if pActiveArea == nil or not SceneObject(pCreature):isPlayerCreature() then return 0 end local areaID = SceneObject(pActiveArea):getObjectID() local ownerID = readData(areaID .. self.taskName .. "ownerID") if ownerID == SceneObject(pCreature):getObjectID() then local wpNum = readData(areaID .. self.taskName .. "waypointNum") self:destroyWaypoint(pCreature, wpNum) local wpDone = readData(ownerID .. ":patrolWaypointsReached") + 1 writeData(ownerID .. ":patrolWaypointsReached", wpDone) self:onEnteredActiveArea(pCreature, pActiveArea) SceneObject(pActiveArea):destroyObjectFromWorld() return 1 end return 0 end function Patrol:destroyWaypoint(pCreature, num) local playerID = SceneObject(pCreature):getObjectID() local areaID = readData(playerID .. self.taskName .. "waypointNum" .. num) local waypointNum = readData(areaID .. self.taskName .. "waypointNum") local waypointID = readData(areaID .. self.taskName .. "waypointID") ObjectManager.withCreaturePlayerObject(pCreature, function(ghost) ghost:removeWaypoint(waypointID, true) end) local pActiveArea = getSceneObject(areaID) if (pActiveArea ~= nil) then SceneObject(pActiveArea):destroyObjectFromWorld() end deleteData(playerID .. self.taskName .. "waypointNum" .. waypointNum) deleteData(areaID .. self.taskName .. "waypointID") deleteData(areaID .. self.taskName .. "waypointNum") deleteData(areaID .. self.taskName .. "ownerID") end function Patrol:waypointCleanup(pCreature) for i = 1, self.numPoints, 1 do self:destroyWaypoint(pCreature, i) end end function Patrol:failPatrol(pCreature) self:waypointCleanup(pCreature) local playerID = SceneObject(pCreature):getObjectID() deleteData(playerID .. ":patrolWaypointsReached") writeData(playerID .. ":failedPatrol", 1) return true end function Patrol:taskStart(pCreature) self:setupPatrolPoints(pCreature) createObserver(OBJECTDESTRUCTION, self.taskName, "playerKilled", pCreature) end function Patrol:playerKilled(pCreature, pKiller, nothing) if (pCreature == nil) then return 0 end self:callFunctionIfNotNil(self.onPlayerKilled, false, pCreature) return 0 end function Patrol:taskFinish(pCreature) local playerID = SceneObject(pCreature):getObjectID() deleteData(playerID .. ":patrolWaypointsReached") deleteData(playerID .. ":failedPatrol") self:waypointCleanup(pCreature) return true end return Patrol
local ObjectManager = require("managers.object.object_manager") local QuestManager = require("managers.quest.quest_manager") local Logger = require("utils.logger") Patrol = Task:new { -- Task properties taskName = "", -- Patrol properties waypointName = "", numPoints = 0, areaSize = 0, originX = 0, originY = 0, forceSpawn = false, onPlayerKilled = nil, onEnteredActiveArea = nil } function Patrol:setupPatrolPoints(pCreature) local playerID = SceneObject(pCreature):getObjectID() local radius = 1024 -- Default radius local curQuest = QuestManager.getCurrentQuestID(pCreature) local pQuest = getQuestInfo(curQuest) if (pQuest ~= nil) then local questRadius = LuaQuestInfo(pQuest):getQuestParameter() if (questRadius ~= "" and questRadius ~= nil) then radius = tonumber(questRadius) end end for i = 1, self.numPoints, 1 do local offsetX = getRandomNumber(-75, 75) local offsetY = getRandomNumber(-75, 75) local offsetTheta = getRandomNumber(-2, 2) local theta = (i * 45 + offsetTheta) * 0.0175; local x = (self.originX + offsetX) + (radius * math.cos(theta)) local y = (self.originY + offsetY) + (radius * math.sin(theta)) local planetName = SceneObject(pCreature):getZoneName() local spawnPoint = getSpawnPoint(planetName, x, y, 0, 200, self.forceSpawn) local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", spawnPoint[1], spawnPoint[2], spawnPoint[3], self.areaSize, 0) if (pActiveArea == nil) then return nil end local areaID = SceneObject(pActiveArea):getObjectID() writeData(areaID .. self.taskName .. "ownerID", playerID) writeData(areaID .. self.taskName .. "waypointNum", i) writeData(playerID .. self.taskName .. "waypointNum" .. i, areaID) createObserver(ENTEREDAREA, self.taskName, "handleEnteredAreaEvent", pActiveArea) ObjectManager.withCreaturePlayerObject(pCreature, function(ghost) local waypointID = ghost:addWaypoint(planetName, self.waypointName, "", spawnPoint[1], spawnPoint[3], WAYPOINTYELLOW, true, true, 0, 0) writeData(areaID .. self.taskName .. "waypointID", waypointID) end) end end function Patrol:handleEnteredAreaEvent(pActiveArea, pCreature) if pActiveArea == nil or not SceneObject(pCreature):isPlayerCreature() then return 0 end local areaID = SceneObject(pActiveArea):getObjectID() local ownerID = readData(areaID .. self.taskName .. "ownerID") if ownerID == SceneObject(pCreature):getObjectID() then local wpNum = readData(areaID .. self.taskName .. "waypointNum") self:destroyWaypoint(pCreature, wpNum) local wpDone = readData(ownerID .. ":patrolWaypointsReached") + 1 writeData(ownerID .. ":patrolWaypointsReached", wpDone) self:onEnteredActiveArea(pCreature, pActiveArea) SceneObject(pActiveArea):destroyObjectFromWorld() return 1 end return 0 end function Patrol:destroyWaypoint(pCreature, num) local playerID = SceneObject(pCreature):getObjectID() local areaID = readData(playerID .. self.taskName .. "waypointNum" .. num) local waypointNum = readData(areaID .. self.taskName .. "waypointNum") local waypointID = readData(areaID .. self.taskName .. "waypointID") ObjectManager.withCreaturePlayerObject(pCreature, function(ghost) ghost:removeWaypoint(waypointID, true) end) local pActiveArea = getSceneObject(areaID) if (pActiveArea ~= nil) then SceneObject(pActiveArea):destroyObjectFromWorld() end deleteData(playerID .. self.taskName .. "waypointNum" .. waypointNum) deleteData(areaID .. self.taskName .. "waypointID") deleteData(areaID .. self.taskName .. "waypointNum") deleteData(areaID .. self.taskName .. "ownerID") end function Patrol:waypointCleanup(pCreature) for i = 1, self.numPoints, 1 do self:destroyWaypoint(pCreature, i) end end function Patrol:failPatrol(pCreature) self:waypointCleanup(pCreature) local playerID = SceneObject(pCreature):getObjectID() deleteData(playerID .. ":patrolWaypointsReached") writeData(playerID .. ":failedPatrol", 1) return true end function Patrol:taskStart(pCreature) self:setupPatrolPoints(pCreature) createObserver(OBJECTDESTRUCTION, self.taskName, "playerKilled", pCreature) end function Patrol:playerKilled(pCreature, pKiller, nothing) if (pCreature == nil) then return 0 end self:callFunctionIfNotNil(self.onPlayerKilled, false, pCreature) return 0 end function Patrol:taskFinish(pCreature) local playerID = SceneObject(pCreature):getObjectID() deleteData(playerID .. ":patrolWaypointsReached") deleteData(playerID .. ":failedPatrol") dropObserver(OBJECTDESTRUCTION, self.taskName, "playerKilled", pCreature) self:waypointCleanup(pCreature) return true end return Patrol
[fixed] Whip patrol quests failing on player death after player had already completed patrol
[fixed] Whip patrol quests failing on player death after player had already completed patrol Change-Id: I410b21568968381c09b6bbc04e57465a50fa04bc
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
13743ba84ba51e237f70ca633f0a6bb9b6615736
main.lua
main.lua
local paths = require 'paths' local optim = require 'optim' local Executer = require 'utils.executer' local RnnCore = require 'models.rnnCore' local Stack = require 'utils.stack' local StoragePolicy = require 'utils.storagePolicy' local cmd = torch.CmdLine() cmd:option('-memoryAllocation', 100, 'memory allocation') cmd:option('-truncation', 50, 'truncation') cmd:option('-epochs', 20, 'number of epochs') cmd:option('-cuda', false, 'gpu') local opt = cmd:parse(arg) torch.manualSeed(1) local dataset_directory = 'dataset' local train_file = paths.concat(dataset_directory, 'train.t7') local valid_file = paths.concat(dataset_directory, 'valid.t7') local test_file = paths.concat(dataset_directory, 'test.t7') local vocab_file = paths.concat(dataset_directory, 'vocab_text8.t7') local train_data = torch.load(train_file) local valid_data = torch.load(valid_file) local vocab = torch.load(vocab_file) local vocab_size = 0 for k,v in pairs(vocab) do vocab_size = vocab_size + 1 end local train_size = 10000 -- train_data:size(1) local valid_size = 10000 -- valid_data:size(1) local hiddenSize = 32 local batchSize = train_data:size(2) local initState = torch.Tensor(batchSize, hiddenSize):zero() local hiddenGradient = torch.Tensor(batchSize, hiddenSize):zero() local nb_sequences = math.floor(train_size / opt.truncation) local rnnBuilder = RnnCore{vocabSize=vocab_size, hiddenSize=hiddenSize} local rnn = rnnBuilder:buildCore() local params, gradParams = rnn:getParameters() local stack = Stack{memoryAllocation=opt.memoryAllocation, cellSize=torch.Tensor{batchSize, hiddenSize}} stack:push(initState) local policy = StoragePolicy{memoryAllocation=opt.memoryAllocation} policy:addTimesteps(opt.truncation) local exec = Executer{D=policy.D,stack=stack,rnnCore=rnn} local criterion = nn.ClassNLLCriterion() local loss = 0 local optimState = { learningRate=1e-3 } if opt.cuda then require 'cunn' require 'cudnn' initState = initState:cuda() hiddenGradient = hiddenGradient:cuda() train_data = train_data:cuda() valid_data = valid_data:cuda() stack = stack:cuda() rnn = rnn:cuda() criterion = criterion:cuda() end function exec:getInput(t) return train_data[(t-1)%train_size + 1] end function exec:setOutputAndGetGradOutput(t, output) loss = loss + criterion:forward(output, train_data[t%train_size + 1]) return criterion:backward(output, train_data[t%train_size + 1]) end local function train() local t=1 local cumLoss = 0 local function feval(params_) if params_ ~= params then params:copy(params_) end loss = 0 gradParams:zero() exec:executeStrategy(hiddenGradient, opt.memoryAllocation-1, opt.truncation, t) return loss, gradParams end for i=1, nb_sequences do xlua.progress(i, nb_sequences) local _, batch_loss = optim.rmsprop(feval, params, optimState) cumLoss = cumLoss + batch_loss[1] t = t + opt.truncation end return cumLoss / nb_sequences / opt.truncation end local function evaluate() local t=1 local cumLoss = 0 local state = torch.Tensor(batchSize, hiddenSize):zero() if opt.cuda then state = state:cuda() end for t=1, valid_size do xlua.progress(t, valid_size) local output, next_state = unpack(rnn:forward{valid_data[t], state}) state:copy(next_state) cumLoss = cumLoss + criterion:forward(output, valid_data[t%valid_size+1]) end return cumLoss / valid_size end for e=1, opt.epochs do print("On epoch " .. e .. ":") print("Train:") print(train()) print("Validation:") print(evaluate()) end
local paths = require 'paths' local optim = require 'optim' local Executer = require 'utils.executer' local RnnCore = require 'models.rnnCore' local Stack = require 'utils.stack' local StoragePolicy = require 'utils.storagePolicy' local cmd = torch.CmdLine() cmd:option('-memoryAllocation', 100, 'memory allocation') cmd:option('-truncation', 50, 'truncation') cmd:option('-epochs', 20, 'number of epochs') cmd:option('-cuda', false, 'gpu') local opt = cmd:parse(arg) torch.manualSeed(1) local dataset_directory = 'dataset' local train_file = paths.concat(dataset_directory, 'train.t7') local valid_file = paths.concat(dataset_directory, 'valid.t7') local test_file = paths.concat(dataset_directory, 'test.t7') local vocab_file = paths.concat(dataset_directory, 'vocab_text8.t7') local train_data = torch.load(train_file) local valid_data = torch.load(valid_file) local vocab = torch.load(vocab_file) local vocab_size = 0 for k,v in pairs(vocab) do vocab_size = vocab_size + 1 end local train_size = 10000 -- train_data:size(1) local valid_size = 10000 -- valid_data:size(1) local hiddenSize = 32 local batchSize = train_data:size(2) local initState = torch.Tensor(batchSize, hiddenSize):zero() local hiddenGradient = torch.Tensor(batchSize, hiddenSize):zero() local nb_sequences = math.floor(train_size / opt.truncation) local rnnBuilder = RnnCore{vocabSize=vocab_size, hiddenSize=hiddenSize} local rnn = rnnBuilder:buildCore() local stack = Stack{memoryAllocation=opt.memoryAllocation, cellSize=torch.Tensor{batchSize, hiddenSize}} stack:push(initState) local policy = StoragePolicy{memoryAllocation=opt.memoryAllocation} policy:addTimesteps(opt.truncation) local exec = Executer{D=policy.D,stack=stack,rnnCore=rnn} local criterion = nn.ClassNLLCriterion() local loss = 0 local optimState = { learningRate=1e-3 } if opt.cuda then require 'cunn' require 'cudnn' initState = initState:cuda() hiddenGradient = hiddenGradient:cuda() train_data = train_data:cuda() valid_data = valid_data:cuda() stack = stack:cuda() rnn = rnn:cuda() criterion = criterion:cuda() end local params, gradParams = rnn:getParameters() function exec:getInput(t) return train_data[(t-1)%train_size + 1] end function exec:setOutputAndGetGradOutput(t, output) loss = loss + criterion:forward(output, train_data[t%train_size + 1]) return criterion:backward(output, train_data[t%train_size + 1]) end local function train() local t=1 local cumLoss = 0 local function feval(params_) if params_ ~= params then params:copy(params_) end loss = 0 gradParams:zero() exec:executeStrategy(hiddenGradient, opt.memoryAllocation-1, opt.truncation, t) return loss, gradParams end for i=1, nb_sequences do xlua.progress(i, nb_sequences) local _, batch_loss = optim.rmsprop(feval, params, optimState) cumLoss = cumLoss + batch_loss[1] t = t + opt.truncation end return cumLoss / nb_sequences / opt.truncation end local function evaluate() local t=1 local cumLoss = 0 local state = torch.Tensor(batchSize, hiddenSize):zero() if opt.cuda then state = state:cuda() end for t=1, valid_size do xlua.progress(t, valid_size) local output, next_state = unpack(rnn:forward{valid_data[t], state}) state:copy(next_state) cumLoss = cumLoss + criterion:forward(output, valid_data[t%valid_size+1]) end return cumLoss / valid_size end for e=1, opt.epochs do print("On epoch " .. e .. ":") print("Train:") print(train()) print("Validation:") print(evaluate()) end
Bugfix: params and gradParams after cuda
Bugfix: params and gradParams after cuda
Lua
mit
ctallec/bigart
9a11b9de79c8ff028c157021236bfd8d792ac087
framework.lua
framework.lua
-- Layer to create quests and act as middle-man between Evennia and Agent require 'utils' local underscore = require 'underscore' local DEBUG = false local DEFAULT_REWARD = -0.1 local STEP_COUNT = 0 -- count the number of steps in current episode local MAX_STEPS = 500 quests = {'You are hungry.','You are sleepy.', 'You are bored.', 'You are getting fat.'} quest_actions = {'eat', 'sleep', 'watch' ,'exercise'} -- aligned to quests above quest_checklist = {} quest_levels = 1 --number of levels in any given quest rooms = {'Living', 'Garden', 'Kitchen','Bedroom'} actions = {"eat", "sleep", "watch", "exercise", "go"} -- hard code in objects = {'north','south','east','west'} -- read rest from build file symbols = {} symbol_mapping = {} NUM_ROOMS = 4 local current_room_description = "" function random_teleport() local room_index = torch.random(1, NUM_ROOMS) data_out('@tel tut#0'..room_index) sleep(0.1) data_in() data_out('l') if DEBUG then print('Start Room : ' .. room_index ..' ' .. rooms[room_index]) end end function random_quest() -- indxs = torch.randperm(#quests) for i=1,quest_levels do -- local quest_index = indxs[i] local quest_index = torch.random(1, #quests) quest_checklist[#quest_checklist+1] = quest_index end if DEBUG then print("Start quest", quests[quest_checklist[1]], quest_actions[quest_checklist[1]]) end end function login(user, password) local num_rooms = 4 local pre_login_text = data_in() print(pre_login_text) sleep(1) data_out('connect ' .. user .. ' ' .. password) end --Function to parse the output of the game (to extract rewards, etc. ) function parse_game_output(text) -- extract REWARD if it exists -- text is a list of sentences local reward = nil local text_to_agent = {current_room_description, quests[quest_checklist[1]]} for i=1, #text do if i < #text and string.match(text[i], '<EOM>') then text_to_agent = {current_room_description, quests[quest_checklist[1]]} elseif string.match(text[i], "REWARD") then if string.match(text[i], quest_actions[quest_checklist[1]]) then reward = tonumber(string.match(text[i], "%d+")) end else --IMP: only description and quest are necessary (for now) --table.insert(text_to_agent, text[i]) end end if not reward then reward = DEFAULT_REWARD end return text_to_agent, reward end --take a step in the game function step_game(action_index, object_index, gameLogger) local command = build_command(actions[action_index], objects[object_index], gameLogger) data_out(command) if DEBUG then print(actions[action_index] .. ' ' .. objects[object_index]) end STEP_COUNT = STEP_COUNT + 1 return getState(gameLogger) end -- TODO function nextRandomGame() end -- TODO function newGame(gameLogger) quest_checklist = {} STEP_COUNT = 0 random_teleport() random_quest() if gameLogger then end return getState(gameLogger) end -- build game command to send to the game function build_command(action, object, logger) if logger then logger:write(">>" .. action .. ' '.. object..'\n') end return action .. ' ' ..object end function parseLine( list_words, start_index) -- parse line to update symbols and symbol_mapping -- IMP: make sure we're using simple english - ignores punctuation, etc. local sindx start_index = start_index or 1 for i=start_index,#list_words do word = split(list_words[i], "%a+")[1] word = word:lower() if symbol_mapping[word] == nil then sindx = #symbols + 1 symbols[sindx] = word symbol_mapping[word] = sindx end end end function addQuestWordsToVocab() for i, quest in pairs(quests) do parseLine(split(quest, "%a+"), 1) end end -- read in text data from file with sentences (one sentence per line) - nicely tokenized function makeSymbolMapping(filename) local file = io.open(filename, "r"); local data = {} local parts for line in file:lines() do list_words = split(line, "%S+") if list_words[1] == '@detail' or list_words[1] == '@desc' then parseLine(list_words, 4) elseif list_words[1] == '@create/drop' then -- add to actionable objects table.insert(objects, split(list_words[2], "%a+")[1]) end end addQuestWordsToVocab() end -- Args: { -- 1: desc of room -- 2: quest desc -- } function convert_text_to_bow(input_text) local vector = torch.zeros(#symbols) for j, line in pairs(input_text) do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[symbol_mapping[word]] = vector[symbol_mapping[word]] + 1 else print(word .. ' not in vocab') end end end return vector end -- Args: { -- 1: desc of room -- 2: quest desc -- } -- Create separate bow vectors for the two sentences function convert_text_to_bow2(input_text) local vector = torch.zeros(2 * #symbols) for j=1, 2 do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[(j-1)*(#symbols) + symbol_mapping[word]] = vector[(j-1)*(#symbols) + symbol_mapping[word]] + 1 else print(word .. ' not in vocab') end end end return vector end -------------------------VECTOR function ------------------------- vector_function = convert_text_to_bow2 ------------------------------------------------------------------- function getState(logger, print_on) local terminal = (STEP_COUNT >= MAX_STEPS) local inData = data_in() while #inData == 0 or not string.match(inData[#inData],'<EOM>') do TableConcat(inData, data_in()) end data_out('look') local inData2 = data_in() while #inData2 == 0 or not string.match(inData2[#inData2],'<EOM>') do TableConcat(inData2, data_in()) end current_room_description = inData2[1] local text, reward = parse_game_output(inData) if DEBUG or print_on then print(text, reward) sleep(0.1) if reward > 0 then print(text, reward) sleep(2) end end if reward >= 1 then quest_checklist = underscore.rest(quest_checklist) --remove first element in table if #quest_checklist == 0 then --quest has been succesfully finished terminal = true end end local vector = vector_function(text) if logger then logger:write(table.concat(text, ' '), '\n') logger:write('Reward: '..reward, '\n') if terminal then logger:write('****************************\n\n') end end return vector, reward, terminal end function getActions() return actions end function getObjects() return objects end return { makeSymbolMapping = makeSymbolMapping, getActions = getActions, getObjects = getObjects, getState = getState, step = step_game, newGame = newGame, nextRandomGame = nextRandomGame, }
-- Layer to create quests and act as middle-man between Evennia and Agent require 'utils' local underscore = require 'underscore' local DEBUG = false local DEFAULT_REWARD = -0.05 local STEP_COUNT = 0 -- count the number of steps in current episode local MAX_STEPS = 500 quests = {'You are hungry.','You are sleepy.', 'You are bored.', 'You are getting fat.'} quest_actions = {'eat', 'sleep', 'watch' ,'exercise'} -- aligned to quests above quest_checklist = {} quest_levels = 2 --number of levels in any given quest rooms = {'Living', 'Garden', 'Kitchen','Bedroom'} actions = {"eat", "sleep", "watch", "exercise", "go"} -- hard code in objects = {'north','south','east','west'} -- read rest from build file symbols = {} symbol_mapping = {} NUM_ROOMS = 4 local current_room_description = "" function random_teleport() local room_index = torch.random(1, NUM_ROOMS) data_out('@tel tut#0'..room_index) sleep(0.1) data_in() data_out('l') if DEBUG then print('Start Room : ' .. room_index ..' ' .. rooms[room_index]) end end function random_quest() indxs = torch.randperm(#quests) for i=1,quest_levels do local quest_index = indxs[i] -- local quest_index = torch.random(1, #quests) quest_checklist[#quest_checklist+1] = quest_index end if DEBUG then print("Start quest", quests[quest_checklist[1]], quest_actions[quest_checklist[1]]) end end function login(user, password) local num_rooms = 4 local pre_login_text = data_in() print(pre_login_text) sleep(1) data_out('connect ' .. user .. ' ' .. password) end --Function to parse the output of the game (to extract rewards, etc. ) function parse_game_output(text) -- extract REWARD if it exists -- text is a list of sentences local reward = nil local text_to_agent = {current_room_description, quests[quest_checklist[1]]} for i=1, #text do if i < #text and string.match(text[i], '<EOM>') then text_to_agent = {current_room_description, quests[quest_checklist[1]]} elseif string.match(text[i], "REWARD") then if string.match(text[i], quest_actions[quest_checklist[1]]) then reward = tonumber(string.match(text[i], "%d+")) end else --IMP: only description and quest are necessary (for now) --table.insert(text_to_agent, text[i]) end end if not reward then reward = DEFAULT_REWARD end return text_to_agent, reward end --take a step in the game function step_game(action_index, object_index, gameLogger) local command = build_command(actions[action_index], objects[object_index], gameLogger) data_out(command) if DEBUG then print(actions[action_index] .. ' ' .. objects[object_index]) end STEP_COUNT = STEP_COUNT + 1 return getState(gameLogger) end -- TODO function nextRandomGame() end -- TODO function newGame(gameLogger) quest_checklist = {} STEP_COUNT = 0 random_teleport() random_quest() if gameLogger then end return getState(gameLogger) end -- build game command to send to the game function build_command(action, object, logger) if logger then logger:write(">>" .. action .. ' '.. object..'\n') end return action .. ' ' ..object end function parseLine( list_words, start_index) -- parse line to update symbols and symbol_mapping -- IMP: make sure we're using simple english - ignores punctuation, etc. local sindx start_index = start_index or 1 for i=start_index,#list_words do word = split(list_words[i], "%a+")[1] word = word:lower() if symbol_mapping[word] == nil then sindx = #symbols + 1 symbols[sindx] = word symbol_mapping[word] = sindx end end end function addQuestWordsToVocab() for i, quest in pairs(quests) do parseLine(split(quest, "%a+"), 1) end end -- read in text data from file with sentences (one sentence per line) - nicely tokenized function makeSymbolMapping(filename) local file = io.open(filename, "r"); local data = {} local parts for line in file:lines() do list_words = split(line, "%S+") if list_words[1] == '@detail' or list_words[1] == '@desc' then parseLine(list_words, 4) elseif list_words[1] == '@create/drop' then -- add to actionable objects table.insert(objects, split(list_words[2], "%a+")[1]) end end addQuestWordsToVocab() end -- Args: { -- 1: desc of room -- 2: quest desc -- } function convert_text_to_bow(input_text) local vector = torch.zeros(#symbols) for j, line in pairs(input_text) do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[symbol_mapping[word]] = vector[symbol_mapping[word]] + 1 else print(word .. ' not in vocab') end end end return vector end -- Args: { -- 1: desc of room -- 2: quest desc -- } -- Create separate bow vectors for the two sentences function convert_text_to_bow2(input_text) local vector = torch.zeros(2 * #symbols) for j=1, 2 do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[(j-1)*(#symbols) + symbol_mapping[word]] = vector[(j-1)*(#symbols) + symbol_mapping[word]] + 1 else print(word .. ' not in vocab') end end end return vector end -------------------------VECTOR function ------------------------- vector_function = convert_text_to_bow2 ------------------------------------------------------------------- function getState(logger, print_on) local terminal = (STEP_COUNT >= MAX_STEPS) local inData = data_in() while #inData == 0 or not string.match(inData[#inData],'<EOM>') do TableConcat(inData, data_in()) end data_out('look') local inData2 = data_in() while #inData2 == 0 or not string.match(inData2[#inData2],'<EOM>') do TableConcat(inData2, data_in()) end current_room_description = inData2[1] local text, reward = parse_game_output(inData) if DEBUG or print_on then print(text, reward) sleep(0.1) if reward > 0 then print(text, reward) sleep(2) end end if reward >= 1 then quest_checklist = underscore.rest(quest_checklist) --remove first element in table if #quest_checklist == 0 then --quest has been succesfully finished terminal = true else text[2] = quests[quest_checklist[1]] end end local vector = vector_function(text) if logger then logger:write(table.concat(text, ' '), '\n') logger:write('Reward: '..reward, '\n') if terminal then logger:write('****************************\n\n') end end return vector, reward, terminal end function getActions() return actions end function getObjects() return objects end return { makeSymbolMapping = makeSymbolMapping, getActions = getActions, getObjects = getObjects, getState = getState, step = step_game, newGame = newGame, nextRandomGame = nextRandomGame, }
fixed bug for multi-level quests
fixed bug for multi-level quests
Lua
mit
karthikncode/text-world-player,ljm342/text-world-player,karthikncode/text-world-player,ljm342/text-world-player
da9ff1be6fbcda1d67fd8cab18c9cc21bfe28726
fontchooser.lua
fontchooser.lua
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 32), tfhash = "hbo32", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 2, oldcurrent = 1, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) -- draw menu title renderUtf8Text(fb.bb, 30, ypos + self.title_H, self.tface, self.tfhash, "[ Fonts Menu ]", true) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 30), tfhash = "hbo30", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 1, oldcurrent = 0, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then -- draw menu title fb.bb:paintRect(30, ypos + 10, fb.bb:getWidth() - 60, self.title_H, 5) x = fb.bb:getWidth() - 220 -- move text to the right y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, self.tface, self.tfhash, "Fonts Menu", true) 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, 50, y, self.face, self.fhash, self.fonts[i], 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 if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
mod: two fix
mod: two fix * add background to the font menu title * set default current item to 1
Lua
agpl-3.0
mihailim/koreader,Hzj-jie/koreader,apletnev/koreader,frankyifei/koreader-base,lgeek/koreader,koreader/koreader-base,chihyang/koreader,NickSavage/koreader,apletnev/koreader-base,Frenzie/koreader-base,chrox/koreader,Frenzie/koreader-base,Frenzie/koreader,ashang/koreader,koreader/koreader-base,ashhher3/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,robert00s/koreader,Hzj-jie/koreader-base,poire-z/koreader,koreader/koreader-base,NiLuJe/koreader,mwoz123/koreader,Frenzie/koreader,Frenzie/koreader-base,houqp/koreader,pazos/koreader,frankyifei/koreader-base,frankyifei/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,Frenzie/koreader-base,Markismus/koreader,koreader/koreader,Hzj-jie/koreader-base,koreader/koreader,apletnev/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,frankyifei/koreader,poire-z/koreader,NiLuJe/koreader-base,noname007/koreader,houqp/koreader-base,apletnev/koreader-base,NiLuJe/koreader,Hzj-jie/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base
a9e5469bcd85e0627576e56ff07aa17203954c31
spec/purge_spec.lua
spec/purge_spec.lua
local test_env = require("test/test_environment") local run = test_env.run local testing_paths = test_env.testing_paths test_env.unload_luarocks() describe("LuaRocks purge tests #blackbox #b_purge", function() before_each(function() test_env.setup_specs() end) describe("LuaRocks purge basic tests", function() it("LuaRocks purge missing tree", function() assert.is_false(run.luarocks_bool("purge --tree=" .. testing_paths.testing_tree)) end) it("LuaRocks purge tree with no string", function() assert.is_false(run.luarocks_bool("purge --tree=1")) end) it("LuaRocks purge tree with no string", function() assert.is_true(run.luarocks_bool("purge --tree=" .. testing_paths.testing_sys_tree)) end) it("LuaRocks purge old versions tree", function() assert.is_true(run.luarocks_bool("purge --old-versions --tree=" .. testing_paths.testing_sys_tree)) end) end) end)
local test_env = require("test/test_environment") local run = test_env.run local testing_paths = test_env.testing_paths test_env.unload_luarocks() local extra_rocks = { "/say-1.0-1.src.rock", } describe("LuaRocks purge tests #blackbox #b_purge", function() before_each(function() test_env.setup_specs(extra_rocks) end) describe("LuaRocks purge basic tests", function() it("LuaRocks purge missing tree", function() assert.is_false(run.luarocks_bool("purge --tree=" .. testing_paths.testing_tree)) end) it("LuaRocks purge tree with no string", function() assert.is_false(run.luarocks_bool("purge --tree=")) end) it("LuaRocks purge tree with no string", function() assert.is_true(run.luarocks_bool("purge --tree=" .. testing_paths.testing_sys_tree)) end) it("LuaRocks purge tree missing files", function() assert.is_true(run.luarocks_bool("install say 1.0")) test_env.remove_dir(testing_paths.testing_sys_tree .. "/share/lua/"..test_env.lua_version.."/say") assert.is_true(run.luarocks_bool("purge --tree=" .. testing_paths.testing_sys_tree)) assert.is_false(test_env.exists(testing_paths.testing_sys_rocks .. "/say")) end) it("LuaRocks purge old versions tree", function() assert.is_true(run.luarocks_bool("purge --old-versions --tree=" .. testing_paths.testing_sys_tree)) end) end) end)
Tests: add regression test for #750
Tests: add regression test for #750 Fix #750.
Lua
mit
keplerproject/luarocks,tarantool/luarocks,keplerproject/luarocks,tarantool/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks
5368a9d43606359a568ab76071e86535b8a9e769
scheduled/gaia.lua
scheduled/gaia.lua
require("base.common") module("scheduled.gaia", package.seeall) -- INSERT INTO scheduledscripts VALUES('scheduled.gaia', 10, 10, 'plantdrop'); function AddPlant(ItemID,Ground,Frequenz,Season,Datawert) table.insert(plnt,ItemID); table.insert(grnd,Ground); table.insert(freq,Frequenz); table.insert(seas,Season); table.insert(dataval,Datawert); end function Init() plnt = {}; grnd = {}; freq = {}; seas = {}; dataval= {}; AddPlant(133,{1,1,1,1,4},1,{8,10,2,0},0); -- Sonnenkraut AddPlant(134,{4},1,{6,1,5,10},0); -- Vierbl�ttrige Einbeere AddPlant(135,{1},1,{10,6,3,0},0); -- Gelbkraut AddPlant(136,{5},1,{4,3,10,7},0); -- Wutbeere AddPlant(137,{3},1,{3,1,4,10},0); -- Flammkelchbl�te AddPlant(138,{2,7},1,{2,2,9,5},0); -- Nachtengelsbl�te AddPlant(140,{2},1,{10,2,7,3},0); -- Donfblatt AddPlant(141,{4},1,{3,10,5,0},0); -- Schwarze Distel AddPlant(142,{3},1,{2,3,10,6},0); -- Sandbeere AddPlant(143,{4},1,{0,5,10,5},0); -- Roter Holunder AddPlant(144,{5},1,{5,0,2,10},0); -- Jungfernkraut AddPlant(145,{4},1,{10,6,3,0},0); -- Heidebl�te AddPlant(146,{3},1,{6,5,10,5},0); -- W�stenhimmelkapsel AddPlant(148,{5},1,{2,10,3,0},0); -- Firnisbl�te AddPlant(152,{2,3,5,6},1,{4,4,4,4},0); -- Lebenswurz AddPlant(153,{5},1,{10,4,1,0},0); -- Fussblatt AddPlant(155,{7},1,{4,10,5,1},0); -- Sibanac Blatt AddPlant(156,{3},1,{10,1,2,4},0); -- Steppenfarn AddPlant(2696,{2,4,5},1,{6,4,8,1},80); -- Federn -- Pflanzen des DS-Systems mit SonderID in data AddPlant(133,{4},1,{8,10,6,0},9001); -- "Einbl�ttrige Vierbeere" / "oneleaved fourberry" AddPlant(134,{4},1,{6,0,6,10},9002); -- "Blaue Vogelbeere" / "blue birdsberry" AddPlant(135,{5},1,{10,6,0,8},9003); -- "Schwefelkraut" / "sulfur weed" AddPlant(136,{5},1,{0,6,10,7},9004); -- "Frommbeere" / "pious berry" AddPlant(137,{4},1,{6,0,6,10},9005); -- "Wasserbl�te" / "water blossom" AddPlant(138,{2},1,{0,6,10,6},9006); -- "Tagteufel" / "daydevil" AddPlant(140,{2},1,{10,6,0,6},9007); -- "Rauchblatt" / "reek leave" AddPlant(141,{5},1,{6,10,6,0},9008); -- "Graue Distel" / "grey thistle" AddPlant(142,{3},1,{0,6,10,6},9009); -- "W�stenbeere" / "desert berry" AddPlant(152,{4},1,{4,4, 4,4},9013); -- "Feuerwurz" / "fire root" AddPlant(144,{2},1,{6,0,6,10},9010); -- "Altweiberkraut" / "gossamer weed" AddPlant(145,{4},1,{10,6,0,6},9011); -- "Regenkraut" / "rain weed" AddPlant(146,{3},1,{6,10,6,0},9012); -- "Gottesblume" / "godsflower" AddPlant(148,{2},1,{6,10,6,0},9014); -- "Trugbl�te" / "con blossom" AddPlant(156,{2},1,{0,6,10,6},9015); -- "Wolfsfarn" / "wolverine fern" AddPlant(153,{4},1,{6,10,6,0},9016); -- "Wiesen-Rhabarber" / "meadow rhabarb" -- 0 alle / 1 Acker / 2 Wald / 3 Sand / 4 Wiese / 5 Fels / 6 Wasser / 7 Dreck anz_pflanzen = table.getn(plnt); anz_voraussetzungen = table.getn(grnd); end function plantdrop() if ( plnt==nil ) then Init(); end local season=math.ceil( world:getTime("month") / 4 ); season = base.common.Limit( season, 1, 4 ); local spawn_amm = 15; if (season == 1) then --Fr�hling spawn_amm = 40; elseif (season == 2) then --Sommer spawn_amm = 40; elseif (season == 3) then --Herbst spawn_amm = 40; elseif (season == 4) then --Winter spawn_amm = 40; end for i=1,spawn_amm do ---- Pflanze aussuchen auswahl = math.random( anz_pflanzen ); if( seas[ auswahl ][ season ] >= math.random(10) ) then success = true; else success = false; end if success then check = grnd[auswahl][math.random(1,table.getn(grnd[auswahl]))] pflwert = dataval[auswahl] ---- Standortbestimmung newpos = position( math.random(0,1000), math.random(0,1000), 0 ); ---- bodentile feststellen local bodenart = base.common.GetGroundType( world:getField(newpos):tile() ); if ((bodenart == check) or (check == 0)) then world:createItemFromId(plnt[auswahl],1,newpos,false,333,pflwert); end end end end
require("base.common") module("scheduled.gaia", package.seeall) -- INSERT INTO scheduledscripts VALUES('scheduled.gaia', 10, 10, 'plantdrop'); function AddPlant(ItemID,Ground,Frequenz,Season,Datawert) table.insert(plnt,ItemID); table.insert(grnd,Ground); table.insert(freq,Frequenz); table.insert(seas,Season); table.insert(dataval,Datawert); end function Init() plnt = {}; grnd = {}; freq = {}; seas = {}; dataval= {}; AddPlant(133,{1,1,1,1,4},1,{8,10,2,0},0); -- Sonnenkraut AddPlant(134,{4},1,{6,1,5,10},0); -- Vierbl�ttrige Einbeere AddPlant(135,{1},1,{10,6,3,0},0); -- Gelbkraut AddPlant(136,{5},1,{4,3,10,7},0); -- Wutbeere AddPlant(137,{3},1,{3,1,4,10},0); -- Flammkelchbl�te AddPlant(138,{2,7},1,{2,2,9,5},0); -- Nachtengelsbl�te AddPlant(140,{2},1,{10,2,7,3},0); -- Donfblatt AddPlant(141,{4},1,{3,10,5,0},0); -- Schwarze Distel AddPlant(142,{3},1,{2,3,10,6},0); -- Sandbeere AddPlant(143,{4},1,{0,5,10,5},0); -- Roter Holunder AddPlant(144,{5},1,{5,0,2,10},0); -- Jungfernkraut AddPlant(145,{4},1,{10,6,3,0},0); -- Heidebl�te AddPlant(146,{3},1,{6,5,10,5},0); -- W�stenhimmelkapsel AddPlant(148,{5},1,{2,10,3,0},0); -- Firnisbl�te AddPlant(152,{2,3,5,6},1,{4,4,4,4},0); -- Lebenswurz AddPlant(153,{5},1,{10,4,1,0},0); -- Fussblatt AddPlant(155,{7},1,{4,10,5,1},0); -- Sibanac Blatt AddPlant(156,{3},1,{10,1,2,4},0); -- Steppenfarn AddPlant(2696,{2,4,5},1,{6,4,8,1},80); -- Federn -- Pflanzen des DS-Systems mit SonderID in data AddPlant(133,{4},1,{8,10,6,0},9001); -- "Einbl�ttrige Vierbeere" / "oneleaved fourberry" AddPlant(134,{4},1,{6,0,6,10},9002); -- "Blaue Vogelbeere" / "blue birdsberry" AddPlant(135,{5},1,{10,6,0,8},9003); -- "Schwefelkraut" / "sulfur weed" AddPlant(136,{5},1,{0,6,10,7},9004); -- "Frommbeere" / "pious berry" AddPlant(137,{4},1,{6,0,6,10},9005); -- "Wasserbl�te" / "water blossom" AddPlant(138,{2},1,{0,6,10,6},9006); -- "Tagteufel" / "daydevil" AddPlant(140,{2},1,{10,6,0,6},9007); -- "Rauchblatt" / "reek leave" AddPlant(141,{5},1,{6,10,6,0},9008); -- "Graue Distel" / "grey thistle" AddPlant(142,{3},1,{0,6,10,6},9009); -- "W�stenbeere" / "desert berry" AddPlant(152,{4},1,{4,4, 4,4},9013); -- "Feuerwurz" / "fire root" AddPlant(144,{2},1,{6,0,6,10},9010); -- "Altweiberkraut" / "gossamer weed" AddPlant(145,{4},1,{10,6,0,6},9011); -- "Regenkraut" / "rain weed" AddPlant(146,{3},1,{6,10,6,0},9012); -- "Gottesblume" / "godsflower" AddPlant(148,{2},1,{6,10,6,0},9014); -- "Trugbl�te" / "con blossom" AddPlant(156,{2},1,{0,6,10,6},9015); -- "Wolfsfarn" / "wolverine fern" AddPlant(153,{4},1,{6,10,6,0},9016); -- "Wiesen-Rhabarber" / "meadow rhabarb" -- 0 alle / 1 Acker / 2 Wald / 3 Sand / 4 Wiese / 5 Fels / 6 Wasser / 7 Dreck anz_pflanzen = table.getn(plnt); anz_voraussetzungen = table.getn(grnd); end function plantdrop() if ( plnt==nil ) then Init(); end local season=math.ceil( world:getTime("month") / 4 ); season = base.common.Limit( season, 1, 4 ); local spawn_amm = 15; if (season == 1) then --Fr�hling spawn_amm = 40; elseif (season == 2) then --Sommer spawn_amm = 40; elseif (season == 3) then --Herbst spawn_amm = 40; elseif (season == 4) then --Winter spawn_amm = 40; end for i=1,spawn_amm do ---- Pflanze aussuchen auswahl = math.random( anz_pflanzen ); if( seas[ auswahl ][ season ] >= math.random(10) ) then success = true; else success = false; end if success then check = grnd[auswahl][math.random(1,table.getn(grnd[auswahl]))] pflwert = dataval[auswahl] ---- Standortbestimmung newpos = position( math.random(0,1000), math.random(0,1000), 0 ); ---- bodentile feststellen theTile=world:getField(newpos); local bodenart = base.common.GetGroundType( theTile.tile ); if ((bodenart == check) or (check == 0)) then world:createItemFromId(plnt[auswahl],1,newpos,false,333,pflwert); end end end end
Tried to solve a bug.
Tried to solve a bug.
Lua
agpl-3.0
KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content
f9600ce63d4a7717b2b554a7e96a21f4e5678a76
main.lua
main.lua
io.stdout:setvbuf("no") local events = require("Engine.events") --Internal Callbacks-- function love.load() love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run() if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(arg) end -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw if love.update then events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled end if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end end end
io.stdout:setvbuf("no") local events = require("Engine.events") --Internal Callbacks-- function love.load() love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run() if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(arg) end -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end end end
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
9ce763234292b4b9029ecf654ff396485d71a2d2
src/patch/ui/hooks/common/protocol_kickunpatched.lua
src/patch/ui/hooks/common/protocol_kickunpatched.lua
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. if _mpPatch and _mpPatch.loaded then local playerMap = {} local getPlayerName, joinWarning1Ending function _mpPatch.hooks.protocol_kickunpached_init(pGetPlayerName, pIsInGame) getPlayerName = pGetPlayerName joinWarning1Ending = Locale.Lookup(isInGame and "TXT_KEY_MPPATCH_JOIN_WARNING_1_INGAME" or "TXT_KEY_MPPATCH_JOIN_WARNING_1_STAGING") end local website = _mpPatch.version.info["mppatch.website"] or "<unknown>" local function getHeader(playerId) local header = "" if getPlayerName then local name = getPlayerName(playerId) if name then header = "@"..tostring(name)..": " end end return header end function _mpPatch.hooks.protocol_kickunpached_installHooks() _mpPatch.addResetHook(function() playerMap = {} end) _mpPatch.net.clientIsPatched.registerHandler(function(protocolVersion, playerID) if Matchmaking.IsHost() then if protocolVersion == _mpPatch.protocolVersion then playerMap[playerID] = nil else local header = getHeader(playerId) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_OUTDATED").." ".. joinWarning1Ending) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end end end) local function checkPlayerId(player, reason) if playerMap[player] then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch. ("..reason..")") Matchmaking.KickPlayer(player) playerMap[player] = nil end end _mpPatch.event.kickIfUnpatched.registerHandler(function(player, reason) if Matchmaking.IsHost() then checkPlayerId(player, reason) end end) _mpPatch.event.kickAllUnpatched.registerHandler(function(reason) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do checkPlayerId(player, reason) end end end) end function _mpPatch.hooks.protocol_kickunpached_onUpdate(timeDiff) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do playerMap[player] = playerMap[player] - timeDiff if playerMap[player] <= 0 then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch.") Matchmaking.KickPlayer(player) playerMap[player] = nil end end end end function _mpPatch.hooks.protocol_kickunpached_onJoin(playerId) if Matchmaking.IsHost() and not playerMap[playerId] then local header = getHeader(playerId) _mpPatch.net.skipNextChat(2) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_NOT_INSTALLED").." ".. joinWarning1Ending) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) playerMap[playerId] = 30 end end function _mpPatch.hooks.protocol_kickunpached_onDisconnect(playerId) if Matchmaking.IsHost() then playerMap[playerId] = nil end end end
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. if _mpPatch and _mpPatch.loaded then local playerMap = {} local isPatched = {} local getPlayerName, joinWarning1Ending function _mpPatch.hooks.protocol_kickunpached_init(pGetPlayerName, pIsInGame) getPlayerName = pGetPlayerName joinWarning1Ending = Locale.Lookup(isInGame and "TXT_KEY_MPPATCH_JOIN_WARNING_1_INGAME" or "TXT_KEY_MPPATCH_JOIN_WARNING_1_STAGING") end local website = _mpPatch.version.info["mppatch.website"] or "<unknown>" local function getHeader(playerId) local header = "" if getPlayerName then local name = getPlayerName(playerId) if name then header = "@"..tostring(name)..": " end end return header end function _mpPatch.hooks.protocol_kickunpached_installHooks() _mpPatch.addResetHook(function() playerMap = {} isPatched = {} end) _mpPatch.net.clientIsPatched.registerHandler(function(protocolVersion, playerId) if Matchmaking.IsHost() then if protocolVersion == _mpPatch.protocolVersion then playerMap[playerId] = nil isPatched[playerId] = true else local header = getHeader(playerId) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_OUTDATED").." ".. joinWarning1Ending) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end end end) local function checkPlayerId(player, reason) if playerMap[player] then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch. ("..reason..")") Matchmaking.KickPlayer(player) playerMap[player] = nil end end _mpPatch.event.kickIfUnpatched.registerHandler(function(player, reason) if Matchmaking.IsHost() then checkPlayerId(player, reason) end end) _mpPatch.event.kickAllUnpatched.registerHandler(function(reason) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do checkPlayerId(player, reason) end end end) end function _mpPatch.hooks.protocol_kickunpached_onUpdate(timeDiff) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do playerMap[player] = playerMap[player] - timeDiff if playerMap[player] <= 0 then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch.") Matchmaking.KickPlayer(player) playerMap[player] = nil end end end end function _mpPatch.hooks.protocol_kickunpached_onJoin(playerId) if Matchmaking.IsHost() and not playerMap[playerId] and not isPatched[playerId] then local header = getHeader(playerId) _mpPatch.net.skipNextChat(2) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_NOT_INSTALLED").." ".. joinWarning1Ending) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) playerMap[playerId] = 30 end end function _mpPatch.hooks.protocol_kickunpached_onDisconnect(playerId) if Matchmaking.IsHost() then playerMap[playerId] = nil isPatched[playerId] = nil end end end
Fix MPPatch detection for hotjoins.
Fix MPPatch detection for hotjoins.
Lua
mit
Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager
af292e2b4b0b7fd699c216fa83da9b1dca6ff4f1
src/premake-system.lua
src/premake-system.lua
local function _updateRepo(destination, url, name, branch) local current = os.getcwd() if os.isdir(destination) then printf(" - Updating '%s'", name) os.chdir(destination) if branch then os.executef("git checkout %s", branch) else os.execute("git checkout .") end os.execute("git pull") os.chdir(current) else printf(" - Creating '%s'", name) if branch then os.executef("git clone -v -b %s --recurse --progress \"%s\" \"%s\"", branch, url, destination) else os.executef("git clone -v --recurse --progress \"%s\" \"%s\"", url, destination) end end end newaction { trigger = "update-bootstrap", shortname = "Update module loader", description = "Updates the module loader bootstrapping process", execute = function() local destination = path.join(CMD, BOOTSTRAP_DIR) _updateRepo(destination, BOOTSTRAP_REPO, "bootstrap loader") end } newaction { trigger = "update-zpm", shortname = "Update zpm", description = "Updates the zpm module", execute = function() local destination = path.join(CMD, INSTALL_DIR) _updateRepo(destination, INSTALL_REPO, "zpm", ZPM_BRANCH) end } newaction { trigger = "update-registry", shortname = "Update the registry", description = "Updates the zpm library definitions", execute = function() local destination = path.join(CMD, REGISTRY_DIR) _updateRepo(destination, REGISTRY_REPO, "registry") if os.isdir(REGISTRY_DIR) then assert(os.mkdir(REGISTRY_DIR)) end end } if _ACTION ~= "update-bootstrap" and _ACTION ~= "update-zpm" and _ACTION ~= "update-registry" then if _ACTION ~= "install-zpm" then bootstrap = dofile(path.join(_PREMAKE_DIR, "../bootstrap/bootstrap.lua")) end if not zpm or not zpm.__isLoaded then zpm = dofile(path.join(_PREMAKE_DIR, "../zpm/zpm.lua")) zpm.onLoad() zpm.__isLoaded = true end else _MAIN_SCRIPT = "." end
local function _updateRepo(destination, url, name, branch) local current = os.getcwd() if os.isdir(destination) then printf(" - Updating '%s'", name) os.chdir(destination) if branch then os.executef("git checkout %s", branch) else os.execute("git checkout .") end os.execute("git pull") os.chdir(current) else printf(" - Creating '%s'", name) if branch then os.executef("git clone -v -b %s --recurse --progress \"%s\" \"%s\"", branch, url, destination) else os.executef("git clone -v --recurse --progress \"%s\" \"%s\"", url, destination) end end end newaction { trigger = "update-bootstrap", shortname = "Update module loader", description = "Updates the module loader bootstrapping process", execute = function() local destination = path.join(CMD, BOOTSTRAP_DIR) _updateRepo(destination, BOOTSTRAP_REPO, "bootstrap loader") end } newaction { trigger = "update-zpm", shortname = "Update zpm", description = "Updates the zpm module", execute = function() local destination = path.join(CMD, INSTALL_DIR) _updateRepo(destination, INSTALL_REPO, "zpm", ZPM_BRANCH) end } newaction { trigger = "update-registry", shortname = "Update the registry", description = "Updates the zpm library definitions", execute = function() local destination = path.join(CMD, REGISTRY_DIR) _updateRepo(destination, REGISTRY_REPO, "registry") if os.isdir(REGISTRY_DIR) then assert(os.mkdir(REGISTRY_DIR)) end end } if _ACTION ~= "update" then if not (_ACTION == "install" and _ARGS[1] == "zpm" ) then bootstrap = dofile(path.join(_PREMAKE_DIR, "../bootstrap/bootstrap.lua")) end if not zpm or not zpm.__isLoaded then zpm = dofile(path.join(_PREMAKE_DIR, "../zpm/zpm.lua")) zpm.onLoad() zpm.__isLoaded = true end else _MAIN_SCRIPT = "." end
Fix installer
Fix installer
Lua
mit
Zefiros-Software/ZPM
bdb81c72f1c15357680a5a4c21a165990a68d604
frontend/version.lua
frontend/version.lua
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, revision = rev:match("v(%d%d%d%d)%.(%d%d)-?(%d*)") local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see normalized_version function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end return Version
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, revision = rev:match("v(%d%d%d%d)%.(%d%d)-?(%d*)") if type(year) ~= "number" then revision = 0 end if type(month) ~= "number" then revision = 0 end if type(revision) ~= "number" then revision = 0 end local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see normalized_version function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end return Version
[hotfix] Version: empty pattern max is an empty string, not nil! (#4299)
[hotfix] Version: empty pattern max is an empty string, not nil! (#4299) Fixes #4298.
Lua
agpl-3.0
poire-z/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,houqp/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader,pazos/koreader,NiLuJe/koreader,mwoz123/koreader,Markismus/koreader,NiLuJe/koreader,Hzj-jie/koreader
869f867dd3df1bf4f972198ea84cd09ceeffade8
test/serialize.lua
test/serialize.lua
#!/usr/bin/env lua -- Script for serializing a lua-gumbo parse tree into various formats. -- Can be used with the diff utility for testing against expected output. local gumbo = require "gumbo" local open = io.open local usage = [[ Usage: %s COMMAND [INPUT-FILE] [OUTPUT-FILE] Commands: html Parse and serialize back to HTML table Parse and serialize to Lua table tree Parse and serialize to html5lib tree-constructor format bench Parse and print CPU time and memory usage information help Print usage information and exit ]] local commands = setmetatable({}, {__index = function(s) return s.help end}) function commands.help() io.stdout:write(string.format(usage, arg[0])) end function commands.html(input, output) local to_html = require "gumbo.serialize.html" local document = assert(gumbo.parse_file(input)) to_html(document, output) end function commands.table(input, output) local to_table = require "gumbo.serialize.table" local document = assert(gumbo.parse_file(input)) to_table(document, output) end function commands.tree(input, output) local to_tree = require "gumbo.serialize.html5lib" local document = assert(gumbo.parse_file(input)) to_tree(document, output) end function commands.bench(input) local start = os.clock() local liveref = assert(gumbo.parse_file(input)) local elapsed = ("%.2f"):format(os.clock() - start) collectgarbage() local mem = ("%.0f"):format(collectgarbage("count")) local memsep = mem:reverse():gsub('(%d%d%d)', '%1,'):reverse() io.stderr:write(elapsed, "s / ", memsep, " KB\n") end local input = (arg[2] and arg[2] ~= "-") and assert(open(arg[2])) or io.stdin local output = arg[3] and assert(open(arg[3], "a")) or io.stdout commands[arg[1]](input, output)
#!/usr/bin/env lua -- Script for serializing a lua-gumbo parse tree into various formats. -- Can be used with the diff utility for testing against expected output. local gumbo = require "gumbo" local format = string.format local open = io.open local usage = [[ Usage: %s COMMAND [INPUT-FILE] [OUTPUT-FILE] Commands: html Parse and serialize back to HTML table Parse and serialize to Lua table tree Parse and serialize to html5lib tree-constructor format bench Parse and print CPU time and memory usage information help Print usage information and exit ]] local commands = setmetatable({}, {__index = function(s) return s.help end}) function commands.help() io.stdout:write(string.format(usage, arg[0])) end function commands.html(input, output) local to_html = require "gumbo.serialize.html" local document = assert(gumbo.parse_file(input)) to_html(document, output) end function commands.table(input, output) local to_table = require "gumbo.serialize.table" local document = assert(gumbo.parse_file(input)) to_table(document, output) end function commands.tree(input, output) local to_tree = require "gumbo.serialize.html5lib" local document = assert(gumbo.parse_file(input)) to_tree(document, output) end function commands.bench(input) local start = os.clock() local liveref = assert(gumbo.parse_file(input)) local elapsed = format("%.2f", os.clock() - start) collectgarbage() local mem = format("%.0f", collectgarbage("count")) local memsep = mem:reverse():gsub('(%d%d%d)', '%1,'):reverse() io.stderr:write(elapsed, "s / ", memsep, " KB\n") end local input = (arg[2] and arg[2] ~= "-") and assert(open(arg[2])) or io.stdin local output = arg[3] and assert(open(arg[3], "a")) or io.stdout commands[arg[1]](input, output)
Style fixes for previous commit
Style fixes for previous commit
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
7d4488f149feb66c8933af290b63745ef656236d
path.lua
path.lua
--[[ Copyright (C) 2013 Masatoshi Teruya Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local pathc = require('path.pathc'); local function normalize( ... ) local argv = {...}; local path = argv[1]; local res = {}; if #argv > 1 then path = table.concat( argv, '/' ); else path = argv[1]; end -- remove double slash path = path:gsub( '/+', '/' ); for seg in string.gmatch( path, '[^/]+' ) do if seg == '..' then table.remove( res ); elseif seg ~= '.' then table.insert( res, seg ); end end return '/' .. table.concat( res, '/' ); end return { normalize = normalize, dirname = pathc.dirname, basename = pathc.basename, extname = pathc.extname, exists = pathc.exists, stat = pathc.stat, toReg = pathc.toReg, toDir = pathc.toDir, isReg = pathc.isReg, isDir = pathc.isDir, isChr = pathc.isChr, isBlk = pathc.isBlk, isFifo = pathc.isFifo, isLnk = pathc.isLnk, isSock = pathc.isSock, readdir = pathc.readdir };
--[[ Copyright (C) 2013 Masatoshi Teruya Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local pathc = require('path.pathc'); local function concat( sep, ... ) local argv = {...}; local i, v = next( argv ); local res = {}; local len = 0; while i do if v ~= nil then len = len + 1; res[len] = tostring( v ); end i, v = next( argv, i ); end return table.concat( res, sep ); end local function normalize( ... ) local path = concat( '/', ... ); local res = {}; local len = 0; -- remove double slash path = path:gsub( '/+', '/' ); for seg in string.gmatch( path, '[^/]+' ) do if seg == '..' then if len > 0 then res[len] = nil; len = len - 1; end elseif seg ~= '.' then len = len + 1; res[len] = seg; end end return '/' .. table.concat( res, '/' ); end return { normalize = normalize, dirname = pathc.dirname, basename = pathc.basename, extname = pathc.extname, exists = pathc.exists, stat = pathc.stat, toReg = pathc.toReg, toDir = pathc.toDir, isReg = pathc.isReg, isDir = pathc.isDir, isChr = pathc.isChr, isBlk = pathc.isBlk, isFifo = pathc.isFifo, isLnk = pathc.isLnk, isSock = pathc.isSock, readdir = pathc.readdir };
fix: arguments of normalize function should accept nil values.
fix: arguments of normalize function should accept nil values.
Lua
mit
mah0x211/lua-path
11a9470a5c0a31ca376fb62bd791d0cc4deaa1b6
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 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
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() if not array then return function() end end 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 iterate() when empty
fix iterate() when empty
Lua
mit
scottcs/wyx
ff3154438727888c71de1c2a87d9d4220c8bf510
OS/DiskOS/Libraries/SyntaxParser/init.lua
OS/DiskOS/Libraries/SyntaxParser/init.lua
local newStream = require("Libraries.SyntaxParser.stream") local parser = {} parser.parser = {} parser.cache = {} parser.state = nil function parser:loadParser(language) self.parser = require("Libraries.SyntaxParser.languages."..language) end function parser:previousState(lineIndex) local record = 0 for i, state in pairs(self.cache) do if i >= lineIndex then break end if i > record then record = i end end if record > 0 then return self.cache[record] else return false end end function parser:parseLines(lines, lineIndex) local result = {} -- Forget all states after the modified line for i, state in pairs(self.cache) do if i > lineIndex then self.cache[i] = nil end end -- Process lines local colateral = false for lineID = lineIndex, lineIndex + #lines - 1 do local line = lines[lineID - #lines + 1] self.state = {} -- Copy previous line state table, or create a new one if needed. -- TODO: language should provide a copy method. local tempState = self.cache[lineID - 1] or self:previousState(lineIndex) or self.parser.startState() for k,v in pairs(tempState) do self.state[k] = v end -- Backup previous state of the current line local previousState = {} if self.cache[lineID] then for k,v in pairs(self.cache[lineID]) do previousState[k] = v end end -- Process line table.insert(result, parser:parseLine(line)) -- Copy the processd state to cache. -- Also checks if this is the last line and its change is colateral. self.cache[lineID] = {} for k,v in pairs(self.state) do if i == #lines and previousState[k] ~= self.state[k] then colateral = true end self.cache[lineID][k] = v end end return result, colateral end function parser:parseLine(line) local result = {} local stream = newStream(line) while not stream:eol() do local token = self.parser.token(stream, self.state) result[#result + 1] = token or "text" result[#result + 1] = stream:current() --The text read by the tokenizer stream.start = stream.pos end if #result == 0 then return {"text", line} end return result end return parser
local newStream = require("Libraries.SyntaxParser.stream") local parser = {} parser.parser = {} parser.cache = {} parser.state = nil function parser:loadParser(language) self.cache = {} self.state = nil self.parser = require("Libraries.SyntaxParser.languages."..language) end function parser:previousState(lineIndex) local record = 0 for i, state in pairs(self.cache) do if i >= lineIndex then break end if i > record then record = i end end if record > 0 then return self.cache[record] else return false end end function parser:parseLines(lines, lineIndex) local result = {} -- Forget all states after the modified line for i, state in pairs(self.cache) do if i > lineIndex then self.cache[i] = nil end end -- Process lines local colateral = false for i=1, #lines do local line = lines[i] local lineID = lineIndex + i - 1 self.state = {} -- Copy previous line state table, or create a new one if needed. -- TODO: language should provide a copy method. local tempState = self.cache[lineID - 1] or self:previousState(lineIndex) or self.parser.startState() for k,v in pairs(tempState) do self.state[k] = v end -- Backup previous state of the current line local previousState = {} if self.cache[lineID] then for k,v in pairs(self.cache[lineID]) do previousState[k] = v end end -- Process line table.insert(result, parser:parseLine(line)) -- Copy the processd state to cache. -- Also checks if this is the last line and its change is colateral. self.cache[lineID] = {} for k,v in pairs(self.state) do if i == #lines and previousState[k] ~= self.state[k] then colateral = true end self.cache[lineID][k] = v end end return result, colateral end function parser:parseLine(line) local result = {} local stream = newStream(line) while not stream:eol() do local token = self.parser.token(stream, self.state) result[#result + 1] = token or "text" result[#result + 1] = stream:current() --The text read by the tokenizer stream.start = stream.pos end if #result == 0 then return {"text", line} end return result end return parser
Bugfix
Bugfix Former-commit-id: 8972e0330ac80533391798d3de76841d83277f4b
Lua
mit
RamiLego4Game/LIKO-12
0bacdf08c50dd952842dbc953965ce35e9734f3d
scripts/make_thumbnail.lua
scripts/make_thumbnail.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/>. -- Knora GUI-case: create a thumbnail require "send_response" success, errormsg = server.setBuffer() if not success then return -1 end -- -- check if tmporary directory is available, if not, create it -- local tmpdir = config.imgroot .. '/tmp/' local success, exists = server.fs.exists(tmpdir) if not success then send_error(500, "Internal server error") return -1 end if not exists then local success, result = server.fs.mkdir(tmpdir, 511) if not success then send_error(500, "Couldn't create tmpdir: " .. result) return end end for imgindex,imgparam in pairs(server.uploads) do -- -- copy the file to a safe place -- local success, tmpname = server.uuid62() if not success then send_error(500, "Couldn't generate uuid62!") return -1 end local tmppath = tmpdir .. tmpname local success, result = server.copyTmpfile(imgindex, tmppath) if not success then send_error(500, "Couldn't copy uploaded file: " .. result) return -1 end -- -- create a SipiImage, already resized to the thumbnail size -- local success, myimg = SipiImage.new(tmppath, {size = config.thumb_size}) if not success then send_error(500, "Couldn't create thumbnail: " .. myimg) return -1 end local filename = imgparam["origname"] local mimetype = imgparam["mimetype"] local success, check = myimg:mimetype_consistency(mimetype, filename) if not success then send_error(500, "Couldn't check mimteype consistency: " .. check) return -1 end -- -- if check returns false, the user's input is invalid -- if not check then send_error(400, MIMETYPES_INCONSISTENCY) return -1 end -- -- get the dimensions and print them -- local success, dims = myimg:dims() if not success then send_error(500, "Couldn't get image dimensions: " .. dims) return -1 end -- -- write the thumbnail file -- local thumbsdir = config.imgroot .. '/thumbs/' local success, exists = server.fs.exists(thumbsdir) if not success then send_error(500, "Internal server error") return -1 end if not exists then local success, result = server.fs.mkdir(thumbsdir, 511) if not success then send_error(500, "Couldn't create thumbsdir: " .. result) return -1 end end local thumbname = thumbsdir .. tmpname .. "_THUMB.jpg" local success, result = myimg:write(thumbname) if not success then send_error(500, "Couldn't create thumbnail: " .. result) return -1 end answer = { nx_thumb = dims.nx, ny_thumb = dims.ny, mimetype_thumb = 'image/jpeg', preview_path = "http://localhost:1024/thumbs/" .. tmpname .. "_THUMB.jpg" .. "/full/full/0/default.jpg", filename = tmpname, -- make this a IIIF URL original_mimetype = mimetype, original_filename = filename, file_type = 'IMAGE' } end send_success(answer)
-- -- 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/>. -- Knora GUI-case: create a thumbnail require "send_response" success, errormsg = server.setBuffer() if not success then return -1 end -- -- check if tmporary directory is available, if not, create it -- local tmpdir = config.imgroot .. '/tmp/' local success, exists = server.fs.exists(tmpdir) if not success then send_error(500, "Internal server error") return -1 end if not exists then local success, result = server.fs.mkdir(tmpdir, 511) if not success then send_error(500, "Couldn't create tmpdir: " .. result) return end end if server.uploads == nil then send_error(500, "no image uploaded") return -1 end for imgindex,imgparam in pairs(server.uploads) do -- -- copy the file to a safe place -- local success, tmpname = server.uuid62() if not success then send_error(500, "Couldn't generate uuid62!") return -1 end local tmppath = tmpdir .. tmpname local success, result = server.copyTmpfile(imgindex, tmppath) if not success then send_error(500, "Couldn't copy uploaded file: " .. result) return -1 end -- -- create a SipiImage, already resized to the thumbnail size -- local success, myimg = SipiImage.new(tmppath, {size = config.thumb_size}) if not success then send_error(500, "Couldn't create thumbnail: " .. myimg) return -1 end local filename = imgparam["origname"] local mimetype = imgparam["mimetype"] local success, check = myimg:mimetype_consistency(mimetype, filename) if not success then send_error(500, "Couldn't check mimteype consistency: " .. check) return -1 end -- -- if check returns false, the user's input is invalid -- if not check then send_error(400, MIMETYPES_INCONSISTENCY) return -1 end -- -- get the dimensions and print them -- local success, dims = myimg:dims() if not success then send_error(500, "Couldn't get image dimensions: " .. dims) return -1 end -- -- write the thumbnail file -- local thumbsdir = config.imgroot .. '/thumbs/' local success, exists = server.fs.exists(thumbsdir) if not success then send_error(500, "Internal server error") return -1 end if not exists then local success, result = server.fs.mkdir(thumbsdir, 511) if not success then send_error(500, "Couldn't create thumbsdir: " .. result) return -1 end end local thumbname = thumbsdir .. tmpname .. "_THUMB.jpg" local success, result = myimg:write(thumbname) if not success then send_error(500, "Couldn't create thumbnail: " .. result) return -1 end answer = { nx_thumb = dims.nx, ny_thumb = dims.ny, mimetype_thumb = 'image/jpeg', preview_path = "http://localhost:1024/thumbs/" .. tmpname .. "_THUMB.jpg" .. "/full/full/0/default.jpg", filename = tmpname, -- make this a IIIF URL original_mimetype = mimetype, original_filename = filename, file_type = 'IMAGE' } end send_success(answer)
fix (check for uploaded image): check if there was an image uploaded
fix (check for uploaded image): check if there was an image uploaded
Lua
agpl-3.0
dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi
9197fc03cc759c2fa40ac87e71b549d3e91f73dd
Model.lua
Model.lua
local Model = {}; local Plotter = require 'Plotter' Model.Lattice = nil; Model.k = 1; -- boltzmann function Model:New() local obj = {}; setmetatable(obj, {__index=self}) return obj end -- Helper functions, get min/max val of a table. local function mint(t) cmin = math.huge; for i,v in pairs(t) do if v < cmin then cmin = v end end return cmin end local function maxt(t) cmax = -math.huge for i,v in pairs(t) do if v > cmax then cmax = v end end return cmax end -- function Model:Run(PList, SweepMode, SweepOptions) local index = next(PList) local DataOut = {}; if SweepMode == "Cycle" then for i = 1, #PList[index] do -- Set vars. for ParamName, Params in pairs(PList) do self.Lattice[ParamName] = Params[i]; end local rep = true; while rep do rep=false; -- Sweep over grain. for _, Grain in pairs(self.Lattice.Grains) do --print(self.Lattice:GetDeltaU(Grain)) if self.Lattice:GetDeltaU(Grain) < 0 then self.Lattice:FlipSpin(Grain); rep=true; end end end -- self.Lattice:Show() -- print(self.Lattice:GetM(), PList.ExternalField[i]) self.Lattice:Dump("tmp.lat") local Measure = self:Measure(self.Lattice); for ParamName, Data in pairs(PList) do if not DataOut[ParamName]then DataOut[ParamName] = {}; end local xValue = Data[i]; for index, yValue in pairs(Measure) do if not (DataOut[ParamName][index]) then DataOut[ParamName][index] = {x = {}, y = {}}; end table.insert(DataOut[ParamName][index].x, xValue); table.insert(DataOut[ParamName][index].y, yValue); end end end self.Lattice:ToAnim("tmp.lat", "out.gif",4,5,1) -- Plot this data. for xLabel, Contents in pairs(DataOut) do for yLabel, Data in pairs(Contents) do local NewPlot = Plotter:New(); NewPlot:Set("xlabel", "Normalized temperature") -- Create a new plot. NewPlot:Set("ylabel", "Volume fraction metal"); local Data = Data; if yLabel == "M" and xLabel == "ExternalField" then local new = {}; new.x = {}; new.y = {}; local min_x = mint(Data.x); local max_x = maxt(Data.x); for ind, val in pairs(Data.x) do table.insert(new.x, (val - min_x)/(max_x - min_x)); end local min_y = mint(Data.y); local max_y = maxt(Data.y); for ind, val in pairs(Data.y) do table.insert(new.y, (val - min_y)/(max_y - min_y)); end NewPlot:SetData("xdata", new.x,true); NewPlot:SetData("ydata", new.y); else NewPlot:SetData("xdata", Data.x,true); NewPlot:SetData("ydata", Data.y); end NewPlot:SetData("title", yLabel .. " vs " .. xLabel) NewPlot:Plot(yLabel.."vs"..xLabel..".png") end end elseif SweepMode == "Metropolis" then local SweepOptions = SweepOptions or {}; -- One full sweep per setting is default. local Sweeps = SweepOptions.Sweeps or self.Lattice.x*self.Lattice.y*self.Lattice.z; local k = self.k; for i = 1, #PList[index] do -- Set vars. for ParamName, Params in pairs(PList) do self.Lattice[ParamName] = Params[i]; end local rep = true; while rep do rep=false; -- Sweep over grain. for _, Grain in pairs(self.Lattice.Grains) do --print(self.Lattice:GetDeltaU(Grain)) if self.Lattice:GetDeltaU(Grain) < 0 then self.Lattice:FlipSpin(Grain); rep=true; end end end for Sweep = 1,Sweeps do -- Pick a random grain; local Grain = self.Lattice:GetRandomLatticeSite(); local dU = self.Lattice:GetDeltaU(Grain); -- print(dU, dU/(self.k*self.Lattice.Temperature), math.exp(-dU/(self.k*self.Lattice.Temperature))) if dU <= 0 then self.Lattice:FlipSpin(Grain) elseif math.exp(-dU/(self.k*self.Lattice.Temperature)) > math.random() then self.Lattice:FlipSpin(Grain) end end -- print(self.Lattice.ExternalField) -- self.Lattice:Show() -- print(self.Lattice:GetM(), PList.ExternalField[i]) -- self.Lattice:Dump("tmp.lat") local Measure = self:Measure(self.Lattice); for ParamName, Data in pairs(PList) do if not DataOut[ParamName]then DataOut[ParamName] = {}; end local xValue = Data[i]; for index, yValue in pairs(Measure) do if not (DataOut[ParamName][index]) then DataOut[ParamName][index] = {x = {}, y = {}}; end table.insert(DataOut[ParamName][index].x, xValue); table.insert(DataOut[ParamName][index].y, yValue); end end end for xLabel, Contents in pairs(DataOut) do for yLabel, Data in pairs(Contents) do local NewPlot = Plotter:New(); NewPlot:Set("xlabel", xlabel) -- Create a new plot. NewPlot:Set("ylabel", ylabel); local Data = Data; if yLabel == "M" and xLabel == "ExternalField" then local new = {}; new.x = {}; new.y = {}; local min_x = mint(Data.x); local max_x = maxt(Data.x); for ind, val in pairs(Data.x) do table.insert(new.x, (val - min_x)/(max_x - min_x)); end local min_y = mint(Data.y); local max_y = maxt(Data.y); for ind, val in pairs(Data.y) do table.insert(new.y, (val - min_y)/(max_y - min_y)); end NewPlot:SetData("xdata", new.x,true); NewPlot:SetData("ydata", new.y); else NewPlot:SetData("xdata", Data.x,true); NewPlot:SetData("ydata", Data.y); end -- NewPlot:SetData("title", yLabel .. " vs " .. xLabel) NewPlot:Plot(yLabel.."vs"..xLabel..".png") end end end end return Model
local Model = {}; local Plotter = require 'Plotter' Model.Lattice = nil; Model.k = 1; -- boltzmann function Model:New() local obj = {}; setmetatable(obj, {__index=self}) return obj end -- Helper functions, get min/max val of a table. local function mint(t) cmin = math.huge; for i,v in pairs(t) do if v < cmin then cmin = v end end return cmin end local function maxt(t) cmax = -math.huge for i,v in pairs(t) do if v > cmax then cmax = v end end return cmax end -- function Model:Run(PList, SweepMode, Options) local index = next(PList) local DataOut = {}; local ANIM = Options and Options.Anim; if SweepMode == "Cycle" then for i = 1, #PList[index] do -- Set vars. for ParamName, Params in pairs(PList) do self.Lattice[ParamName] = Params[i]; end local rep = true; while rep do rep=false; -- Sweep over grain. for _, Grain in pairs(self.Lattice.Grains) do --print(self.Lattice:GetDeltaU(Grain)) if self.Lattice:GetDeltaU(Grain) < 0 then self.Lattice:FlipSpin(Grain); rep=true; end end end -- self.Lattice:Show() -- print(self.Lattice:GetM(), PList.ExternalField[i]) if ANIM then self.Lattice:Dump("tmp.lat") end local Measure = self:Measure(self.Lattice); for ParamName, Data in pairs(PList) do if not DataOut[ParamName]then DataOut[ParamName] = {}; end local xValue = Data[i]; for index, yValue in pairs(Measure) do if not (DataOut[ParamName][index]) then DataOut[ParamName][index] = {x = {}, y = {}}; end table.insert(DataOut[ParamName][index].x, xValue); table.insert(DataOut[ParamName][index].y, yValue); end end end if ANIM then self.Lattice:ToAnim("tmp.lat", "out.gif",4,5,1) end -- Plot this data. for xLabel, Contents in pairs(DataOut) do for yLabel, Data in pairs(Contents) do local NewPlot = Plotter:New(); NewPlot:Set("xlabel", "Normalized temperature") -- Create a new plot. NewPlot:Set("ylabel", "Volume fraction metal"); local Data = Data; if yLabel == "M" and xLabel == "ExternalField" then local new = {}; new.x = {}; new.y = {}; local min_x = mint(Data.x); local max_x = maxt(Data.x); for ind, val in pairs(Data.x) do table.insert(new.x, (val - min_x)/(max_x - min_x)); end local min_y = mint(Data.y); local max_y = maxt(Data.y); for ind, val in pairs(Data.y) do table.insert(new.y, (val - min_y)/(max_y - min_y)); end NewPlot:SetData("xdata", new.x,true); NewPlot:SetData("ydata", new.y); else NewPlot:SetData("xdata", Data.x,true); NewPlot:SetData("ydata", Data.y); end NewPlot:SetData("title", yLabel .. " vs " .. xLabel) NewPlot:Plot(yLabel.."vs"..xLabel..".png") end end elseif SweepMode == "Metropolis" then local SweepOptions = Options or {}; -- One full sweep per setting is default. local Sweeps = SweepOptions.Sweeps or self.Lattice.x*self.Lattice.y*self.Lattice.z; local k = self.k; for i = 1, #PList[index] do -- Set vars. for ParamName, Params in pairs(PList) do self.Lattice[ParamName] = Params[i]; end local rep = true; while rep do rep=false; -- Sweep over grain. for _, Grain in pairs(self.Lattice.Grains) do --print(self.Lattice:GetDeltaU(Grain)) if self.Lattice:GetDeltaU(Grain) < 0 then self.Lattice:FlipSpin(Grain); rep=true; end end end for Sweep = 1,Sweeps do -- Pick a random grain; local Grain = self.Lattice:GetRandomLatticeSite(); local dU = self.Lattice:GetDeltaU(Grain); -- print(dU, dU/(self.k*self.Lattice.Temperature), math.exp(-dU/(self.k*self.Lattice.Temperature))) if dU <= 0 then self.Lattice:FlipSpin(Grain) elseif math.exp(-dU/(self.k*self.Lattice.Temperature)) > math.random() then self.Lattice:FlipSpin(Grain) end end if ANIM then self.Lattice:Dump("tmp.lat") end -- print(self.Lattice.ExternalField) -- self.Lattice:Show() -- print(self.Lattice:GetM(), PList.ExternalField[i]) -- self.Lattice:Dump("tmp.lat") local Measure = self:Measure(self.Lattice); for ParamName, Data in pairs(PList) do if not DataOut[ParamName]then DataOut[ParamName] = {}; end local xValue = Data[i]; for index, yValue in pairs(Measure) do if not (DataOut[ParamName][index]) then DataOut[ParamName][index] = {x = {}, y = {}}; end table.insert(DataOut[ParamName][index].x, xValue); table.insert(DataOut[ParamName][index].y, yValue); end end end for xLabel, Contents in pairs(DataOut) do for yLabel, Data in pairs(Contents) do local NewPlot = Plotter:New(); NewPlot:Set("xlabel", xlabel) -- Create a new plot. NewPlot:Set("ylabel", ylabel); local Data = Data; if yLabel == "M" and xLabel == "ExternalField" then local new = {}; new.x = {}; new.y = {}; local min_x = mint(Data.x); local max_x = maxt(Data.x); for ind, val in pairs(Data.x) do table.insert(new.x, (val - min_x)/(max_x - min_x)); end local min_y = mint(Data.y); local max_y = maxt(Data.y); for ind, val in pairs(Data.y) do table.insert(new.y, (val - min_y)/(max_y - min_y)); end NewPlot:SetData("xdata", new.x,true); NewPlot:SetData("ydata", new.y); else NewPlot:SetData("xdata", Data.x,true); NewPlot:SetData("ydata", Data.y); end -- NewPlot:SetData("title", yLabel .. " vs " .. xLabel) NewPlot:Plot(yLabel.."vs"..xLabel..".png") end end if ANIM then self.Lattice:ToAnim("tmp.lat", "out.gif",4,5,1) end end end return Model
fixed anim metropolis
fixed anim metropolis
Lua
mit
jochem-brouwer/VO2_Model,jochem-brouwer/VO2_Model
7c1f97f2f414f1f0208244bb6de94dc2abdd09ec
test-server/test-server-ev.lua
test-server/test-server-ev.lua
#!/usr/bin/env lua --- lua websocket equivalent to test-server.c from libwebsockets. -- using lua-ev event loop package.path = package.path..';../src/?.lua' local ev = require'ev' local loop = ev.Loop.default local server = require'websocket'.server.ev.listen { protocols = { ['lws-mirror-protocol'] = function(ws) ws:on_message( function(ws,data) ws:broadcast(data) end) end, ['dumb-increment-protocol'] = function(ws) local number = 0 local timer = ev.Timer.new( function() ws:send(tostring(number)) number = number + 1 end,0.1,0.1) timer:start(loop) ws:on_message( function(ws,message) if message:match('reset') then number = 0 end end) ws:on_close( function() timer:stop(loop) end) end }, port = 12345 } print('Open browser:') print('file://'..io.popen('pwd'):read()..'/index.html') loop:loop()
#!/usr/bin/env lua --- lua websocket equivalent to test-server.c from libwebsockets. -- using lua-ev event loop package.path = '../src/?.lua;../src/?/?.lua;'..package.path local ev = require'ev' local loop = ev.Loop.default local server = require'websocket'.server.ev.listen { protocols = { ['lws-mirror-protocol'] = function(ws) ws:on_message( function(ws,data) ws:broadcast(data) end) end, ['dumb-increment-protocol'] = function(ws) local number = 0 local timer = ev.Timer.new( function() ws:send(tostring(number)) number = number + 1 end,0.1,0.1) timer:start(loop) ws:on_message( function(ws,message) if message:match('reset') then number = 0 end end) ws:on_close( function() timer:stop(loop) end) end }, port = 12345 } print('Open browser:') print('file://'..io.popen('pwd'):read()..'/index.html') loop:loop()
fix search path for local websocket module
fix search path for local websocket module
Lua
mit
enginix/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets
9be82da44951c5b0389592369be0dcca65527e1a
frontend/document/documentregistry.lua
frontend/document/documentregistry.lua
--[[-- This is a registry for document providers ]]-- local logger = require("logger") local lfs = require("libs/libkoreader-lfs") local util = require("util") local DocumentRegistry = { registry = {}, providers = {}, filetype_provider = {}, } function DocumentRegistry:addProvider(extension, mimetype, provider, weight) table.insert(self.providers, { extension = extension, mimetype = mimetype, provider = provider, weight = weight or 100, }) self.filetype_provider[extension] = true end function DocumentRegistry:getRandomFile(dir, opened, extension) local DocSettings = require("docsettings") if string.sub(dir, string.len(dir)) ~= "/" then dir = dir .. "/" end local files = {} local i = 0 local ok, iter, dir_obj = pcall(lfs.dir, dir) if ok then for entry in iter, dir_obj do if lfs.attributes(dir .. entry, "mode") == "file" and self:hasProvider(dir .. entry) and (opened == nil or DocSettings:hasSidecarFile(dir .. entry) == opened) and (extension == nil or extension[util.getFileNameSuffix(entry)]) then i = i + 1 files[i] = entry end end if i == 0 then return nil end else return nil end math.randomseed(os.time()) return dir .. files[math.random(i)] end --- Returns true if file has provider. -- @string file -- @treturn boolean function DocumentRegistry:hasProvider(file) local filename_suffix = util.getFileNameSuffix(file) if self.filetype_provider[filename_suffix] then return true end return false end --- Returns the preferred registered document handler. -- @string file -- @treturn table provider, or nil function DocumentRegistry:getProvider(file) local providers = self:getProviders(file) if providers then -- provider for document local DocSettings = require("docsettings") if DocSettings:hasSidecarFile(file) then local doc_settings_provider = DocSettings:open(file):readSetting("provider") if doc_settings_provider then for _, provider in ipairs(providers) do if provider.provider.provider == doc_settings_provider then return provider.provider end end end end -- global provider for filetype local filename_suffix = util.getFileNameSuffix(file) local g_settings_provider = G_reader_settings:readSetting("provider") if g_settings_provider and g_settings_provider[filename_suffix] then for _, provider in ipairs(providers) do if provider.provider.provider == g_settings_provider[filename_suffix] then return provider.provider end end end -- highest weighted provider return providers[1].provider end end --- Returns the registered document handlers. -- @string file -- @treturn table providers, or nil function DocumentRegistry:getProviders(file) local providers = {} -- TODO: some implementation based on mime types? for _, provider in ipairs(self.providers) do local suffix = string.sub(file, -string.len(provider.extension) - 1) if string.lower(suffix) == "."..provider.extension then -- if extension == provider.extension then -- stick highest weighted provider at the front if #providers >= 1 and provider.weight > providers[1].weight then table.insert(providers, 1, provider) else table.insert(providers, provider) end end end if #providers >= 1 then return providers end end --- Sets the preferred registered document handler. -- @string file -- @bool all function DocumentRegistry:setProvider(file, provider, all) local _, filename_suffix = util.splitFileNameSuffix(file) -- per-document if not all then local DocSettings = require("docsettings"):open(file) DocSettings:saveSetting("provider", provider.provider) DocSettings:flush() -- global else local filetype_provider = G_reader_settings:readSetting("provider") or {} filetype_provider[filename_suffix] = provider.provider G_reader_settings:saveSetting("provider", filetype_provider) end end function DocumentRegistry:openDocument(file, provider) -- force a GC, so that any previous document used memory can be reused -- immediately by this new document without having to wait for the -- next regular gc. The second call may help reclaming more memory. collectgarbage() collectgarbage() if not self.registry[file] then provider = provider or self:getProvider(file) if provider ~= nil then local ok, doc = pcall(provider.new, provider, {file = file}) if ok then self.registry[file] = { doc = doc, refs = 1, } else logger.warn("cannot open document", file, doc) end end else self.registry[file].refs = self.registry[file].refs + 1 end if self.registry[file] then return self.registry[file].doc end end function DocumentRegistry:closeDocument(file) if self.registry[file] then self.registry[file].refs = self.registry[file].refs - 1 if self.registry[file].refs == 0 then self.registry[file] = nil return 0 else return self.registry[file].refs end else error("Try to close unregistered file.") end end -- load implementations: require("document/credocument"):register(DocumentRegistry) require("document/pdfdocument"):register(DocumentRegistry) require("document/djvudocument"):register(DocumentRegistry) require("document/picdocument"):register(DocumentRegistry) return DocumentRegistry
--[[-- This is a registry for document providers ]]-- local logger = require("logger") local lfs = require("libs/libkoreader-lfs") local util = require("util") local DocumentRegistry = { registry = {}, providers = {}, filetype_provider = {}, } function DocumentRegistry:addProvider(extension, mimetype, provider, weight) extension = string.lower(extension) table.insert(self.providers, { extension = extension, mimetype = mimetype, provider = provider, weight = weight or 100, }) self.filetype_provider[extension] = true end function DocumentRegistry:getRandomFile(dir, opened, extension) local DocSettings = require("docsettings") if string.sub(dir, string.len(dir)) ~= "/" then dir = dir .. "/" end local files = {} local i = 0 local ok, iter, dir_obj = pcall(lfs.dir, dir) if ok then for entry in iter, dir_obj do if lfs.attributes(dir .. entry, "mode") == "file" and self:hasProvider(dir .. entry) and (opened == nil or DocSettings:hasSidecarFile(dir .. entry) == opened) and (extension == nil or extension[util.getFileNameSuffix(entry)]) then i = i + 1 files[i] = entry end end if i == 0 then return nil end else return nil end math.randomseed(os.time()) return dir .. files[math.random(i)] end --- Returns true if file has provider. -- @string file -- @treturn boolean function DocumentRegistry:hasProvider(file) local filename_suffix = string.lower(util.getFileNameSuffix(file)) if self.filetype_provider[filename_suffix] then return true end return false end --- Returns the preferred registered document handler. -- @string file -- @treturn table provider, or nil function DocumentRegistry:getProvider(file) local providers = self:getProviders(file) if providers then -- provider for document local DocSettings = require("docsettings") if DocSettings:hasSidecarFile(file) then local doc_settings_provider = DocSettings:open(file):readSetting("provider") if doc_settings_provider then for _, provider in ipairs(providers) do if provider.provider.provider == doc_settings_provider then return provider.provider end end end end -- global provider for filetype local filename_suffix = util.getFileNameSuffix(file) local g_settings_provider = G_reader_settings:readSetting("provider") if g_settings_provider and g_settings_provider[filename_suffix] then for _, provider in ipairs(providers) do if provider.provider.provider == g_settings_provider[filename_suffix] then return provider.provider end end end -- highest weighted provider return providers[1].provider end end --- Returns the registered document handlers. -- @string file -- @treturn table providers, or nil function DocumentRegistry:getProviders(file) local providers = {} -- TODO: some implementation based on mime types? for _, provider in ipairs(self.providers) do local suffix = string.sub(file, -string.len(provider.extension) - 1) if string.lower(suffix) == "."..provider.extension then -- if extension == provider.extension then -- stick highest weighted provider at the front if #providers >= 1 and provider.weight > providers[1].weight then table.insert(providers, 1, provider) else table.insert(providers, provider) end end end if #providers >= 1 then return providers end end --- Sets the preferred registered document handler. -- @string file -- @bool all function DocumentRegistry:setProvider(file, provider, all) local _, filename_suffix = util.splitFileNameSuffix(file) -- per-document if not all then local DocSettings = require("docsettings"):open(file) DocSettings:saveSetting("provider", provider.provider) DocSettings:flush() -- global else local filetype_provider = G_reader_settings:readSetting("provider") or {} filetype_provider[filename_suffix] = provider.provider G_reader_settings:saveSetting("provider", filetype_provider) end end function DocumentRegistry:openDocument(file, provider) -- force a GC, so that any previous document used memory can be reused -- immediately by this new document without having to wait for the -- next regular gc. The second call may help reclaming more memory. collectgarbage() collectgarbage() if not self.registry[file] then provider = provider or self:getProvider(file) if provider ~= nil then local ok, doc = pcall(provider.new, provider, {file = file}) if ok then self.registry[file] = { doc = doc, refs = 1, } else logger.warn("cannot open document", file, doc) end end else self.registry[file].refs = self.registry[file].refs + 1 end if self.registry[file] then return self.registry[file].doc end end function DocumentRegistry:closeDocument(file) if self.registry[file] then self.registry[file].refs = self.registry[file].refs - 1 if self.registry[file].refs == 0 then self.registry[file] = nil return 0 else return self.registry[file].refs end else error("Try to close unregistered file.") end end -- load implementations: require("document/credocument"):register(DocumentRegistry) require("document/pdfdocument"):register(DocumentRegistry) require("document/djvudocument"):register(DocumentRegistry) require("document/picdocument"):register(DocumentRegistry) return DocumentRegistry
Lower file suffix (#4369)
Lower file suffix (#4369)
Lua
agpl-3.0
koreader/koreader,koreader/koreader,mihailim/koreader,poire-z/koreader,NiLuJe/koreader,Frenzie/koreader,NiLuJe/koreader,Hzj-jie/koreader,Frenzie/koreader,houqp/koreader,pazos/koreader,mwoz123/koreader,Markismus/koreader,poire-z/koreader
2292a6fc2a4f0a92f20e2e223c9a7ab6acdd32fa
lib/onmt/Encoder.lua
lib/onmt/Encoder.lua
--[[ Encoder is a unidirectional Sequencer used for the source language. h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](lib+onmt+Sequencer). --]] local Encoder, parent = torch.class('onmt.Encoder', 'onmt.Sequencer') --[[ Construct an encoder layer. Parameters: * `input_network` - input module. * `rnn` - recurrent module. ]] function Encoder:__init(input_network, rnn) self.rnn = rnn self.inputNet = input_network self.inputNet.name = 'input_network' self.args = {} self.args.rnn_size = self.rnn.output_size self.args.num_effective_layers = self.rnn.num_effective_layers parent.__init(self, self:_buildModel()) self:resetPreallocation() end --[[ Return a new Encoder using the serialized data `pretrained`. ]] function Encoder.load(pretrained) local self = torch.factory('onmt.Encoder')() self.args = pretrained.args parent.__init(self, pretrained.modules[1]) self.network:apply(function (m) if m.name == 'input_network' then self.inputNet = m end end) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function Encoder:serialize() return { modules = self.modules, args = self.args } end function Encoder:resetPreallocation() -- Prototype for preallocated hidden and cell states. self.stateProto = torch.Tensor() -- Prototype for preallocated output gradients. self.gradOutputProto = torch.Tensor() -- Prototype for preallocated context vector. self.contextProto = torch.Tensor() end function Encoder:maskPadding() self.mask_padding = true end --[[ Build one time-step of an encoder Returns: An nn-graph mapping $${(c^1_{t-1}, h^1_{t-1}, .., c^L_{t-1}, h^L_{t-1}, x_t) => (c^1_{t}, h^1_{t}, .., c^L_{t}, h^L_{t})}$$ Where $$c^l$$ and $$h^l$$ are the hidden and cell states at each layer, $$x_t$$ is a sparse word to lookup. --]] function Encoder:_buildModel() local inputs = {} local states = {} -- Inputs are previous layers first. for _ = 1, self.args.num_effective_layers do local h0 = nn.Identity()() -- batch_size x rnn_size table.insert(inputs, h0) table.insert(states, h0) end -- Input word. local x = nn.Identity()() -- batch_size table.insert(inputs, x) -- Compute input network. local input = self.inputNet(x) table.insert(states, input) -- Forward states and input into the RNN. local outputs = self.rnn(states) return nn.gModule(inputs, { outputs }) end function Encoder:shareInput(other) self.inputNet:share(other.inputNet, 'weight', 'gradWeight') end --[[Compute the context representation of an input. Parameters: * `batch` - as defined in batch.lua. Returns: 1. - final hidden states 2. - context matrix H --]] function Encoder:forward(batch) -- TODO: Change `batch` to `input`. local final_states local output_size = self.args.rnn_size if self.statesProto == nil then self.statesProto = utils.Tensor.initTensorTable(self.args.num_effective_layers, self.stateProto, { batch.size, output_size }) end -- Make initial states h_0. local states = utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, output_size }) -- Preallocated output matrix. local context = utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.source_length, output_size }) if self.mask_padding and not batch.source_input_pad_left then final_states = utils.Tensor.recursiveClone(states) end if self.train then self.inputs = {} end -- Act like nn.Sequential and call each clone in a feed-forward -- fashion. for t = 1, batch.source_length do -- Construct "inputs". Prev states come first then source. local inputs = {} utils.Table.append(inputs, states) table.insert(inputs, batch:get_source_input(t)) if self.train then -- Remember inputs for the backward pass. self.inputs[t] = inputs end states = self:net(t):forward(inputs) -- Special case padding. if self.mask_padding then for b = 1, batch.size do if batch.source_input_pad_left and t <= batch.source_length - batch.source_size[b] then for j = 1, #states do states[j][b]:zero() end elseif not batch.source_input_pad_left and t == batch.source_size[b] then for j = 1, #states do final_states[j][b]:copy(states[j][b]) end end end end -- Copy output (h^L_t = states[#states]) to context. context[{{}, t}]:copy(states[#states]) end if final_states == nil then final_states = states end return final_states, context end --[[ Backward pass (only called during training) Parameters: * `batch` - must be same as for forward * `grad_states_output` gradient of loss wrt last state * `grad_context_output` - gradient of loss wrt full context. Returns: nil --]] function Encoder:backward(batch, grad_states_output, grad_context_output) -- TODO: change this to (input, gradOutput) as in nngraph. local output_size = self.args.rnn_size if self.gradOutputsProto == nil then self.gradOutputsProto = utils.Tensor.initTensorTable(self.args.num_effective_layers, self.gradOutputProto, { batch.size, output_size }) end local grad_states_input = utils.Tensor.copyTensorTable(self.gradOutputsProto, grad_states_output) local gradInput = {} for t = batch.source_length, 1, -1 do -- Add context gradients to last hidden states gradients. grad_states_input[#grad_states_input]:add(grad_context_output[{{}, t}]) local grad_input = self:net(t):backward(self.inputs[t], grad_states_input) -- Prepare next encoder output gradients. for i = 1, #grad_states_input do grad_states_input[i]:copy(grad_input[i]) end gradInput[t] = grad_states_input[#grad_states_input]:clone() end -- TODO: make these names clearer. -- Useful if input came from another network. return gradInput end
--[[ Encoder is a unidirectional Sequencer used for the source language. h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](lib+onmt+Sequencer). --]] local Encoder, parent = torch.class('onmt.Encoder', 'onmt.Sequencer') --[[ Construct an encoder layer. Parameters: * `input_network` - input module. * `rnn` - recurrent module. ]] function Encoder:__init(input_network, rnn) self.rnn = rnn self.inputNet = input_network self.inputNet.name = 'input_network' self.args = {} self.args.rnn_size = self.rnn.output_size self.args.num_effective_layers = self.rnn.num_effective_layers parent.__init(self, self:_buildModel()) self:resetPreallocation() end --[[ Return a new Encoder using the serialized data `pretrained`. ]] function Encoder.load(pretrained) local self = torch.factory('onmt.Encoder')() self.args = pretrained.args parent.__init(self, pretrained.modules[1]) self.network:apply(function (m) if m.name == 'input_network' then self.inputNet = m end end) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function Encoder:serialize() return { modules = self.modules, args = self.args } end function Encoder:resetPreallocation() -- Prototype for preallocated hidden and cell states. self.stateProto = torch.Tensor() -- Prototype for preallocated output gradients. self.gradOutputProto = torch.Tensor() -- Prototype for preallocated context vector. self.contextProto = torch.Tensor() end function Encoder:maskPadding() self.mask_padding = true end --[[ Build one time-step of an encoder Returns: An nn-graph mapping $${(c^1_{t-1}, h^1_{t-1}, .., c^L_{t-1}, h^L_{t-1}, x_t) => (c^1_{t}, h^1_{t}, .., c^L_{t}, h^L_{t})}$$ Where $$c^l$$ and $$h^l$$ are the hidden and cell states at each layer, $$x_t$$ is a sparse word to lookup. --]] function Encoder:_buildModel() local inputs = {} local states = {} -- Inputs are previous layers first. for _ = 1, self.args.num_effective_layers do local h0 = nn.Identity()() -- batch_size x rnn_size table.insert(inputs, h0) table.insert(states, h0) end -- Input word. local x = nn.Identity()() -- batch_size table.insert(inputs, x) -- Compute input network. local input = self.inputNet(x) table.insert(states, input) -- Forward states and input into the RNN. local outputs = self.rnn(states) return nn.gModule(inputs, { outputs }) end function Encoder:shareInput(other) self.inputNet:share(other.inputNet, 'weight', 'gradWeight') end --[[Compute the context representation of an input. Parameters: * `batch` - as defined in batch.lua. Returns: 1. - final hidden states 2. - context matrix H --]] function Encoder:forward(batch) -- TODO: Change `batch` to `input`. local final_states local output_size = self.args.rnn_size if self.statesProto == nil then self.statesProto = utils.Tensor.initTensorTable(self.args.num_effective_layers, self.stateProto, { batch.size, output_size }) end -- Make initial states h_0. local states = utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, output_size }) -- Preallocated output matrix. local context = utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.source_length, output_size }) if self.mask_padding and not batch.source_input_pad_left then final_states = utils.Tensor.recursiveClone(states) end if self.train then self.inputs = {} end -- Act like nn.Sequential and call each clone in a feed-forward -- fashion. for t = 1, batch.source_length do -- Construct "inputs". Prev states come first then source. local inputs = {} utils.Table.append(inputs, states) table.insert(inputs, batch:get_source_input(t)) if self.train then -- Remember inputs for the backward pass. self.inputs[t] = inputs end states = self:net(t):forward(inputs) -- Special case padding. if self.mask_padding then for b = 1, batch.size do if batch.source_input_pad_left and t <= batch.source_length - batch.source_size[b] then for j = 1, #states do states[j][b]:zero() end elseif not batch.source_input_pad_left and t == batch.source_size[b] then for j = 1, #states do final_states[j][b]:copy(states[j][b]) end end end end -- Copy output (h^L_t = states[#states]) to context. context[{{}, t}]:copy(states[#states]) end if final_states == nil then final_states = states end return final_states, context end --[[ Backward pass (only called during training) Parameters: * `batch` - must be same as for forward * `grad_states_output` gradient of loss wrt last state * `grad_context_output` - gradient of loss wrt full context. Returns: nil --]] function Encoder:backward(batch, grad_states_output, grad_context_output) -- TODO: change this to (input, gradOutput) as in nngraph. local output_size = self.args.rnn_size if self.gradOutputsProto == nil then self.gradOutputsProto = utils.Tensor.initTensorTable(self.args.num_effective_layers, self.gradOutputProto, { batch.size, output_size }) end local grad_states_input = utils.Tensor.copyTensorTable(self.gradOutputsProto, grad_states_output) local gradInput = {} for t = batch.source_length, 1, -1 do -- Add context gradients to last hidden states gradients. grad_states_input[#grad_states_input]:add(grad_context_output[{{}, t}]) local grad_input = self:net(t):backward(self.inputs[t], grad_states_input) -- Prepare next encoder output gradients. for i = 1, #grad_states_input do grad_states_input[i]:copy(grad_input[i]) end -- Gather gradients of all user inputs. gradInput[t] = {} for i = #grad_states_input + 1, #grad_input do table.insert(gradInput[t], grad_input[i]) end if #gradInput[t] == 1 then gradInput[t] = gradInput[t][1] end end -- TODO: make these names clearer. -- Useful if input came from another network. return gradInput end
fix encoder input gradients
fix encoder input gradients Previously, the gradients of the last hidden states were returned instead of the gradients of the user inputs. Also discard the `clone()` which should ideally be avoided.
Lua
mit
da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,cservan/OpenNMT_scores_0.2.0,jungikim/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,srush/OpenNMT,jsenellart-systran/OpenNMT
4cd1cb61faf648f1e4653481b1e4895339c63471
src/lgix/GObject-Value.lua
src/lgix/GObject-Value.lua
------------------------------------------------------------------------------ -- -- LGI GObject.Value support. -- -- Copyright (c) 2010, 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local assert, pairs = assert, pairs local lgi = require 'lgi' local core = require 'lgi.core' local repo = core.repo local gi = core.gi local Type = repo.GObject.Type -- Value is constructible from any kind of source Lua value, and the -- type of the value can be hinted by type name. local Value = repo.GObject.Value local value_info = gi.GObject.Value local log = lgi.log.domain('Lgi') -- Workaround for incorrect annotations - g_value_set_xxx are missing -- (allow-none) annotations in glib < 2.30. for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do if not value_info.methods[name].args[1].optional then log.message("g_value_%s() is missing (allow-none)", name) local setter = Value[name] Value._method[name] = function(value, val) if not val then Value.reset(value) else setter(value, val) end end end end -- Do not allow direct access to fields. local value_field_gtype = Value._field.g_type Value._field = nil -- 'type' property controls gtype of the property. Value._attribute = { gtype = {} } function Value._attribute.gtype.get(value) return core.record.field(value, value_field_gtype) end function Value._attribute.gtype.set(value, newtype) local gtype = core.record.field(value, value_field_gtype) if gtype then if newtype then -- Try converting old value to new one. local dest = core.record.new(value_info) Value.init(dest, newtype) if not Value.transform(value, dest) then error(("GObject.Value: cannot convert `%s' to `%s'"):format( gtype, core.record.field(dest, value_field_gtype))) end Value.unset(value) Value.init(value, newtype) Value.copy(dest, value) else Value.unset(value) end elseif newtype then -- No value was set and some is requested, so set it. Value.init(value, newtype) end end local value_marshallers = {} for name, gtype in pairs(Type) do local get = Value._method['get_' .. name:lower()] local set = Value._method['set_' .. name:lower()] if get and set then value_marshallers[gtype] = function(value, params, ...) return (select('#', ...) > 0 and set or get)(value, ...) end end end -- Interface marshaller is the same as object marshallers. value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT] -- Override 'boxed' marshaller, default one marshalls to gpointer -- instead of target boxed type. value_marshallers[Type.BOXED] = function(value, params, ...) local gtype = core.record.field(value, value_field_gtype) if select('#', ...) > 0 then Value.set_boxed(value, core.record.query((...), 'addr', gtype)) else return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value)) end end -- Create GStrv marshaller, implement it using typeinfo marshaller -- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from -- g_shell_parse_argv(). value_marshallers[Type.STRV] = core.marshal.container( gi.GLib.shell_parse_argv.args[3].typeinfo) -- Workaround for GoI < 1.30; it does not know that GLib structs are -- boxed, so it does not assign them GType; moreover it incorrectly -- considers GParamSpec as GType-less struct instead of the class. local function marshal_record_no_gtype(value, params, ...) -- Check actual gtype of the real value. local gtype = core.record.field(value, value_field_gtype) if Type.is_a(gtype, Type.PARAM) then return value_marshallers[Type.PARAM](value, ...) end -- Find out proper getter/setter method for the value. local get, set if Type.is_a(gtype, Type.BOXED) then get, set = Value.get_boxed, Value.set_boxed else get, set = Value.get_pointer, Value.set_pointer end -- Do GValue<->record transfer. local record_info = typeinfo.interface if select('#', ...) > 0 then set(value, core.record.query((...), 'addr', record_info)) else return core.record.new(record_info, get(value)) end end -- Finds marshaller closure which can marshal type described either by -- gtype or typeinfo/transfer combo. function Value._method.find_marshaller(gtype, typeinfo, transfer) -- Check whether we can have marshaller for typeinfo, if the -- typeinfo is container. local marshaller if typeinfo then marshaller = core.marshal.container(typeinfo, transfer) if marshaller then return marshaller end end -- Special case for non-gtype records. if not gtype and typeinfo and typeinfo.tag == 'interface' then return marshal_record_no_gtype end local gt = gtype if type(gt) == 'number' then gt = Type.name(gt) end -- Special marshaller, allowing only 'nil'. if not gt then return function() end end -- Find marshaller according to gtype of the value. while gt do -- Check simple and/or fundamental marshallers. marshaller = value_marshallers[gt] or core.marshal.fundamental(gt) if marshaller then return marshaller end gt = Type.parent(gt) end error(("GValue marshaller for `%s' not found"):format(tostring(gtype))) end -- Value 'value' property provides access to GValue's embedded data. function Value._attribute:value(...) local marshaller = Value._method.find_marshaller( core.record.field(self, value_field_gtype)) return marshaller(self, nil, ...) end -- Implement custom 'constructor', taking optionally two values (type -- and value). The reason why it is overriden is that the order of -- initialization is important, and standard record intializer cannot -- enforce the order. function Value:_new(gtype, value) local v = core.record.new(value_info) if gtype then v.gtype = gtype end if value then v.value = value end return v end
------------------------------------------------------------------------------ -- -- LGI GObject.Value support. -- -- Copyright (c) 2010, 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local assert, pairs = assert, pairs local lgi = require 'lgi' local core = require 'lgi.core' local repo = core.repo local gi = core.gi local Type = repo.GObject.Type -- Value is constructible from any kind of source Lua value, and the -- type of the value can be hinted by type name. local Value = repo.GObject.Value local value_info = gi.GObject.Value local log = lgi.log.domain('Lgi') -- Workaround for incorrect annotations - g_value_set_xxx are missing -- (allow-none) annotations in glib < 2.30. for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do if not value_info.methods[name].args[1].optional then log.message("g_value_%s() is missing (allow-none)", name) local setter = Value[name] Value._method[name] = function(value, val) if not val then Value.reset(value) else setter(value, val) end end end end -- Do not allow direct access to fields. local value_field_gtype = Value._field.g_type Value._field = nil -- 'type' property controls gtype of the property. Value._attribute = { gtype = {} } function Value._attribute.gtype.get(value) return core.record.field(value, value_field_gtype) end function Value._attribute.gtype.set(value, newtype) local gtype = core.record.field(value, value_field_gtype) if gtype then if newtype then -- Try converting old value to new one. local dest = core.record.new(value_info) Value.init(dest, newtype) if not Value.transform(value, dest) then error(("GObject.Value: cannot convert `%s' to `%s'"):format( gtype, core.record.field(dest, value_field_gtype))) end Value.unset(value) Value.init(value, newtype) Value.copy(dest, value) else Value.unset(value) end elseif newtype then -- No value was set and some is requested, so set it. Value.init(value, newtype) end end local value_marshallers = {} for name, gtype in pairs(Type) do local get = Value._method['get_' .. name:lower()] local set = Value._method['set_' .. name:lower()] if get and set then value_marshallers[gtype] = function(value, params, ...) return (select('#', ...) > 0 and set or get)(value, ...) end end end -- Interface marshaller is the same as object marshallers. value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT] -- Override 'boxed' marshaller, default one marshalls to gpointer -- instead of target boxed type. value_marshallers[Type.BOXED] = function(value, params, ...) local gtype = core.record.field(value, value_field_gtype) if select('#', ...) > 0 then Value.set_boxed(value, core.record.query((...), 'addr', gtype)) else return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value)) end end -- Create GStrv marshaller, implement it using typeinfo marshaller -- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from -- g_shell_parse_argv(). value_marshallers[Type.STRV] = core.marshal.container( gi.GLib.shell_parse_argv.args[3].typeinfo) -- Finds marshaller closure which can marshal type described either by -- gtype or typeinfo/transfer combo. function Value._method.find_marshaller(gtype, typeinfo, transfer) -- Check whether we can have marshaller for typeinfo, if the -- typeinfo is container. local marshaller if typeinfo then marshaller = core.marshal.container(typeinfo, transfer) if marshaller then return marshaller end end -- Special case for non-gtype records. if not gtype and typeinfo and typeinfo.tag == 'interface' then -- Workaround for GoI < 1.30; it does not know that GLib structs are -- boxed, so it does not assign them GType; moreover it incorrectly -- considers GParamSpec as GType-less struct instead of the class. local function marshal_record_no_gtype(value, params, ...) -- Check actual gtype of the real value. local gtype = core.record.field(value, value_field_gtype) if Type.is_a(gtype, Type.PARAM) then return value_marshallers[Type.PARAM](value, ...) end -- Find out proper getter/setter method for the value. local get, set if Type.is_a(gtype, Type.BOXED) then get, set = Value.get_boxed, Value.set_boxed else get, set = Value.get_pointer, Value.set_pointer end -- Do GValue<->record transfer. local record_info = typeinfo.interface if select('#', ...) > 0 then set(value, core.record.query((...), 'addr', record_info)) else return core.record.new(record_info, get(value)) end end return marshal_record_no_gtype end local gt = gtype if type(gt) == 'number' then gt = Type.name(gt) end -- Special marshaller, allowing only 'nil'. if not gt then return function() end end -- Find marshaller according to gtype of the value. while gt do -- Check simple and/or fundamental marshallers. marshaller = value_marshallers[gt] or core.marshal.fundamental(gt) if marshaller then return marshaller end gt = Type.parent(gt) end error(("GValue marshaller for `%s' not found"):format(tostring(gtype))) end -- Value 'value' property provides access to GValue's embedded data. function Value._attribute:value(...) local marshaller = Value._method.find_marshaller( core.record.field(self, value_field_gtype)) return marshaller(self, nil, ...) end -- Implement custom 'constructor', taking optionally two values (type -- and value). The reason why it is overriden is that the order of -- initialization is important, and standard record intializer cannot -- enforce the order. function Value:_new(gtype, value) local v = core.record.new(value_info) if gtype then v.gtype = gtype end if value then v.value = value end return v end
Fix workaround for boxed GLib structs in older GI
Fix workaround for boxed GLib structs in older GI
Lua
mit
zevv/lgi,psychon/lgi,pavouk/lgi