repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
dmccuskey/dmc-wamp
examples/dmc-wamp-publish/dmc_corona/lib/dmc_lua/json.lua
49
2030
--====================================================================-- -- dmc_lua/json.lua -- -- consistent method which which to load json on various systems -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library: JSON Shim --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.2.0" --====================================================================-- --== Setup, Constants -- these are some popular json modules local JSON_LIBS = { 'dkjson', 'cjson', 'json' } local has_json, json for _, name in ipairs( JSON_LIBS ) do has_json, json = pcall( require, name ) if has_json then break end end assert( has_json, "json module not found" ) return json
mit
dmccuskey/dmc-wamp
examples/dmc-wamp-rpc-callee/dmc_corona/lib/dmc_lua/json.lua
49
2030
--====================================================================-- -- dmc_lua/json.lua -- -- consistent method which which to load json on various systems -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library: JSON Shim --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.2.0" --====================================================================-- --== Setup, Constants -- these are some popular json modules local JSON_LIBS = { 'dkjson', 'cjson', 'json' } local has_json, json for _, name in ipairs( JSON_LIBS ) do has_json, json = pcall( require, name ) if has_json then break end end assert( has_json, "json module not found" ) return json
mit
moltafet35/ssssis
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
mc-server/Coiny
coiny_functions.lua
2
3779
-- coiny_functions.lua -- Implements various helper functions function SaveSettings() local ini = cIniFile() ini:ReadFile(cPluginManager:GetCurrentPlugin():GetLocalFolder() .. "/coiny_settings.ini") ini:SetValueI("Settings", "StarterPack", StarterPack, false) ini:SetValueB("Settings", "AdvancedMessages", AdvancedMessages, false) if (AdvancedMessages) then ini:SetValue("AMNegative", "Prefix", AdvancedMessagesData["NegativePrefix"], false) ini:SetValue("AMNegative", "Postfix", AdvancedMessagesData["NegativePostfix"], false) ini:SetValue("AMZero", "MinusOneCoinText", AdvancedMessagesData["MinusOneCoin"], false) ini:SetValue("AMZero", "ZeroCoinsText", AdvancedMessagesData["ZeroCoins"], false) ini:SetValue("AMZero", "OneCoinText", AdvancedMessagesData["OneCoin"], false) ini:SetValueI("AMLow", "Value", AdvancedMessagesData["LowValue"], false) ini:SetValue ("AMLow", "Prefix", AdvancedMessagesData["LowPrefix"], false) ini:SetValue ("AMLow", "Postfix", AdvancedMessagesData["LowPostfix"], false) ini:SetValueI("AMMedium", "Value", AdvancedMessagesData["MediumValue"], false) ini:SetValue ("AMMedium", "Prefix", AdvancedMessagesData["MediumPrefix"], false) ini:SetValue ("AMMedium", "Postfix", AdvancedMessagesData["MediumPostfix"], false) ini:SetValue("AMHigh", "Prefix", AdvancedMessagesData["HighPrefix"], false) ini:SetValue("AMHigh", "Postfix", AdvancedMessagesData["HighPostfix"], false) end ini:DeleteKey("Messages") for k, v in pairs(Messages) do ini:SetValue("Messages", k, v) end ini:WriteFile(cPluginManager:GetCurrentPlugin():GetLocalFolder() .. "/coiny_settings.ini") end function LoadSettings() local ini = cIniFile() ini:ReadFile(cPluginManager:GetCurrentPlugin():GetLocalFolder().. "/coiny_settings.ini") StarterPack = ini:GetValueSetI("Settings", "StarterPack", 200) AdvancedMessages = ini:GetValueSetB("Settings", "AdvancedMessages", true) if (AdvancedMessages) then AdvancedMessagesData["NegativePrefix"] = ini:GetValueSet("AMNegative", "Prefix", "You owe ") AdvancedMessagesData["NegativePostfix"] = ini:GetValueSet("AMNegative", "Postfix", " coins. Sorry :(") AdvancedMessagesData["MinusOneCoin"] = ini:GetValueSet("AMZero", "MinusOneCoinText", "You owe 1 coin") AdvancedMessagesData["ZeroCoins"] = ini:GetValueSet("AMZero", "ZeroCoinsText", "You're out of coins, mate!") AdvancedMessagesData["OneCoin"] = ini:GetValueSet("AMZero", "OneCoinText", "You only have 1 coin") AdvancedMessagesData["LowValue"] = ini:GetValueSetI("AMLow", "Value", 100) AdvancedMessagesData["LowPrefix"] = ini:GetValueSet ("AMLow", "Prefix", "Your pocket is ") AdvancedMessagesData["LowPostfix"] = ini:GetValueSet ("AMLow", "Postfix", " coins heavy") AdvancedMessagesData["MediumValue"] = ini:GetValueSetI("AMMedium", "Value", 1000) AdvancedMessagesData["MediumPrefix"] = ini:GetValueSet ("AMMedium", "Prefix", "You possess ") AdvancedMessagesData["MediumPostfix"] = ini:GetValueSet ("AMMedium", "Postfix", " coins") AdvancedMessagesData["HighPrefix"] = ini:GetValueSet("AMHigh", "Prefix", "Your bank account has ") AdvancedMessagesData["HighPostfix"] = ini:GetValueSet("AMHigh", "Postfix", " coins!") end local values = ini:GetNumValues("Messages") for index = 0, (values - 1), 1 do local valueName = ini:GetValueName("Messages", index) Messages[valueName] = ini:GetValue("Messages", valueName) end ini:WriteFile(cPluginManager:GetCurrentPlugin():GetLocalFolder() .. "/coiny_settings.ini") end function FormatMessage(inKey, inPlayerName, inAmount) return Messages[inKey .. "Prefix"] .. inAmount .. Messages[inKey .. "Middle"] .. inPlayerName .. Messages[inKey .. "Postfix"] end
unlicense
c4augustus/Urho3D
bin/Data/LuaScripts/33_Urho2DSpriterAnimation.lua
24
7416
-- Urho2D sprite example. -- This sample demonstrates: -- - Creating a 2D scene with spriter animation -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard to move and zoom 2D camera require "LuaScripts/Utilities/Sample" local spriterNode = nil local spriterAnimationIndex = 0 function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 0.0, -10.0) local camera = cameraNode:CreateComponent("Camera") camera.orthographic = true camera.orthoSize = graphics.height * PIXEL_SIZE camera.zoom = 1.5 * Min(graphics.width / 1280, graphics.height / 800) -- Set zoom according to user's resolution to ensure full visibility (initial zoom (1.5) is set for full visibility at 1280x800 resolution) local spriterAnimationSet = cache:GetResource("AnimationSet2D", "Urho2D/imp/imp.scml") if spriterAnimationSet == nil then return end spriterNode = scene_:CreateChild("SpriterAnimation") local spriterAnimatedSprite = spriterNode:CreateComponent("AnimatedSprite2D") spriterAnimatedSprite.animationSet = spriterAnimationSet spriterAnimatedSprite:SetAnimation(spriterAnimationSet:GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Mouse click to play next animation, \nUse WASD keys and mouse to move, Use PageUp PageDown to zoom.") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) instructionText.textAlignment = HA_CENTER -- Center rows in relation to each other -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 4.0 -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 1.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, -1.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_PAGEUP) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 1.01 end if input:GetKeyDown(KEY_PAGEDOWN) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 0.99 end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown") -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample UnsubscribeFromEvent("SceneUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandleMouseButtonDown(eventType, eventData) local spriterAnimatedSprite = spriterNode:GetComponent("AnimatedSprite2D") local spriterAnimationSet = spriterAnimatedSprite.animationSet spriterAnimationIndex = (spriterAnimationIndex + 1) % spriterAnimationSet.numAnimations spriterAnimatedSprite:SetAnimation(spriterAnimationSet:GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED) end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"PAGEUP\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
telespeed/telespeed
plugins/ingroup.lua
1
31502
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Grouop is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- @'..v..' [' ..k.. '] \n' end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(msg.to.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^[!/](add)$", "^[!/](rem)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](demote) (.*)$", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
stephank/luci
modules/rpc/luasrc/jsonrpcbind/uci.lua
81
1914
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() local ucis = require "luci.model.uci".cursor_state() local table = require "table" module "luci.jsonrpcbind.uci" _M, _PACKAGE, _NAME = nil, nil, nil function add(config, ...) uci:load(config) local stat = uci:add(config, ...) return uci:save(config) and stat end function apply(config) return uci:apply(config) end function changes(...) return uci:changes(...) end function commit(config) return uci:load(config) and uci:commit(config) end function delete(config, ...) uci:load(config) return uci:delete(config, ...) and uci:save(config) end function delete_all(config, ...) uci:load(config) return uci:delete_all(config, ...) and uci:save(config) end function foreach(config, stype) uci:load(config) local sections = {} return uci:foreach(config, stype, function(section) table.insert(sections, section) end) and sections end function get(config, ...) uci:load(config) return uci:get(config, ...) end function get_all(config, ...) uci:load(config) return uci:get_all(config, ...) end function get_state(config, ...) ucis:load(config) return ucis:get(config, ...) end function revert(config) return uci:load(config) and uci:revert(config) end function section(config, ...) uci:load(config) return uci:section(config, ...) and uci:save(config) end function set(config, ...) uci:load(config) return uci:set(config, ...) and uci:save(config) end function tset(config, ...) uci:load(config) return uci:tset(config, ...) and uci:save(config) end
apache-2.0
dxmgame/dxm-cocos-demo
src/lua-fantasy-warrior-3d/src/custom/api/EffectNormalMapped.lua
9
1036
-------------------------------- -- @module EffectNormalMapped -- @extend Effect -- @parent_module cc -------------------------------- -- -- @function [parent=#EffectNormalMapped] setKBump -- @param self -- @param #float value -- @return EffectNormalMapped#EffectNormalMapped self (return value: cc.EffectNormalMapped) -------------------------------- -- -- @function [parent=#EffectNormalMapped] setPointLight -- @param self -- @param #point_table pointLight -- @return EffectNormalMapped#EffectNormalMapped self (return value: cc.EffectNormalMapped) -------------------------------- -- -- @function [parent=#EffectNormalMapped] getKBump -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @overload self, string -- @overload self -- @function [parent=#EffectNormalMapped] create -- @param self -- @param #string normalMapFileName -- @return EffectNormalMapped#EffectNormalMapped ret (return value: cc.EffectNormalMapped) return nil
mit
Alexx-G/openface
training/attic/test-hardNeg.lua
8
6898
-- Copyright 2015-2016 Carnegie Mellon University -- -- 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. testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) local batchNumber local triplet_loss local timer = torch.Timer() function test() print('==> doing epoch on validation data:') print("==> online epoch # " .. epoch) batchNumber = 0 cutorch.synchronize() timer:reset() model:evaluate() model:cuda() triplet_loss = 0 local i = 1 while batchNumber < opt.epochSize do donkeys:addjob( function() local inputs, numPerClass = trainLoader:samplePeople(opt.peoplePerBatch, opt.imagesPerPerson) inputs = inputs:float() numPerClass = numPerClass:float() return sendTensor(inputs), sendTensor(numPerClass) end, testBatch ) if i % 5 == 0 then donkeys:synchronize() collectgarbage() end i = i + 1 end donkeys:synchronize() cutorch.synchronize() triplet_loss = triplet_loss / opt.testEpochSize testLogger:add{ ['avg triplet loss (test set)'] = triplet_loss } print(string.format('Epoch: [%d][TESTING SUMMARY] Total Time(s): %.2f \t' .. 'average triplet loss (per batch): %.2f', epoch, timer:time().real, triplet_loss)) print('\n') end local inputsCPU = torch.FloatTensor() local numPerClass = torch.FloatTensor() function testBatch(inputsThread, numPerClassThread) if batchNumber >= opt.epochSize then return end cutorch.synchronize() timer:reset() receiveTensor(inputsThread, inputsCPU) receiveTensor(numPerClassThread, numPerClass) -- inputs:resize(inputsCPU:size()):copy(inputsCPU) local numImages = inputsCPU:size(1) local embeddings = torch.Tensor(numImages, 128) local singleNet = model.modules[1] local beginIdx = 1 local inputs = torch.CudaTensor() while beginIdx <= numImages do local endIdx = math.min(beginIdx+opt.testBatchSize-1, numImages) local range = {{beginIdx,endIdx}} local sz = inputsCPU[range]:size() inputs:resize(sz):copy(inputsCPU[range]) local reps = singleNet:forward(inputs):float() embeddings[range] = reps beginIdx = endIdx + 1 end assert(beginIdx - 1 == numImages) local numTrips = numImages - opt.peoplePerBatch local as = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ps = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ns = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) function dist(emb1, emb2) local d = emb1 - emb2 return d:cmul(d):sum() end local tripIdx = 1 local shuffle = torch.randperm(numTrips) local embStartIdx = 1 local nRandomNegs = 0 for i = 1,opt.peoplePerBatch do local n = numPerClass[i] for j = 1,n-1 do local aIdx = embStartIdx local pIdx = embStartIdx+j as[shuffle[tripIdx]] = inputsCPU[aIdx] ps[shuffle[tripIdx]] = inputsCPU[pIdx] -- Select a semi-hard negative that has a distance -- further away from the positive exemplar. local posDist = dist(embeddings[aIdx], embeddings[pIdx]) local selNegIdx = embStartIdx while selNegIdx >= embStartIdx and selNegIdx <= embStartIdx+n-1 do selNegIdx = (torch.random() % numImages) + 1 end local selNegDist = dist(embeddings[aIdx], embeddings[selNegIdx]) local randomNeg = true for k = 1,numImages do if k < embStartIdx or k > embStartIdx+n-1 then local negDist = dist(embeddings[aIdx], embeddings[k]) if posDist < negDist and negDist < selNegDist and math.abs(posDist-negDist) < alpha then randomNeg = false selNegDist = negDist selNegIdx = k end end end if randomNeg then nRandomNegs = nRandomNegs + 1 end ns[shuffle[tripIdx]] = inputsCPU[selNegIdx] tripIdx = tripIdx + 1 end embStartIdx = embStartIdx + n end assert(embStartIdx - 1 == numImages) assert(tripIdx - 1 == numTrips) print((' + (nRandomNegs, nTrips) = (%d, %d)'):format(nRandomNegs, numTrips)) beginIdx = 1 local asCuda = torch.CudaTensor() local psCuda = torch.CudaTensor() local nsCuda = torch.CudaTensor() -- Return early if the loss is 0 for `numZeros` iterations. local numZeros = 4 local zeroCounts = torch.IntTensor(numZeros):zero() local zeroIdx = 1 -- Return early if the loss shrinks too much. -- local firstLoss = nil -- TODO: Should be <=, but batches with just one image cause errors. while beginIdx < numTrips do local endIdx = math.min(beginIdx+opt.testBatchSize, numTrips) local range = {{beginIdx,endIdx}} local sz = as[range]:size() asCuda:resize(sz):copy(as[range]) psCuda:resize(sz):copy(ps[range]) nsCuda:resize(sz):copy(ns[range]) local output = model:forward({asCuda, psCuda, nsCuda}) local err = criterion:forward(output) cutorch.synchronize() batchNumber = batchNumber + 1 print(string.format('Epoch: [%d][%d/%d] Triplet Loss: %.2f', epoch, batchNumber, opt.testEpochSize, err)) timer:reset() triplet_loss = triplet_loss + err -- Return early if the epoch is over. if batchNumber >= opt.epochSize then return end -- Return early if the loss is 0 for `numZeros` iterations. zeroCounts[zeroIdx] = (err == 0.0) and 1 or 0 -- Boolean to int. zeroIdx = (zeroIdx % numZeros) + 1 if zeroCounts:sum() == numZeros then return end -- Return early if the loss shrinks too much. -- if firstLoss == nil then -- firstLoss = err -- else -- -- Triplets trivially satisfied if err=0 -- if err ~= 0 and firstLoss/err > 4 then -- return -- end -- end beginIdx = endIdx + 1 end assert(beginIdx - 1 == numTrips or beginIdx == numTrips) end
apache-2.0
ondravondra/vlc
share/lua/meta/reader/filename.lua
17
1684
--[[ Gets an artwork for french TV channels $Id$ Copyright © 2007 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. --]] function descriptor() return { scope="local" } end function trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end function read_meta() local metas = vlc.item:metas() -- Don't do anything if there is already a title if metas["title"] then return end local name = metas["filename"]; if not name then return end -- Find "Show.Name.S01E12-blah.avi" local title, seasonNumber _, _, showName, seasonNumber, episodeNumber = string.find(name, "(.+)S(%d%d)E(%d%d).*") if not showName then return end -- Remove . in showName showName = trim(string.gsub(showName, "%.", " ")) vlc.item:set_meta("title", showName.." S"..seasonNumber.."E"..episodeNumber) vlc.item:set_meta("showName", showName) vlc.item:set_meta("episodeNumber", episodeNumber) vlc.item:set_meta("seasonNumber", seasonNumber) end
gpl-2.0
UnluckyNinja/PathOfBuilding
Data/3_0/Spectres.lua
1
34826
-- This file is automatically generated, do not edit! -- Path of Building -- -- Spectre Data -- Monster data (c) Grinding Gear Games -- local minions, mod = ... -- Blackguard minions["Metadata/Monsters/Axis/AxisCaster"] = { name = "Blackguard Mage", life = 0.9, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.305, attackRange = 40, weaponType1 = "Wand", weaponType2 = "Shield", skillList = { "Melee", "SkeletonSpark", "MonsterLightningThorns", "AxisClaimSoldierMinions", }, modList = { -- MonsterCastsSparkText -- MonsterCastsLightningThornsText }, } minions["Metadata/Monsters/Axis/AxisCasterArc"] = { name = "Blackguard Arcmage", life = 0.9, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.305, attackRange = 40, weaponType1 = "Wand", weaponType2 = "Shield", skillList = { "Melee", "MonsterLightningThorns", "MonsterArc", "AxisClaimSoldierMinions", }, modList = { -- MonsterCastsArcText -- MonsterCastsLightningThornsText }, } minions["Metadata/Monsters/Axis/AxisExperimenter"] = { name = "Mortality Experimenter", life = 0.96, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 75, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Wand", skillList = { "Melee", "SkeletonTemporalChains", "ExperimenterDetonateDead", }, modList = { -- MonsterCastsTemporalChainsText -- MonsterDetonatesCorpsesText }, } minions["Metadata/Monsters/Axis/AxisExperimenter2"] = { name = "Flesh Sculptor", life = 0.96, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 75, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Wand", skillList = { "ExperimenterDetonateDead", "Melee", "MonsterEnfeeble", "MonsterProjectileWeakness", }, modList = { -- MonsterDetonatesCorpsesText -- MonsterCastsEnfeebleCurseText -- MonsterCastsProjectileWeaknessCurseText }, } minions["Metadata/Monsters/Axis/AxisExperimenterRaiseZombie"] = { name = "Reanimator", life = 0.96, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 75, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Wand", skillList = { "Melee", "MonsterEnfeeble", "NecromancerRaiseZombie", }, modList = { -- MonsterCastsEnfeebleCurseText -- MonsterRaisesZombiesText }, } -- Bandit minions["Metadata/Monsters/Bandits/BanditBowExplosiveArrow"] = { name = "Kraityn's Sniper", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "BanditExplosiveArrow", }, modList = { -- MonsterFiresExplosiveArrowText }, } minions["Metadata/Monsters/Bandits/BanditBowPoisonArrow"] = { name = "Alira's Deadeye", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterCausticArrow", }, modList = { -- MonsterFiresCausticArrowsText }, } minions["Metadata/Monsters/Bandits/BanditMeleeWarlordsMarkMaul"] = { name = "Oak's Devoted", life = 1, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.35, attackRange = 5, weaponType1 = "Two Handed Mace", skillList = { "Melee", "MonsterWarlordsMark", }, modList = { -- MonsterCastsWarlordsMarkCurseText }, } -- Beast minions["Metadata/Monsters/Beasts/BeastCaveDegenAura"] = { name = "Shaggy Monstrosity", life = 2.1, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.5, damageSpread = 0.2, attackTime = 1.605, attackRange = 12, damageFixup = 0.33, skillList = { "Melee", "ChaosDegenAura", }, modList = { -- MonsterSpeedAndDamageFixupComplete }, } minions["Metadata/Monsters/Beasts/BeastCleaveEnduringCry"] = { name = "Hairy Bonecruncher", life = 2.1, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.5, damageSpread = 0.2, attackTime = 1.605, attackRange = 12, damageFixup = 0.33, skillList = { "Melee", "MonsterEnduringCry", "BeastCleave", }, modList = { -- MonsterSpeedAndDamageFixupComplete -- MonsterUsesEnduringCryText -- MonsterCleavesText }, } -- Blood apes minions["Metadata/Monsters/BloodChieftain/MonkeyChiefBloodEnrage"] = { name = "Carnage Chieftain", life = 1.5, fireResist = 75, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.5, damageSpread = 0.2, attackTime = 1.395, attackRange = 5, damageFixup = 0.22, weaponType1 = "One Handed Mace", skillList = { "Melee", "BloodChieftainSummonMonkeys", "MassFrenzy", }, modList = { -- MonsterSpeedAndDamageFixupLarge -- MonsterSummonsMonkeysText -- MonsterCastsMassFrenzyText }, } -- Bull minions["Metadata/Monsters/Bull/Bull"] = { name = "Fighting Bull", life = 2.38, fireResist = 0, coldResist = 40, lightningResist = 0, chaosResist = 0, damage = 1.28, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, weaponType1 = "One Handed Mace", skillList = { "Melee", "BullCharge", }, modList = { }, } -- Cannibals minions["Metadata/Monsters/Cannibal/CannibalMaleChampion"] = { name = "Cannibal Fire-eater", life = 1.44, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.2, damageSpread = 0.2, attackTime = 1.995, attackRange = 5, weaponType1 = "One Handed Mace", skillList = { "Melee", "MonsterFlameRedCannibal", }, modList = { -- StanceScavengerRun }, } -- Goatmen minions["Metadata/Monsters/Goatman/GoatmanLeapSlam"] = { name = "Goatman", life = 1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.455, attackRange = 5, skillList = { "MonsterLeapSlam", "Melee", "GoatmanWait", "GoatmanWait2", }, modList = { -- MonsterLeapsOntoEnemiesText }, } minions["Metadata/Monsters/Goatman/GoatmanLightningLeapSlamMaps"] = { name = "Bearded Devil", life = 1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.8, damageSpread = 0.2, attackTime = 1.455, attackRange = 5, skillList = { "MonsterLeapSlam", "Melee", "GoatmanWait", "GoatmanWait2", }, modList = { mod("PhysicalDamageGainAsLightning", "BASE", 100), -- MonsterPhysicalAddedAsLightningSkeletonMaps -- MonsterLeapsOntoEnemiesText }, } minions["Metadata/Monsters/Goatman/GoatmanShamanFireball"] = { name = "Goatman Shaman", life = 1, energyShield = 0.2, fireResist = 75, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, weaponType1 = "Staff", skillList = { "MonsterFireball", "GoatmanMoltenShell", }, modList = { -- MonsterSpeedAndDamageFixupSmall mod("Speed", "INC", -50, ModFlag.Cast), -- MonsterGoatmanShamanCastSpeed -- MonsterCastsFireballText -- MonsterCastsMoltenShellText }, } minions["Metadata/Monsters/Goatman/GoatmanShamanFireChampion"] = { name = "Goatman Fire-raiser", life = 1.4, energyShield = 0.2, fireResist = 75, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, weaponType1 = "Staff", skillList = { "MonsterFireball", "GoatmanMoltenShell", "GoatmanFireMagmaOrb", }, modList = { -- MonsterSpeedAndDamageFixupSmall mod("Speed", "INC", -50, ModFlag.Cast), -- MonsterGoatmanShamanCastSpeed }, } minions["Metadata/Monsters/Goatman/GoatmanShamanLightning"] = { name = "Bearded Shaman", life = 1, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, weaponType1 = "Staff", skillList = { "Melee", "MonsterShockNova", "MonsterSpark", }, modList = { -- MonsterSpeedAndDamageFixupSmall mod("Speed", "INC", -50, ModFlag.Cast), -- MonsterGoatmanShamanCastSpeed -- MonsterCastsShockNovaText -- MonsterCastsSparkText }, } -- Miscreation minions["Metadata/Monsters/DemonFemale/DemonFemale"] = { name = "Whipping Miscreation", life = 0.99, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.88, damageSpread = 0.2, attackTime = 2.445, attackRange = 16, skillList = { "Melee", }, modList = { -- MonsterChanceToVulnerabilityOnHit2 }, } minions["Metadata/Monsters/DemonModular/DemonFemaleRanged"] = { name = "Tentacle Miscreation", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.84, damageSpread = 0.2, attackTime = 3, attackRange = 4, skillList = { "DemonFemaleRangedProjectile", }, modList = { mod("PhysicalDamageConvertToFire", "BASE", 50), -- MonsterConvertToFireDamage2 }, } minions["Metadata/Monsters/DemonModular/DemonModularBladeVortex"] = { name = "Slashed Miscreation", life = 1.5, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, skillList = { "Melee", "DemonModularBladeVortex", "DemonModularBladeVortexSpectre", }, modList = { }, } minions["Metadata/Monsters/DemonModular/DemonModularFire"] = { name = "Burned Miscreation", life = 1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, skillList = { "Melee", "MonsterRighteousFire", "MonsterRighteousFireWhileSpectred", }, modList = { -- MonsterCastsUnholyFireText }, } -- Maw minions["Metadata/Monsters/Frog/Frog"] = { name = "Fetid Maw", life = 1, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.455, attackRange = 5, skillList = { "MonsterLeapSlam", "Melee", }, modList = { -- MonsterLeapsOntoEnemiesText }, } minions["Metadata/Monsters/Frog/Frog2"] = { name = "Murk Fiend", life = 1, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.455, attackRange = 5, skillList = { "MonsterLeapSlam", "Melee", }, modList = { -- MonsterLeapsOntoEnemiesText }, } -- Chimeral minions["Metadata/Monsters/GemMonster/Iguana"] = { name = "Plumed Chimeral", life = 1.25, energyShield = 0.2, fireResist = 52, coldResist = 52, lightningResist = 0, chaosResist = 0, damage = 1.12, damageSpread = 0.2, attackTime = 1.005, attackRange = 7, skillList = { "IguanaProjectile", "Melee", }, modList = { -- MonsterSuppressingFire -- DisplayMonsterSuppressingFire }, } -- Ghost pirate minions["Metadata/Monsters/GhostPirates/GhostPirateBlackBowMaps"] = { name = "Spectral Bowman", life = 0.96, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.48, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterPuncture", }, modList = { mod("PhysicalDamageGainAsLightning", "BASE", 100), -- MonsterPhysicalAddedAsLightningSkeletonMaps -- MonsterCastsPunctureText }, } minions["Metadata/Monsters/GhostPirates/GhostPirateBlackFlickerStrikeMaps"] = { name = "Cursed Mariner", life = 1, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.8, damageSpread = 0.2, attackTime = 1.65, attackRange = 6, weaponType1 = "One Handed Sword", weaponType2 = "Shield", skillList = { "Melee", "MonsterFlickerStrike", }, modList = { mod("PhysicalDamageGainAsLightning", "BASE", 100), -- MonsterPhysicalAddedAsLightningSkeletonMaps -- MonsterUsesFlickerStrikeText }, } minions["Metadata/Monsters/GhostPirates/GhostPirateGreenBladeVortex"] = { name = "Spectral Scoundrel", life = 1.5, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.65, attackRange = 6, weaponType1 = "One Handed Sword", weaponType2 = "Shield", skillList = { "Melee", "GhostPirateBladeVortex", "GhostPirateBladeVortexSpectre", }, modList = { mod("PhysicalDamageConvertToLightning", "BASE", 50), -- MonsterElementalSkeletonLightning }, } -- Undying grappler minions["Metadata/Monsters/Grappler/Grappler"] = { name = "Undying Grappler", life = 1, fireResist = 20, coldResist = 20, lightningResist = 20, chaosResist = 20, damage = 1, damageSpread = 0.2, attackTime = 1.245, attackRange = 5, skillList = { "Melee", "MonsterFlickerStrike", "MonsterDischarge", }, modList = { -- MonsterGainsPowerChargeOnKinDeath -- MonsterUsesFlickerStrikeText -- MonsterCastsDischargeText }, } minions["Metadata/Monsters/Grappler/GrapplerLabyrinth"] = { name = "Shadow Lurker", life = 1, fireResist = 20, coldResist = 20, lightningResist = 20, chaosResist = 20, damage = 1, damageSpread = 0.2, attackTime = 1.245, attackRange = 5, skillList = { "Melee", "MonsterFlickerStrike", "MonsterDischarge", }, modList = { -- MonsterGainsPowerChargeOnKinDeath -- MonsterUsesFlickerStrikeText -- MonsterCastsDischargeText }, } -- Ribbon minions["Metadata/Monsters/Guardians/GuardianFire"] = { name = "Flame Sentinel", life = 1.8, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.2, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, skillList = { "MonsterMultiFireball", "MonsterSplitFireball", "MonsterLesserMultiFireball", "MonsterMultiFireballSpectre", "MonsterSplitFireballSpectre", "MonsterLesserMultiFireballSpectre", }, modList = { -- MonsterCastsAugmentedFireballsText }, } minions["Metadata/Monsters/Guardians/GuardianLightning"] = { name = "Galvanic Ribbon", life = 1.8, energyShield = 0.4, fireResist = 0, coldResist = 85, lightningResist = 0, chaosResist = 0, damage = 1.2, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, skillList = { "GuardianArc", }, modList = { -- MonsterChannelsLightningText }, } -- Gut flayer minions["Metadata/Monsters/HalfSkeleton/HalfSkeleton"] = { name = "Gut Flayer", life = 1.32, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.1, damageSpread = 0.3, attackTime = 1.5, attackRange = 8, weaponType1 = "Dagger", skillList = { "Melee", "HalfSkeletonPuncture", }, modList = { -- MonsterCastsPunctureText }, } -- Construct minions["Metadata/Monsters/incaminion/Fragment"] = { name = "Ancient Construct", life = 0.7, energyShield = 0.2, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 40, damage = 0.84, damageSpread = 0.2, attackTime = 1.995, attackRange = 25, skillList = { "IncaMinionProjectile", }, modList = { }, } -- Carrion queen minions["Metadata/Monsters/InsectSpawner/InsectSpawner"] = { name = "Carrion Queen", life = 2.45, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.56, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, skillList = { "InsectSpawnerSpit", "InsectSpawnerSpawn", }, modList = { mod("PhysicalDamageConvertToFire", "BASE", 50), -- MonsterConvertToFireDamage2 }, } -- Kaom's Warriors minions["Metadata/Monsters/KaomWarrior/KaomWarrior2"] = { name = "Kaom's Chosen", life = 1.43, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.16, damageSpread = 0.2, attackTime = 1.755, attackRange = 7, skillList = { "Melee", "KaomWarriorMoltenStrike", }, modList = { }, } minions["Metadata/Monsters/KaomWarrior/KaomWarrior3"] = { name = "Kaom's Chosen", life = 1.43, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.16, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, skillList = { "Melee", "KaomWarriorGroundSlam", }, modList = { }, } -- Birdman minions["Metadata/Monsters/Kiweth/Kiweth"] = { name = "Avian Retch", life = 1.54, energyShield = 0.2, fireResist = 0, coldResist = 40, lightningResist = 0, chaosResist = 0, damage = 1.68, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, damageFixup = 0.11, skillList = { "Melee", "BirdmanConsumeCorpse", "BirdmanBloodProjectile", }, modList = { -- MonsterSpeedAndDamageFixupSmall -- MonsterLesserFarShot }, } minions["Metadata/Monsters/Kiweth/KiwethSeagull"] = { name = "Gluttonous Gull", life = 1.3, energyShield = 0.12, fireResist = 0, coldResist = 40, lightningResist = 0, chaosResist = 0, damage = 1.56, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, damageFixup = 0.11, skillList = { "Melee", "BirdmanConsumeCorpse", "BirdmanBloodProjectile", }, modList = { -- MonsterSpeedAndDamageFixupSmall -- MonsterLesserFarShot }, } -- Helion minions["Metadata/Monsters/Lion/LionDesertSkinPuncture"] = { name = "Dune Hellion", life = 1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 8, skillList = { "Melee", "MonsterPuncture", }, modList = { -- MonsterCastsPunctureText }, } -- Knitted horror minions["Metadata/Monsters/MassSkeleton/MassSkeleton"] = { name = "Knitted Horror", life = 2.25, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 9, skillList = { "Melee", "SkeletonMassBowProjectile", }, modList = { -- MonsterCastsPunctureText }, } -- Miners minions["Metadata/Monsters/Miner/MinerLantern"] = { name = "Pocked Lanternbearer", life = 1.21, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.21, damageSpread = 0.2, attackTime = 1.395, attackRange = 7, skillList = { "MinerThrowFire", "MinerThrowFireSpectre", }, modList = { -- IgniteArtVariation }, } minions["Metadata/Monsters/Miner/MinerLanternCrystalVeins"] = { name = "Pocked Illuminator", life = 1.21, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.21, damageSpread = 0.2, attackTime = 1.395, attackRange = 7, skillList = { "MinerThrowFire", "MinerThrowFireSpectre", }, modList = { -- IgniteArtVariation }, } -- Voidbearer minions["Metadata/Monsters/Monkeys/FlameBearer"] = { name = "Voidbearer", life = 1.1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.1, damageSpread = 0.2, attackTime = 1.5, attackRange = 5, skillList = { "Melee", "FlamebearerFlameBlue", }, modList = { }, } -- Stone golem minions["Metadata/Monsters/MossMonster/FireMonster"] = { name = "Cinder Elemental", life = 2.7, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.5, damageSpread = 0.2, attackTime = 1.695, attackRange = 5, damageFixup = 0.33, skillList = { "Melee", "FireMonsterWhirlingBlades", }, modList = { -- MonsterSpeedAndDamageFixupComplete -- MonsterRollsOverEnemiesText -- ImmuneToLavaDamage }, } -- Necromancer minions["Metadata/Monsters/Necromancer/NecromancerConductivity"] = { name = "Sin Lord", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerConductivity", }, modList = { -- MonsterRaisesUndeadText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty -- MonsterCastsConductivityText }, } minions["Metadata/Monsters/Necromancer/NecromancerEnfeebleCurse"] = { name = "Diabolist", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerEnfeeble", }, modList = { -- MonsterRaisesUndeadText -- MonsterCastsEnfeebleCurseText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty }, } minions["Metadata/Monsters/Necromancer/NecromancerFlamability"] = { name = "Ash Prophet", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerFlammability", }, modList = { -- MonsterRaisesUndeadText -- MonsterCastsFlammabilityText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty -- ImmuneToLavaDamage }, } minions["Metadata/Monsters/Necromancer/NecromancerFrostbite"] = { name = "Death Bishop", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerFrostbite", }, modList = { -- MonsterRaisesUndeadText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty -- MonsterCastsFrostbiteText }, } minions["Metadata/Monsters/Necromancer/NecromancerElementalWeakness"] = { name = "Defiler", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerElementalWeakness", }, modList = { -- MonsterRaisesUndeadText -- MonsterCastsElementralWeaknessCurseText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty }, } minions["Metadata/Monsters/Necromancer/NecromancerProjectileWeakness"] = { name = "Necromancer", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerProjectileWeakness", }, modList = { -- MonsterRaisesUndeadText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty -- MonsterCastsProjectileWeaknessCurseText }, } minions["Metadata/Monsters/Necromancer/NecromancerVulnerability"] = { name = "Necromancer", life = 1.86, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 0.98, damageSpread = 0.2, attackTime = 1.5, attackRange = 7, skillList = { "Melee", "NecromancerReviveSkeleton", "NecromancerVulnerability", }, modList = { -- MonsterRaisesUndeadText mod("Speed", "INC", -80, ModFlag.Cast, KeywordFlag.Curse), -- MonsterCurseCastSpeedPenalty -- MonsterCastsVulnerabilityCurseText }, } -- Undying bomber minions["Metadata/Monsters/Pyromaniac/PyromaniacFire"] = { name = "Undying Incinerator", life = 1, fireResist = 75, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 5, skillList = { "PyroFireball", "PyroSuicideExplosion", "MonsterFireBomb", }, modList = { -- MonsterThrowsFireBombsText -- MonsterExplodesOnItsTargetOnLowLifeText -- ImmuneToLavaDamage }, } minions["Metadata/Monsters/Pyromaniac/PyromaniacPoison"] = { name = "Undying Alchemist", life = 1, fireResist = 75, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.5, attackRange = 5, skillList = { "Melee", "MonsterCausticBomb", "PyroChaosFireball", }, modList = { -- MonsterThrowsPoisonBombsText }, } -- Stygian revenant minions["Metadata/Monsters/Revenant/Revenant"] = { name = "Stygian Revenant", life = 1.82, fireResist = 0, coldResist = 0, lightningResist = 75, chaosResist = 0, damage = 1.4, damageSpread = 0.2, attackTime = 1.5, attackRange = 8, skillList = { "RevenantReviveUndead", "RevenantSpellProjectile", "Melee", "RevenantSpellProjectileSpectre", }, modList = { }, } -- Sea witch minions["Metadata/Monsters/Seawitch/SeaWitchFrostBolt"] = { name = "Merveil's Blessed", life = 1.44, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.02, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, skillList = { "SeaWitchWave", "Melee", "SeawitchFrostbolt", }, modList = { -- MonsterSpeedAndDamageFixupSmall }, } minions["Metadata/Monsters/Seawitch/SeaWitchScreech"] = { name = "Singing Siren", life = 1.02, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.02, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, skillList = { "SeaWitchWave", "Melee", "SeaWitchScreech", }, modList = { -- MonsterSpeedAndDamageFixupSmall }, } minions["Metadata/Monsters/Seawitch/SeaWitchSpawnExploding"] = { name = "Merveil's Attendant", life = 1.02, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.02, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, skillList = { "SeaWitchWave", "Melee", "SummonExplodingSpawn", "SeaWitchScreech", }, modList = { -- MonsterSpeedAndDamageFixupSmall -- MonsterSummonsExplodingSpawnText }, } minions["Metadata/Monsters/Seawitch/SeaWitchSpawnTemporalChains"] = { name = "Merveil's Chosen", life = 1.02, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.02, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, skillList = { "SeaWitchWave", "Melee", "SkeletonTemporalChains", "SummonSpawn", }, modList = { -- MonsterSpeedAndDamageFixupSmall -- MonsterSummonsSpawnText -- MonsterCastsTemporalChainsText }, } minions["Metadata/Monsters/Seawitch/SeaWitchVulnerabilityCurse"] = { name = "Merveil's Chosen", life = 1.02, energyShield = 0.4, fireResist = 0, coldResist = 75, lightningResist = 0, chaosResist = 0, damage = 1.02, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.11, skillList = { "SeaWitchWave", "Melee", "SkeletonVulnerability", }, modList = { -- MonsterSpeedAndDamageFixupSmall -- MonsterCastsVulnerabilityCurseText }, } -- Skeleton minions["Metadata/Monsters/Skeletons/SkeletonBowPuncture"] = { name = "Brittle Bleeder", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterPuncture", }, modList = { -- MonsterNecromancerRaisable -- MonsterCastsPunctureText }, } minions["Metadata/Monsters/Skeletons/SkeletonBowLightning"] = { name = "Brittle Poacher", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterLightningArrow", }, modList = { -- MonsterNecromancerRaisable -- MonsterFiresLightningArrowsText }, } minions["Metadata/Monsters/Skeletons/SkeletonMeleeLarge"] = { name = "Colossal Bonestalker", life = 1.98, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1.8, damageSpread = 0.2, attackTime = 2.25, attackRange = 7, weaponType1 = "One Handed Mace", skillList = { "Melee", }, modList = { -- MonsterNecromancerRaisable }, } minions["Metadata/Monsters/Skeletons/SkeletonBowLightning3"] = { name = "Flayed Archer", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterLightningArrow", }, modList = { -- MonsterNecromancerRaisable -- MonsterFiresLightningArrowsText }, } minions["Metadata/Monsters/Skeletons/SkeletonCasterColdMultipleProjectiles"] = { name = "Frost Harbinger", life = 0.84, energyShield = 0.4, fireResist = 0, coldResist = 40, lightningResist = 0, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.605, attackRange = 46, skillList = { "SkeletonProjectileCold", }, modList = { mod("ProjectileCount", "BASE", 2), -- MonsterMultipleProjectilesImplicit1 -- MonsterNecromancerRaisable }, } minions["Metadata/Monsters/Skeletons/SkeletonCasterFireMultipleProjectiles2"] = { name = "Incinerated Mage", life = 0.84, energyShield = 0.4, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.605, attackRange = 46, skillList = { "SkeletonProjectileFire", }, modList = { -- MonsterNecromancerRaisable mod("ProjectileCount", "BASE", 2), -- MonsterMultipleProjectilesImplicit1 -- ImmuneToLavaDamage }, } minions["Metadata/Monsters/Skeletons/SkeletonBowPoison"] = { name = "Plagued Bowman", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterCausticArrow", }, modList = { -- MonsterNecromancerRaisable -- MonsterFiresCausticArrowsText }, } minions["Metadata/Monsters/Skeletons/SkeletonBowLightning2"] = { name = "Restless Archer", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterLightningArrow", }, modList = { -- MonsterNecromancerRaisable -- MonsterFiresLightningArrowsText }, } minions["Metadata/Monsters/Skeletons/SkeletonBowLightning4"] = { name = "Sin Archer", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterLightningArrow", }, modList = { -- MonsterNecromancerRaisable -- MonsterFiresLightningArrowsText }, } minions["Metadata/Monsters/Skeletons/SkeletonCasterLightningSpark"] = { name = "Sparking Mage", life = 0.84, energyShield = 0.4, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.605, attackRange = 46, skillList = { "SkeletonProjectileLightning", "SkeletonSpark", }, modList = { -- MonsterNecromancerRaisable -- MonsterCastsSparkText }, } minions["Metadata/Monsters/Skeletons/SkeletonBowProjectileWeaknessCurse"] = { name = "Vexing Archer", life = 0.96, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 0.6, damageSpread = 0.2, attackTime = 1.995, attackRange = 40, weaponType1 = "Bow", skillList = { "Melee", "MonsterProjectileWeakness", }, modList = { -- MonsterNecromancerRaisable -- MonsterCastsProjectileWeaknessCurseText }, } -- Snake minions["Metadata/Monsters/Snake/SnakeMeleeSpit"] = { name = "Bramble Cobra", life = 0.8, fireResist = 30, coldResist = 0, lightningResist = 0, chaosResist = 30, damage = 1, damageSpread = 0.2, attackTime = 1.65, attackRange = 7, skillList = { "Melee", "SnakeProjectile", }, modList = { mod("PhysicalDamageConvertToChaos", "BASE", 30), -- MonsterSnakeChaos }, } minions["Metadata/Monsters/Snake/SnakeScorpionMultiShot"] = { name = "Barb Serpent", life = 0.94, fireResist = 30, coldResist = 0, lightningResist = 0, chaosResist = 30, damage = 0.75, damageSpread = 0.2, attackTime = 1.65, attackRange = 7, skillList = { "Melee", "SnakeSpineProjectile", }, modList = { mod("PhysicalDamageConvertToChaos", "BASE", 30), -- MonsterSnakeChaos mod("ProjectileCount", "BASE", 2), -- MonsterMultipleProjectilesImplicit1 }, } -- Spider minions["Metadata/Monsters/Spiders/SpiderThornFlickerStrike"] = { name = "Leaping Spider", life = 1, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.44, attackRange = 6, skillList = { "Melee", "MonsterFlickerStrike", }, modList = { -- MonsterUsesFlickerStrikeText }, } -- Statue minions["Metadata/Monsters/Statue/DaressoStatueLargeMaleSpear"] = { name = "Towering Figment", life = 5.76, fireResist = 0, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.3, damageSpread = 0.2, attackTime = 1.875, attackRange = 14, damageFixup = 0.33, weaponType1 = "One Handed Sword", skillList = { "Melee", "MonsterPuncture", }, modList = { -- MonsterSpeedAndDamageFixupComplete -- MonsterCastsPunctureText }, } -- Ophidian minions["Metadata/Monsters/Taster/Taster"] = { name = "Noisome Ophidian", life = 1, fireResist = 40, coldResist = 0, lightningResist = 0, chaosResist = 0, damage = 1.5, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, weaponType1 = "Dagger", skillList = { "Melee", "TarMortarTaster", }, modList = { }, } -- Undying minions["Metadata/Monsters/Undying/CityStalkerMaleCasterArmour"] = { name = "Undying Evangelist", life = 1.2, fireResist = 37, coldResist = 37, lightningResist = 37, chaosResist = 0, damage = 1.2, damageSpread = 0.2, attackTime = 1.245, attackRange = 5, skillList = { "Melee", "DelayedBlast", "MonsterProximityShield", "DelayedBlastSpectre", }, modList = { }, } minions["Metadata/Monsters/Undying/UndyingOutcastPuncture"] = { name = "Undying Impaler", life = 1, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.65, attackRange = 4, skillList = { "Melee", "MonsterPuncture", }, modList = { -- MonsterCastsPunctureText }, } minions["Metadata/Monsters/Undying/UndyingOutcastWhirlingBlades"] = { name = "Undying Outcast", life = 1, fireResist = 0, coldResist = 0, lightningResist = 40, chaosResist = 0, damage = 1, damageSpread = 0.2, attackTime = 1.65, attackRange = 4, skillList = { "Melee", "UndyingWhirlingBlades", }, modList = { }, }
mit
pchote/OpenRA
mods/d2k/maps/ordos-03a/ordos03a.lua
2
4895
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] HarkonnenBase = { HBarracks, HWindTrap1, HWindTrap2, HLightFactory, HOutpost, HConyard, HRefinery, HSilo1, HSilo2, HSilo3, HSilo4 } HarkonnenBaseAreaTrigger = { CPos.New(2, 58), CPos.New(3, 58), CPos.New(4, 58), CPos.New(5, 58), CPos.New(6, 58), CPos.New(7, 58), CPos.New(8, 58), CPos.New(9, 58), CPos.New(10, 58), CPos.New(11, 58), CPos.New(12, 58), CPos.New(13, 58), CPos.New(14, 58), CPos.New(15, 58), CPos.New(16, 58), CPos.New(16, 59), CPos.New(16, 60) } HarkonnenReinforcements = { easy = { { "light_inf", "trike", "trooper" }, { "light_inf", "trike", "quad" }, { "light_inf", "light_inf", "trooper", "trike", "trike", "quad" } }, normal = { { "light_inf", "trike", "trooper" }, { "light_inf", "trike", "trike" }, { "light_inf", "light_inf", "trooper", "trike", "trike", "quad" }, { "light_inf", "light_inf", "trooper", "trooper" }, { "light_inf", "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike", "quad", "quad" } }, hard = { { "trike", "trike", "quad" }, { "light_inf", "trike", "trike" }, { "trooper", "trooper", "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf", "trooper", "trooper" }, { "trike", "trike", "quad", "quad", "quad", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "trike", "light_inf", "trooper", "trooper", "quad" }, { "trike", "trike", "quad", "quad", "quad", "trike" } } } HarkonnenAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(20) } HarkonnenAttackWaves = { easy = 3, normal = 6, hard = 9 } HarkonnenPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry2.Location, HarkonnenRally2.Location }, { HarkonnenEntry3.Location, HarkonnenRally3.Location } } HarkonnenHunters = { "light_inf", "light_inf", "trike", "quad" } HarkonnenInitialReinforcements = { "light_inf", "light_inf", "quad", "quad", "trike", "trike", "trooper", "trooper" } HarkonnenHunterPath = { HarkonnenEntry5.Location, HarkonnenRally5.Location } HarkonnenInitialPath = { HarkonnenEntry4.Location, HarkonnenRally4.Location } OrdosReinforcements = { "quad", "raider" } OrdosPath = { OrdosEntry.Location, OrdosRally.Location } OrdosBaseBuildings = { "barracks", "light_factory" } OrdosUpgrades = { "upgrade.barracks", "upgrade.light" } MessageCheck = function(index) return #player.GetActorsByType(OrdosBaseBuildings[index]) > 0 and not player.HasPrerequisites({ OrdosUpgrades[index] }) end Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillOrdos) end if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[harkonnen] then local units = harkonnen.GetActorsByType("harvester") if #units > 0 then LastHarvesterEaten[harkonnen] = false ProtectHarvester(units[1], harkonnen, AttackGroupSize[Difficulty]) end end if DateTime.GameTime % DateTime.Seconds(32) == 0 and (MessageCheck(1) or MessageCheck(2)) then Media.DisplayMessage("Upgrade barracks and light factory to produce more advanced units.", "Mentat") end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") player = Player.GetPlayer("Ordos") InitObjectives(player) KillOrdos = harkonnen.AddPrimaryObjective("Kill all Ordos units.") KillHarkonnen = player.AddPrimaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.") Camera.Position = OConyard.CenterPosition Trigger.OnAllKilled(HarkonnenBase, function() Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt) end) local path = function() return Utils.Random(HarkonnenPaths) end local waveCondition = function() return player.IsObjectiveCompleted(KillHarkonnen) end SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty], waveCondition) ActivateAI() Trigger.AfterDelay(DateTime.Minutes(2) + DateTime.Seconds(30), function() Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", OrdosReinforcements, OrdosPath, { OrdosPath[1] }) end) TriggerCarryallReinforcements(player, harkonnen, HarkonnenBaseAreaTrigger, HarkonnenHunters, HarkonnenHunterPath) end
gpl-3.0
codyroux/lean0.1
src/builtin/name_conv.lua
1
1101
-- Output a C++ statement that creates the given name function sanitize(s) s, _ = string.gsub(s, "'", "_") return s end function name_to_cpp_expr(n) function rec(n) if not n:is_atomic() then rec(n:get_prefix()) io.write(", ") end if n:is_string() then local s = n:get_string() io.write("\"" .. sanitize(s) .. "\"") else error("numeral hierarchical names are not supported in the C++ interface: " .. tostring(n)) end end io.write("name(") if n:is_atomic() then rec(n) else io.write("{") rec(n) io.write("}") end io.write(")") end -- Output a C++ constant name based on the given hierarchical name -- It uses '_' to glue the hierarchical name parts function name_to_cpp_decl(n) if not n:is_atomic(n) then name_to_cpp_decl(n:get_prefix()) io.write("_") end if n:is_string() then local s = n:get_string() io.write(sanitize(s)) else error("numeral hierarchical names are not supported in the C++ interface: " .. tostring(n)) end end
apache-2.0
stephank/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-app.lua
137
15546
cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true app_alarmreceiver = module:option(ListValue, "app_alarmreceiver", "Alarm Receiver Application", "") app_alarmreceiver:value("yes", "Load") app_alarmreceiver:value("no", "Do Not Load") app_alarmreceiver:value("auto", "Load as Required") app_alarmreceiver.rmempty = true app_authenticate = module:option(ListValue, "app_authenticate", "Authentication Application", "") app_authenticate:value("yes", "Load") app_authenticate:value("no", "Do Not Load") app_authenticate:value("auto", "Load as Required") app_authenticate.rmempty = true app_cdr = module:option(ListValue, "app_cdr", "Make sure asterisk doesnt save CDR", "") app_cdr:value("yes", "Load") app_cdr:value("no", "Do Not Load") app_cdr:value("auto", "Load as Required") app_cdr.rmempty = true app_chanisavail = module:option(ListValue, "app_chanisavail", "Check if channel is available", "") app_chanisavail:value("yes", "Load") app_chanisavail:value("no", "Do Not Load") app_chanisavail:value("auto", "Load as Required") app_chanisavail.rmempty = true app_chanspy = module:option(ListValue, "app_chanspy", "Listen in on any channel", "") app_chanspy:value("yes", "Load") app_chanspy:value("no", "Do Not Load") app_chanspy:value("auto", "Load as Required") app_chanspy.rmempty = true app_controlplayback = module:option(ListValue, "app_controlplayback", "Control Playback Application", "") app_controlplayback:value("yes", "Load") app_controlplayback:value("no", "Do Not Load") app_controlplayback:value("auto", "Load as Required") app_controlplayback.rmempty = true app_cut = module:option(ListValue, "app_cut", "Cuts up variables", "") app_cut:value("yes", "Load") app_cut:value("no", "Do Not Load") app_cut:value("auto", "Load as Required") app_cut.rmempty = true app_db = module:option(ListValue, "app_db", "Database access functions", "") app_db:value("yes", "Load") app_db:value("no", "Do Not Load") app_db:value("auto", "Load as Required") app_db.rmempty = true app_dial = module:option(ListValue, "app_dial", "Dialing Application", "") app_dial:value("yes", "Load") app_dial:value("no", "Do Not Load") app_dial:value("auto", "Load as Required") app_dial.rmempty = true app_dictate = module:option(ListValue, "app_dictate", "Virtual Dictation Machine Application", "") app_dictate:value("yes", "Load") app_dictate:value("no", "Do Not Load") app_dictate:value("auto", "Load as Required") app_dictate.rmempty = true app_directed_pickup = module:option(ListValue, "app_directed_pickup", "Directed Call Pickup Support", "") app_directed_pickup:value("yes", "Load") app_directed_pickup:value("no", "Do Not Load") app_directed_pickup:value("auto", "Load as Required") app_directed_pickup.rmempty = true app_directory = module:option(ListValue, "app_directory", "Extension Directory", "") app_directory:value("yes", "Load") app_directory:value("no", "Do Not Load") app_directory:value("auto", "Load as Required") app_directory.rmempty = true app_disa = module:option(ListValue, "app_disa", "DISA (Direct Inward System Access) Application", "") app_disa:value("yes", "Load") app_disa:value("no", "Do Not Load") app_disa:value("auto", "Load as Required") app_disa.rmempty = true app_dumpchan = module:option(ListValue, "app_dumpchan", "Dump channel variables Application", "") app_dumpchan:value("yes", "Load") app_dumpchan:value("no", "Do Not Load") app_dumpchan:value("auto", "Load as Required") app_dumpchan.rmempty = true app_echo = module:option(ListValue, "app_echo", "Simple Echo Application", "") app_echo:value("yes", "Load") app_echo:value("no", "Do Not Load") app_echo:value("auto", "Load as Required") app_echo.rmempty = true app_enumlookup = module:option(ListValue, "app_enumlookup", "ENUM Lookup", "") app_enumlookup:value("yes", "Load") app_enumlookup:value("no", "Do Not Load") app_enumlookup:value("auto", "Load as Required") app_enumlookup.rmempty = true app_eval = module:option(ListValue, "app_eval", "Reevaluates strings", "") app_eval:value("yes", "Load") app_eval:value("no", "Do Not Load") app_eval:value("auto", "Load as Required") app_eval.rmempty = true app_exec = module:option(ListValue, "app_exec", "Executes applications", "") app_exec:value("yes", "Load") app_exec:value("no", "Do Not Load") app_exec:value("auto", "Load as Required") app_exec.rmempty = true app_externalivr = module:option(ListValue, "app_externalivr", "External IVR application interface", "") app_externalivr:value("yes", "Load") app_externalivr:value("no", "Do Not Load") app_externalivr:value("auto", "Load as Required") app_externalivr.rmempty = true app_forkcdr = module:option(ListValue, "app_forkcdr", "Fork The CDR into 2 seperate entities", "") app_forkcdr:value("yes", "Load") app_forkcdr:value("no", "Do Not Load") app_forkcdr:value("auto", "Load as Required") app_forkcdr.rmempty = true app_getcpeid = module:option(ListValue, "app_getcpeid", "Get ADSI CPE ID", "") app_getcpeid:value("yes", "Load") app_getcpeid:value("no", "Do Not Load") app_getcpeid:value("auto", "Load as Required") app_getcpeid.rmempty = true app_groupcount = module:option(ListValue, "app_groupcount", "Group Management Routines", "") app_groupcount:value("yes", "Load") app_groupcount:value("no", "Do Not Load") app_groupcount:value("auto", "Load as Required") app_groupcount.rmempty = true app_ices = module:option(ListValue, "app_ices", "Encode and Stream via icecast and ices", "") app_ices:value("yes", "Load") app_ices:value("no", "Do Not Load") app_ices:value("auto", "Load as Required") app_ices.rmempty = true app_image = module:option(ListValue, "app_image", "Image Transmission Application", "") app_image:value("yes", "Load") app_image:value("no", "Do Not Load") app_image:value("auto", "Load as Required") app_image.rmempty = true app_lookupblacklist = module:option(ListValue, "app_lookupblacklist", "Look up Caller*ID name/number from black", "") app_lookupblacklist:value("yes", "Load") app_lookupblacklist:value("no", "Do Not Load") app_lookupblacklist:value("auto", "Load as Required") app_lookupblacklist.rmempty = true app_lookupcidname = module:option(ListValue, "app_lookupcidname", "Look up CallerID Name from local databas", "") app_lookupcidname:value("yes", "Load") app_lookupcidname:value("no", "Do Not Load") app_lookupcidname:value("auto", "Load as Required") app_lookupcidname.rmempty = true app_macro = module:option(ListValue, "app_macro", "Extension Macros", "") app_macro:value("yes", "Load") app_macro:value("no", "Do Not Load") app_macro:value("auto", "Load as Required") app_macro.rmempty = true app_math = module:option(ListValue, "app_math", "A simple math Application", "") app_math:value("yes", "Load") app_math:value("no", "Do Not Load") app_math:value("auto", "Load as Required") app_math.rmempty = true app_md5 = module:option(ListValue, "app_md5", "MD5 checksum Application", "") app_md5:value("yes", "Load") app_md5:value("no", "Do Not Load") app_md5:value("auto", "Load as Required") app_md5.rmempty = true app_milliwatt = module:option(ListValue, "app_milliwatt", "Digital Milliwatt (mu-law) Test Application", "") app_milliwatt:value("yes", "Load") app_milliwatt:value("no", "Do Not Load") app_milliwatt:value("auto", "Load as Required") app_milliwatt.rmempty = true app_mixmonitor = module:option(ListValue, "app_mixmonitor", "Record a call and mix the audio during the recording", "") app_mixmonitor:value("yes", "Load") app_mixmonitor:value("no", "Do Not Load") app_mixmonitor:value("auto", "Load as Required") app_mixmonitor.rmempty = true app_parkandannounce = module:option(ListValue, "app_parkandannounce", "Call Parking and Announce Application", "") app_parkandannounce:value("yes", "Load") app_parkandannounce:value("no", "Do Not Load") app_parkandannounce:value("auto", "Load as Required") app_parkandannounce.rmempty = true app_playback = module:option(ListValue, "app_playback", "Trivial Playback Application", "") app_playback:value("yes", "Load") app_playback:value("no", "Do Not Load") app_playback:value("auto", "Load as Required") app_playback.rmempty = true app_privacy = module:option(ListValue, "app_privacy", "Require phone number to be entered", "") app_privacy:value("yes", "Load") app_privacy:value("no", "Do Not Load") app_privacy:value("auto", "Load as Required") app_privacy.rmempty = true app_queue = module:option(ListValue, "app_queue", "True Call Queueing", "") app_queue:value("yes", "Load") app_queue:value("no", "Do Not Load") app_queue:value("auto", "Load as Required") app_queue.rmempty = true app_random = module:option(ListValue, "app_random", "Random goto", "") app_random:value("yes", "Load") app_random:value("no", "Do Not Load") app_random:value("auto", "Load as Required") app_random.rmempty = true app_read = module:option(ListValue, "app_read", "Read Variable Application", "") app_read:value("yes", "Load") app_read:value("no", "Do Not Load") app_read:value("auto", "Load as Required") app_read.rmempty = true app_readfile = module:option(ListValue, "app_readfile", "Read in a file", "") app_readfile:value("yes", "Load") app_readfile:value("no", "Do Not Load") app_readfile:value("auto", "Load as Required") app_readfile.rmempty = true app_realtime = module:option(ListValue, "app_realtime", "Realtime Data Lookup/Rewrite", "") app_realtime:value("yes", "Load") app_realtime:value("no", "Do Not Load") app_realtime:value("auto", "Load as Required") app_realtime.rmempty = true app_record = module:option(ListValue, "app_record", "Trivial Record Application", "") app_record:value("yes", "Load") app_record:value("no", "Do Not Load") app_record:value("auto", "Load as Required") app_record.rmempty = true app_sayunixtime = module:option(ListValue, "app_sayunixtime", "Say time", "") app_sayunixtime:value("yes", "Load") app_sayunixtime:value("no", "Do Not Load") app_sayunixtime:value("auto", "Load as Required") app_sayunixtime.rmempty = true app_senddtmf = module:option(ListValue, "app_senddtmf", "Send DTMF digits Application", "") app_senddtmf:value("yes", "Load") app_senddtmf:value("no", "Do Not Load") app_senddtmf:value("auto", "Load as Required") app_senddtmf.rmempty = true app_sendtext = module:option(ListValue, "app_sendtext", "Send Text Applications", "") app_sendtext:value("yes", "Load") app_sendtext:value("no", "Do Not Load") app_sendtext:value("auto", "Load as Required") app_sendtext.rmempty = true app_setcallerid = module:option(ListValue, "app_setcallerid", "Set CallerID Application", "") app_setcallerid:value("yes", "Load") app_setcallerid:value("no", "Do Not Load") app_setcallerid:value("auto", "Load as Required") app_setcallerid.rmempty = true app_setcdruserfield = module:option(ListValue, "app_setcdruserfield", "CDR user field apps", "") app_setcdruserfield:value("yes", "Load") app_setcdruserfield:value("no", "Do Not Load") app_setcdruserfield:value("auto", "Load as Required") app_setcdruserfield.rmempty = true app_setcidname = module:option(ListValue, "app_setcidname", "load => .so ; Set CallerID Name", "") app_setcidname:value("yes", "Load") app_setcidname:value("no", "Do Not Load") app_setcidname:value("auto", "Load as Required") app_setcidname.rmempty = true app_setcidnum = module:option(ListValue, "app_setcidnum", "load => .so ; Set CallerID Number", "") app_setcidnum:value("yes", "Load") app_setcidnum:value("no", "Do Not Load") app_setcidnum:value("auto", "Load as Required") app_setcidnum.rmempty = true app_setrdnis = module:option(ListValue, "app_setrdnis", "Set RDNIS Number", "") app_setrdnis:value("yes", "Load") app_setrdnis:value("no", "Do Not Load") app_setrdnis:value("auto", "Load as Required") app_setrdnis.rmempty = true app_settransfercapability = module:option(ListValue, "app_settransfercapability", "Set ISDN Transfer Capability", "") app_settransfercapability:value("yes", "Load") app_settransfercapability:value("no", "Do Not Load") app_settransfercapability:value("auto", "Load as Required") app_settransfercapability.rmempty = true app_sms = module:option(ListValue, "app_sms", "SMS/PSTN handler", "") app_sms:value("yes", "Load") app_sms:value("no", "Do Not Load") app_sms:value("auto", "Load as Required") app_sms.rmempty = true app_softhangup = module:option(ListValue, "app_softhangup", "Hangs up the requested channel", "") app_softhangup:value("yes", "Load") app_softhangup:value("no", "Do Not Load") app_softhangup:value("auto", "Load as Required") app_softhangup.rmempty = true app_stack = module:option(ListValue, "app_stack", "Stack Routines", "") app_stack:value("yes", "Load") app_stack:value("no", "Do Not Load") app_stack:value("auto", "Load as Required") app_stack.rmempty = true app_system = module:option(ListValue, "app_system", "Generic System() application", "") app_system:value("yes", "Load") app_system:value("no", "Do Not Load") app_system:value("auto", "Load as Required") app_system.rmempty = true app_talkdetect = module:option(ListValue, "app_talkdetect", "Playback with Talk Detection", "") app_talkdetect:value("yes", "Load") app_talkdetect:value("no", "Do Not Load") app_talkdetect:value("auto", "Load as Required") app_talkdetect.rmempty = true app_test = module:option(ListValue, "app_test", "Interface Test Application", "") app_test:value("yes", "Load") app_test:value("no", "Do Not Load") app_test:value("auto", "Load as Required") app_test.rmempty = true app_transfer = module:option(ListValue, "app_transfer", "Transfer", "") app_transfer:value("yes", "Load") app_transfer:value("no", "Do Not Load") app_transfer:value("auto", "Load as Required") app_transfer.rmempty = true app_txtcidname = module:option(ListValue, "app_txtcidname", "TXTCIDName", "") app_txtcidname:value("yes", "Load") app_txtcidname:value("no", "Do Not Load") app_txtcidname:value("auto", "Load as Required") app_txtcidname.rmempty = true app_url = module:option(ListValue, "app_url", "Send URL Applications", "") app_url:value("yes", "Load") app_url:value("no", "Do Not Load") app_url:value("auto", "Load as Required") app_url.rmempty = true app_userevent = module:option(ListValue, "app_userevent", "Custom User Event Application", "") app_userevent:value("yes", "Load") app_userevent:value("no", "Do Not Load") app_userevent:value("auto", "Load as Required") app_userevent.rmempty = true app_verbose = module:option(ListValue, "app_verbose", "Send verbose output", "") app_verbose:value("yes", "Load") app_verbose:value("no", "Do Not Load") app_verbose:value("auto", "Load as Required") app_verbose.rmempty = true app_voicemail = module:option(ListValue, "app_voicemail", "Voicemail", "") app_voicemail:value("yes", "Load") app_voicemail:value("no", "Do Not Load") app_voicemail:value("auto", "Load as Required") app_voicemail.rmempty = true app_waitforring = module:option(ListValue, "app_waitforring", "Waits until first ring after time", "") app_waitforring:value("yes", "Load") app_waitforring:value("no", "Do Not Load") app_waitforring:value("auto", "Load as Required") app_waitforring.rmempty = true app_waitforsilence = module:option(ListValue, "app_waitforsilence", "Wait For Silence Application", "") app_waitforsilence:value("yes", "Load") app_waitforsilence:value("no", "Do Not Load") app_waitforsilence:value("auto", "Load as Required") app_waitforsilence.rmempty = true app_while = module:option(ListValue, "app_while", "While Loops and Conditional Execution", "") app_while:value("yes", "Load") app_while:value("no", "Do Not Load") app_while:value("auto", "Load as Required") app_while.rmempty = true return cbimap
apache-2.0
stephank/luci
applications/luci-asterisk/luasrc/asterisk/cc_idd.lua
92
7735
--[[ LuCI - Asterisk - International Direct Dialing Prefixes and Country Codes 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 ]]-- module "luci.asterisk.cc_idd" CC_IDD = { -- Country, CC, IDD { "Afghanistan", "93", "00" }, { "Albania", "355", "00" }, { "Algeria", "213", "00" }, { "American Samoa", "684", "00" }, { "Andorra", "376", "00" }, { "Angola", "244", "00" }, { "Anguilla", "264", "011" }, { "Antarctica", "672", "" }, { "Antigua", "268", "011" }, { "Argentina", "54", "00" }, { "Armenia", "374", "00" }, { "Aruba", "297", "00" }, { "Ascension Island", "247", "00" }, { "Australia", "61", "0011" }, { "Austria", "43", "00" }, { "Azberbaijan", "994", "00" }, { "Bahamas", "242", "011" }, { "Bahrain", "973", "00" }, { "Bangladesh", "880", "00" }, { "Barbados", "246", "011" }, { "Barbuda", "268", "011" }, { "Belarus", "375", "810" }, { "Belgium", "32", "00" }, { "Belize", "501", "00" }, { "Benin", "229", "00" }, { "Bermuda", "441", "011" }, { "Bhutan", "975", "00" }, { "Bolivia", "591", "00" }, { "Bosnia", "387", "00" }, { "Botswana", "267", "00" }, { "Brazil", "55", "00" }, { "British Virgin Islands", "284", "011" }, { "Brunei", "673", "00" }, { "Bulgaria", "359", "00" }, { "Burkina Faso", "226", "00" }, { "Burma (Myanmar)", "95", "00" }, { "Burundi", "257", "00" }, { "Cambodia", "855", "001" }, { "Cameroon", "237", "00" }, { "Canada", "1", "011" }, { "Cape Verde Islands", "238", "0" }, { "Cayman Islands", "345", "011" }, { "Central African Rep.", "236", "00" }, { "Chad", "235", "15" }, { "Chile", "56", "00" }, { "China", "86", "00" }, { "Christmas Island", "61", "0011" }, { "Cocos Islands", "61", "0011" }, { "Colombia", "57", "00" }, { "Comoros", "269", "00" }, { "Congo", "242", "00" }, { "Congo, Dem. Rep. of", "243", "00" }, { "Cook Islands", "682", "00" }, { "Costa Rica", "506", "00" }, { "Croatia", "385", "00" }, { "Cuba", "53", "119" }, { "Cyprus", "357", "00" }, { "Czech Republic", "420", "00" }, { "Denmark", "45", "00" }, { "Diego Garcia", "246", "00" }, { "Djibouti", "253", "00" }, { "Dominica", "767", "011" }, { "Dominican Rep.", "809", "011" }, { "Ecuador", "593", "00" }, { "Egypt", "20", "00" }, { "El Salvador", "503", "00" }, { "Equatorial Guinea", "240", "00" }, { "Eritrea", "291", "00" }, { "Estonia", "372", "00" }, { "Ethiopia", "251", "00" }, { "Faeroe Islands", "298", "00" }, { "Falkland Islands", "500", "00" }, { "Fiji Islands", "679", "00" }, { "Finland", "358", "00" }, { "France", "33", "00" }, { "French Antilles", "596", "00" }, { "French Guiana", "594", "00" }, { "French Polynesia", "689", "00" }, { "Gabon", "241", "00" }, { "Gambia", "220", "00" }, { "Georgia", "995", "810" }, { "Germany", "49", "00" }, { "Ghana", "233", "00" }, { "Gibraltar", "350", "00" }, { "Greece", "30", "00" }, { "Greenland", "299", "00" }, { "Grenada", "473", "011" }, { "Guadeloupe", "590", "00" }, { "Guam", "671", "011" }, { "Guantanamo Bay", "5399", "00" }, { "Guatemala", "502", "00" }, { "Guinea", "224", "00" }, { "Guinea Bissau", "245", "00" }, { "Guyana", "592", "001" }, { "Haiti", "509", "00" }, { "Honduras", "504", "00" }, { "Hong Kong", "852", "001" }, { "Hungary", "36", "00" }, { "Iceland", "354", "00" }, { "India", "91", "00" }, { "Indonesia", "62", { "001", "008" } }, { "Iran", "98", "00" }, { "Iraq", "964", "00" }, { "Ireland", "353", "00" }, { "Israel", "972", "00" }, { "Italy", "39", "00" }, { "Ivory Coast", "225", "00" }, { "Jamaica", "876", "011" }, { "Japan", "81", "001" }, { "Jordan", "962", "00" }, { "Kazakhstan", "7", "810" }, { "Kenya", "254", "000" }, { "Kiribati", "686", "00" }, { "Korea, North", "850", "00" }, { "Korea, South", "82", "001" }, { "Kuwait", "965", "00" }, { "Kyrgyzstan", "996", "00" }, { "Laos", "856", "00" }, { "Latvia", "371", "00" }, { "Lebanon", "961", "00" }, { "Lesotho", "266", "00" }, { "Liberia", "231", "00" }, { "Libya", "218", "00" }, { "Liechtenstein", "423", "00" }, { "Lithuania", "370", "00" }, { "Luxembourg", "352", "00" }, { "Macau", "853", "00" }, { "Macedonia", "389", "00" }, { "Madagascar", "261", "00" }, { "Malawi", "265", "00" }, { "Malaysia", "60", "00" }, { "Maldives", "960", "00" }, { "Mali", "223", "00" }, { "Malta", "356", "00" }, { "Mariana Islands", "670", "011" }, { "Marshall Islands", "692", "011" }, { "Martinique", "596", "00" }, { "Mauritania", "222", "00" }, { "Mauritius", "230", "00" }, { "Mayotte Islands", "269", "00" }, { "Mexico", "52", "00" }, { "Micronesia", "691", "011" }, { "Midway Island", "808", "011" }, { "Moldova", "373", "00" }, { "Monaco", "377", "00" }, { "Mongolia", "976", "001" }, { "Montserrat", "664", "011" }, { "Morocco", "212", "00" }, { "Mozambique", "258", "00" }, { "Myanmar (Burma)", "95", "00" }, { "Namibia", "264", "00" }, { "Nauru", "674", "00" }, { "Nepal", "977", "00" }, { "Netherlands", "31", "00" }, { "Netherlands Antilles", "599", "00" }, { "Nevis", "869", "011" }, { "New Caledonia", "687", "00" }, { "New Zealand", "64", "00" }, { "Nicaragua", "505", "00" }, { "Niger", "227", "00" }, { "Nigeria", "234", "009" }, { "Niue", "683", "00" }, { "Norfolk Island", "672", "00" }, { "Norway", "47", "00" }, { "Oman", "968", "00" }, { "Pakistan", "92", "00" }, { "Palau", "680", "011" }, { "Palestine", "970", "00" }, { "Panama", "507", "00" }, { "Papua New Guinea", "675", "05" }, { "Paraguay", "595", "002" }, { "Peru", "51", "00" }, { "Philippines", "63", "00" }, { "Poland", "48", "00" }, { "Portugal", "351", "00" }, { "Puerto Rico", { "787", "939" }, "011" }, { "Qatar", "974", "00" }, { "Reunion Island", "262", "00" }, { "Romania", "40", "00" }, { "Russia", "7", "810" }, { "Rwanda", "250", "00" }, { "St. Helena", "290", "00" }, { "St. Kitts", "869", "011" }, { "St. Lucia", "758", "011" }, { "St. Perre & Miquelon", "508", "00" }, { "St. Vincent", "784", "011" }, { "San Marino", "378", "00" }, { "Sao Tome & Principe", "239", "00" }, { "Saudi Arabia", "966", "00" }, { "Senegal", "221", "00" }, { "Serbia", "381", "99" }, { "Seychelles", "248", "00" }, { "Sierra Leone", "232", "00" }, { "Singapore", "65", "001" }, { "Slovakia", "421", "00" }, { "Slovenia", "386", "00" }, { "Solomon Islands", "677", "00" }, { "Somalia", "252", "00" }, { "South Africa", "27", "09" }, { "Spain", "34", "00" }, { "Sri Lanka", "94", "00" }, { "Sudan", "249", "00" }, { "Suriname", "597", "00" }, { "Swaziland", "268", "00" }, { "Sweden", "46", "00" }, { "Switzerland", "41", "00" }, { "Syria", "963", "00" }, { "Taiwan", "886", "002" }, { "Tajikistan", "992", "810" }, { "Tanzania", "255", "00" }, { "Thailand", "66", "001" }, { "Togo", "228", "00" }, { "Tonga", "676", "00" }, { "Trinidad & Tobago", "868", "011" }, { "Tunisia", "216", "00" }, { "Turkey", "90", "00" }, { "Turkmenistan", "993", "810" }, { "Turks & Caicos", "649", "011" }, { "Tuvalu", "688", "00" }, { "Uganda", "256", "000" }, { "Ukraine", "380", "810" }, { "United Arab Emirates", "971", "00" }, { "United Kingdom", "44", "00" }, { "Uruguay", "598", "00" }, { "USA", "1", "011" }, { "US Virgin Islands", "340", "011" }, { "Uzbekistan", "998", "810" }, { "Vanuatu", "678", "00" }, { "Vatican City", "39", "00" }, { "Venezuela", "58", "00" }, { "Vietnam", "84", "00" }, { "Wake Island", "808", "00" }, { "Wallis & Futuna", "681", "19" }, { "Western Samoa", "685", "00" }, { "Yemen", "967", "00" }, { "Yugoslavia", "381", "99" }, { "Zambia", "260", "00" }, { "Zimbabwe", "263", "00" } }
apache-2.0
kod3r/torch7
Tensor.lua
57
16339
-- additional methods for Storage local Storage = {} -- additional methods for Tensor local Tensor = {} -- types local types = {'Byte', 'Char', 'Short', 'Int', 'Long', 'Float', 'Double'} -- Lua 5.2 compatibility local log10 = math.log10 or function(x) return math.log(x, 10) end -- tostring() functions for Tensor and Storage local function Storage__printformat(self) if self:size() == 0 then return "", nil, 0 end local intMode = true local type = torch.typename(self) -- if type == 'torch.FloatStorage' or type == 'torch.DoubleStorage' then for i=1,self:size() do if self[i] ~= math.ceil(self[i]) then intMode = false break end end -- end local tensor = torch.DoubleTensor(torch.DoubleStorage(self:size()):copy(self), 1, self:size()):abs() local expMin = tensor:min() if expMin ~= 0 then expMin = math.floor(log10(expMin)) + 1 else expMin = 1 end local expMax = tensor:max() if expMax ~= 0 then expMax = math.floor(log10(expMax)) + 1 else expMax = 1 end local format local scale local sz if intMode then if expMax > 9 then format = "%11.4e" sz = 11 else format = "%SZd" sz = expMax + 1 end else if expMax-expMin > 4 then format = "%SZ.4e" sz = 11 if math.abs(expMax) > 99 or math.abs(expMin) > 99 then sz = sz + 1 end else if expMax > 5 or expMax < 0 then format = "%SZ.4f" sz = 7 scale = math.pow(10, expMax-1) else format = "%SZ.4f" if expMax == 0 then sz = 7 else sz = expMax+6 end end end end format = string.gsub(format, 'SZ', sz) if scale == 1 then scale = nil end return format, scale, sz end function Storage.__tostring__(self) local strt = {'\n'} local format,scale = Storage__printformat(self) if format:sub(2,4) == 'nan' then format = '%f' end if scale then table.insert(strt, string.format('%g', scale) .. ' *\n') for i = 1,self:size() do table.insert(strt, string.format(format, self[i]/scale) .. '\n') end else for i = 1,self:size() do table.insert(strt, string.format(format, self[i]) .. '\n') end end table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. self:size() .. ']\n') local str = table.concat(strt) return str end for _,type in ipairs(types) do local metatable = torch.getmetatable('torch.' .. type .. 'Storage') for funcname, func in pairs(Storage) do rawset(metatable, funcname, func) end end local function Tensor__printMatrix(self, indent) local format,scale,sz = Storage__printformat(self:storage()) if format:sub(2,4) == 'nan' then format = '%f' end -- print('format = ' .. format) scale = scale or 1 indent = indent or '' local strt = {indent} local nColumnPerLine = math.floor((80-#indent)/(sz+1)) -- print('sz = ' .. sz .. ' and nColumnPerLine = ' .. nColumnPerLine) local firstColumn = 1 local lastColumn = -1 while firstColumn <= self:size(2) do if firstColumn + nColumnPerLine - 1 <= self:size(2) then lastColumn = firstColumn + nColumnPerLine - 1 else lastColumn = self:size(2) end if nColumnPerLine < self:size(2) then if firstColumn ~= 1 then table.insert(strt, '\n') end table.insert(strt, 'Columns ' .. firstColumn .. ' to ' .. lastColumn .. '\n' .. indent) end if scale ~= 1 then table.insert(strt, string.format('%g', scale) .. ' *\n ' .. indent) end for l=1,self:size(1) do local row = self:select(1, l) for c=firstColumn,lastColumn do table.insert(strt, string.format(format, row[c]/scale)) if c == lastColumn then table.insert(strt, '\n') if l~=self:size(1) then if scale ~= 1 then table.insert(strt, indent .. ' ') else table.insert(strt, indent) end end else table.insert(strt, ' ') end end end firstColumn = lastColumn + 1 end local str = table.concat(strt) return str end local function Tensor__printTensor(self) local counter = torch.LongStorage(self:nDimension()-2) local strt = {''} local finished counter:fill(1) counter[1] = 0 while true do for i=1,self:nDimension()-2 do counter[i] = counter[i] + 1 if counter[i] > self:size(i) then if i == self:nDimension()-2 then finished = true break end counter[i] = 1 else break end end if finished then break end -- print(counter) if #strt > 1 then table.insert(strt, '\n') end table.insert(strt, '(') local tensor = self for i=1,self:nDimension()-2 do tensor = tensor:select(1, counter[i]) table.insert(strt, counter[i] .. ',') end table.insert(strt, '.,.) = \n') table.insert(strt, Tensor__printMatrix(tensor, ' ')) end local str = table.concat(strt) return str end function Tensor.__tostring__(self) local str = '\n' local strt = {''} if self:nDimension() == 0 then table.insert(strt, '[' .. torch.typename(self) .. ' with no dimension]\n') else local tensor = torch.DoubleTensor():resize(self:size()):copy(self) if tensor:nDimension() == 1 then local format,scale,sz = Storage__printformat(tensor:storage()) if format:sub(2,4) == 'nan' then format = '%f' end if scale then table.insert(strt, string.format('%g', scale) .. ' *\n') for i = 1,tensor:size(1) do table.insert(strt, string.format(format, tensor[i]/scale) .. '\n') end else for i = 1,tensor:size(1) do table.insert(strt, string.format(format, tensor[i]) .. '\n') end end table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. tensor:size(1) .. ']\n') elseif tensor:nDimension() == 2 then table.insert(strt, Tensor__printMatrix(tensor)) table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. tensor:size(1) .. 'x' .. tensor:size(2) .. ']\n') else table.insert(strt, Tensor__printTensor(tensor)) table.insert(strt, '[' .. torch.typename(self) .. ' of size ') for i=1,tensor:nDimension() do table.insert(strt, tensor:size(i)) if i ~= tensor:nDimension() then table.insert(strt, 'x') end end table.insert(strt, ']\n') end end local str = table.concat(strt) return str end function Tensor.type(self,type) local current = torch.typename(self) if not type then return current end if type ~= current then local new = torch.getmetatable(type).new() if self:nElement() > 0 then new:resize(self:size()):copy(self) end return new else return self end end function Tensor.typeAs(self,tensor) return self:type(tensor:type()) end function Tensor.byte(self) return self:type('torch.ByteTensor') end function Tensor.char(self) return self:type('torch.CharTensor') end function Tensor.short(self) return self:type('torch.ShortTensor') end function Tensor.int(self) return self:type('torch.IntTensor') end function Tensor.long(self) return self:type('torch.LongTensor') end function Tensor.float(self) return self:type('torch.FloatTensor') end function Tensor.double(self) return self:type('torch.DoubleTensor') end function Tensor.real(self) return self:type(torch.getdefaulttensortype()) end function Tensor.expand(result,tensor,...) -- get sizes local sizes = {...} local t = torch.type(tensor) if (t == 'number' or t == 'torch.LongStorage') then table.insert(sizes,1,tensor) tensor = result result = tensor.new() end -- check type local size if torch.type(sizes[1])=='torch.LongStorage' then size = sizes[1] else size = torch.LongStorage(#sizes) for i,s in ipairs(sizes) do size[i] = s end end -- get dimensions local tensor_dim = tensor:dim() local tensor_stride = tensor:stride() local tensor_size = tensor:size() -- check nb of dimensions if #size ~= tensor:dim() then error('the number of dimensions provided must equal tensor:dim()') end -- create a new geometry for tensor: for i = 1,tensor_dim do if tensor_size[i] == 1 then tensor_size[i] = size[i] tensor_stride[i] = 0 elseif tensor_size[i] ~= size[i] then error('incorrect size: only supporting singleton expansion (size=1)') end end -- create new view, with singleton expansion: result:set(tensor:storage(), tensor:storageOffset(), tensor_size, tensor_stride) return result end torch.expand = Tensor.expand function Tensor.expandAs(result,tensor,template) if template then return result:expand(tensor,template:size()) end return result:expand(tensor:size()) end torch.expandAs = Tensor.expandAs function Tensor.repeatTensor(result,tensor,...) -- get sizes local sizes = {...} local t = torch.type(tensor) if (t == 'number' or t == 'torch.LongStorage') then table.insert(sizes,1,tensor) tensor = result result = tensor.new() end -- if not contiguous, then force the tensor to be contiguous if not tensor:isContiguous() then tensor = tensor:clone() end -- check type local size if torch.type(sizes[1])=='torch.LongStorage' then size = sizes[1] else size = torch.LongStorage(#sizes) for i,s in ipairs(sizes) do size[i] = s end end if size:size() < tensor:dim() then error('Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor') end local xtensor = tensor.new():set(tensor) local xsize = xtensor:size():totable() for i=1,size:size()-tensor:dim() do table.insert(xsize,1,1) end size = torch.DoubleTensor(xsize):cmul(torch.DoubleTensor(size:totable())):long():storage() xtensor:resize(torch.LongStorage(xsize)) result:resize(size) local urtensor = result.new(result) for i=1,xtensor:dim() do urtensor = urtensor:unfold(i,xtensor:size(i),xtensor:size(i)) end for i=1,urtensor:dim()-xtensor:dim() do table.insert(xsize,1,1) end xtensor:resize(torch.LongStorage(xsize)) local xxtensor = xtensor:expandAs(urtensor) urtensor:copy(xxtensor) return result end torch.repeatTensor = Tensor.repeatTensor --- One of the size elements can be -1, --- a new LongStorage is then returned. --- The length of the unspecified dimension --- is infered from the number of remaining elements. local function specifyFully(size, nElements) local nCoveredElements = 1 local remainingDim = nil local sizes = size:totable() for i = 1, #sizes do local wantedDimSize = sizes[i] if wantedDimSize == -1 then if remainingDim then error("Only one of torch.view dimensions can be -1.") end remainingDim = i else nCoveredElements = nCoveredElements * wantedDimSize end end if not remainingDim then return size end assert(nElements % nCoveredElements == 0, "The number of covered elements is not a multiple of all elements.") local copy = torch.LongStorage(sizes) copy[remainingDim] = nElements / nCoveredElements return copy end -- TODO : This should be implemented in TH and and wrapped. function Tensor.view(result, src, ...) local size = ... local view, tensor local function istensor(tensor) return torch.typename(tensor) and torch.typename(tensor):find('torch.*Tensor') end local function isstorage(storage) return torch.typename(storage) and torch.typename(storage) == 'torch.LongStorage' end if istensor(result) and istensor(src) and type(size) == 'number' then size = torch.LongStorage{...} view = result tensor = src elseif istensor(result) and istensor(src) and isstorage(size) then size = size view = result tensor = src elseif istensor(result) and isstorage(src) and size == nil then size = src tensor = result view = tensor.new() elseif istensor(result) and type(src) == 'number' then size = {...} table.insert(size,1,src) size = torch.LongStorage(size) tensor = result view = tensor.new() else local t1 = 'torch.Tensor, torch.Tensor, number [, number ]*' local t2 = 'torch.Tensor, torch.Tensor, torch.LongStorage' local t3 = 'torch.Tensor, torch.LongStorage' local t4 = 'torch.Tensor, number [, number ]*' error(string.format('torch.view, expected (%s) or\n (%s) or\n (%s)\n or (%s)', t1, t2, t3, t4)) end local origNElement = tensor:nElement() size = specifyFully(size, origNElement) assert(tensor:isContiguous(), "expecting a contiguous tensor") view:set(tensor:storage(), tensor:storageOffset(), size) if view:nElement() ~= origNElement then local inputSize = table.concat(tensor:size():totable(), "x") local outputSize = table.concat(size:totable(), "x") error(string.format("Wrong size for view. Input size: %s. Output size: %s", inputSize, outputSize)) end return view end torch.view = Tensor.view function Tensor.viewAs(result, src, template) if template and torch.typename(template) then return result:view(src, template:size()) elseif template == nil then template = src src = result result = src.new() return result:view(src, template:size()) else local t1 = 'torch.Tensor, torch.Tensor, torch.LongStorage' local t2 = 'torch.Tensor, torch.LongStorage' error(string.format('expecting (%s) or (%s)', t1, t2)) end end torch.viewAs = Tensor.viewAs function Tensor.split(result, tensor, splitSize, dim) if torch.type(result) ~= 'table' then dim = splitSize splitSize = tensor tensor = result result = {} else -- empty existing result table before using it for k,v in pairs(result) do result[k] = nil end end dim = dim or 1 local start = 1 while start <= tensor:size(dim) do local size = math.min(splitSize, tensor:size(dim) - start + 1) local split = tensor:narrow(dim, start, size) table.insert(result, split) start = start + size end return result end torch.split = Tensor.split function Tensor.chunk(result, tensor, nChunk, dim) if torch.type(result) ~= 'table' then dim = nChunk nChunk = tensor tensor = result result = {} end dim = dim or 1 local splitSize = math.ceil(tensor:size(dim)/nChunk) return torch.split(result, tensor, splitSize, dim) end torch.chunk = Tensor.chunk function Tensor.totable(tensor) local result = {} if tensor:dim() == 1 then tensor:apply(function(i) table.insert(result, i) end) else for i = 1, tensor:size(1) do table.insert(result, tensor[i]:totable()) end end return result end torch.totable = Tensor.totable function Tensor.permute(tensor, ...) local perm = {...} local nDims = tensor:dim() assert(#perm == nDims, 'Invalid permutation') local j for i, p in ipairs(perm) do if p ~= i and p ~= 0 then j = i repeat assert(0 < perm[j] and perm[j] <= nDims, 'Invalid permutation') tensor = tensor:transpose(j, perm[j]) j, perm[j] = perm[j], 0 until perm[j] == i perm[j] = j end end return tensor end torch.permute = Tensor.permute for _,type in ipairs(types) do local metatable = torch.getmetatable('torch.' .. type .. 'Tensor') for funcname, func in pairs(Tensor) do rawset(metatable, funcname, func) end end
bsd-3-clause
MeGa-TeAm/megabot
plugins/inpm.lua
59
3138
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
artynet/luci
modules/luci-base/luasrc/cbi.lua
9
43526
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local dispatcher = require("luci.dispatcher") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/etc/luci-uploads/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node.index = k node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false local path = "%s/%s" %{ self.uci:get_confdir(), self.config } if fs.stat(path, "type") ~= "reg" then fs.writefile(path, "") end local ok, err = self.uci:load(self.config) if not ok then local url = dispatcher.build_url(unpack(dispatcher.context.request)) local source = self:formvalue("cbi.source") if type(source) == "string" then fs.writefile(path, source:gsub("\r\n", "\n")) ok, err = self.uci:load(self.config) if ok then luci.http.redirect(url) end end self.save = false end if not ok then self.template = "cbi/error" self.error = err self.source = fs.readfile(path) or "" self.pageaction = false end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) or nil end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) if self:formvalue("cbi.skip") then self.state = FORM_SKIP elseif not self.save then self.state = FORM_INVALID elseif not self:submitstate() then self.state = FORM_NODATA end -- Back out early to prevent unauthorized changes on the subsequent parse if self.state ~= nil then return self:state_handler(self.state) end self.readinput = (readinput ~= false) self:_run_hooks("on_parse") Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") local i, config for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then self:_run_hooks("on_before_commit") if self.apply_on_parse == false then for i, config in ipairs(self.parsechain) do self.uci:commit(config) end end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse == true or self.apply_on_parse == false then self.uci:apply(self.apply_on_parse) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED elseif self.changed then self.state = FORM_CHANGED else self.state = FORM_VALID end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node.index = k node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section, noparse) if not self.optional then return end self.optionals[section] = {} local field = nil if not noparse then field = self.map:formvalue("cbi.opt."..self.config.."."..section) end for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.prepare(self) AbstractSection.prepare(self) AbstractSection.parse_optionals(self, self.section, true) end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end function TypedSection.prepare(self) AbstractSection.prepare(self) local i, s for i, s in ipairs(self:cfgsections()) do AbstractSection.parse_optionals(self, s, true) end end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil self.err_invalid = true else name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sids, sid = { }, nil for sid in util.imatch(order) do sids[#sids+1] = sid end if #sids > 0 then self.map.uci:reorder(self.config, sids) self.changed = true end end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, deps) end -- Serialize dependencies function AbstractValue.deplist2json(self, section, deplist) local deps, i, d = { } if type(self.deps) == "table" then for i, d in ipairs(deplist or self.deps) do local a, k, v = { } for k, v in pairs(d) do if k:find("!", 1, true) then a[k] = v elseif k:find(".", 1, true) then a['cbid.%s' % k] = v else a['cbid.%s.%s.%s' %{ self.config, section, k }] = v end end deps[#deps+1] = a end end return util.serialize_json(deps) end -- Serialize choices function AbstractValue.choices(self) if type(self.keylist) == "table" and #self.keylist > 0 then local i, k, v = nil, nil, {} for i, k in ipairs(self.keylist) do v[k] = self.vallist[i] or k end return v end return nil end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if self.alias then self.section.aliased = self.section.aliased or {} self.section.aliased[section] = self.section.aliased[section] or {} self.section.aliased[section][self.alias] = true end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if not self.alias or not self.section.aliased or not self.section.aliased[section] or not self.section.aliased[section][self.alias] then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.alias or self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.alias or self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.alias or self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} self.readonly = nil end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function Value.parse(self, section, novld) if self.readonly then return end AbstractValue.parse(self, section, novld) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section, novld) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled local cvalue = self:cfgvalue(section) local val_err fvalue, val_err = self:validate(fvalue, section) if not fvalue then if not novld then self:add_error(section, "invalid", val_err) end return end if fvalue == self.default and (self.optional or self.rmempty) then self:remove(section) else self:write(section, fvalue) end if (fvalue ~= cvalue) then self.section.changed = true end else self:remove(section) self.section.changed = true end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end function Flag.validate(self, value) return value end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.size = 1 self.widget = "select" self:reset_values() end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} self.deplist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) table.insert(self.deplist, {...}) end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.widget = "checkbox" self.delimiter = " " self:reset_values() end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} self.deplist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self:reset_values() end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end DropDown = class(MultiValue) function DropDown.__init__(self, ...) ListValue.__init__(self, ...) self.template = "cbi/dropdown" self.delimiter = " " end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true self.unsafeupload = false end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) if self.unsafeupload then return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") or self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") else return AbstractValue.formcreated(self, section) or self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") end end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end -- If we have a new value, use it -- otherwise use old value -- deletion should be managed by a separate button object -- unless self.unsafeupload is set in which case if the user -- choose to remove the old file we do so. -- Also, allow to specify (via textbox) a file already on router function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if self.unsafeupload then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil return nil elseif val ~= "" then return val end end val = luci.http.formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox") if val == "" then val = nil end if not self.unsafeupload then if not val then val = self.map:formvalue("cbi.rlf."..section.."."..self.option) end end return val end function FileUpload.remove(self, section) if self.unsafeupload then local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) else return nil end end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
apache-2.0
c4augustus/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/define.lua
43
1317
-- tolua: define class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: define.lua,v 1.2 1999/07/28 22:21:08 celes Exp $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Define class -- Represents a numeric const definition -- The following filds are stored: -- name = constant name classDefine = { name = '', } classDefine.__index = classDefine setmetatable(classDefine,classFeature) -- register define function classDefine:register (pre) if not self:check_public_access() then return end pre = pre or '' output(pre..'tolua_constant(tolua_S,"'..self.lname..'",'..self.name..');') end -- Print method function classDefine:print (ident,close) print(ident.."Define{") print(ident.." name = '"..self.name.."',") print(ident.." lname = '"..self.lname.."',") print(ident.."}"..close) end -- Internal constructor function _Define (t) setmetatable(t,classDefine) t:buildnames() if t.name == '' then error("#invalid define") end append(t) return t end -- Constructor -- Expects a string representing the constant name function Define (n) return _Define{ name = n } end
mit
alikineh/spammer-bot
bot/seedbot.lua
1
9867
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "spam1", "spam2", "spam3", "plugins", "bot_on_off", "broadcast", "admin", "join", "stats", "leave", "invite", "gitpuller", "xy", "spamauto", "spamauto2", "spamauto3", "help" }, sudo_users = {179162978,153862670,186625098},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[ 😐 ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
Daniex0r/project-roleplay-rp
resources/system-real/c_backup_bleepers.lua
1
3989
-- Backup Truck - Beeping Sound (By Cyanide) local soundElement = { } local beepingTrucksArray = -- Removed SAN vehicles because of Fields. { [486] = true, -- Dozer [406] = true, -- Dumper [573] = true, -- Dune [455] = true, -- FlatBed [407] = true, -- FireTruck [427] = true, -- Enforcer [416] = true, -- Ambulance [578] = true, -- DFT [544] = true, -- Firetruck (Ladder) [456] = true, -- Yankee [414] = true, -- Mule [515] = true, -- RoadTrain [403] = true, -- LineRunner [514] = true, -- LineRunner (Tank Commando thing) [525] = true, -- Towtruck [443] = true -- Packer } function isVehicleThatBeeps( vehicleModel ) return beepingTrucksArray[getElementModel( vehicleModel )] end function doBeep() local localPlayer = getLocalPlayer( ) local elementVehicle = getPedOccupiedVehicle ( localPlayer ) if not elementVehicle then if getElementData( localPlayer, "backupbleepers:goingBackwards" ) then setElementData( localPlayer, "backupbleepers:goingBackwards", false ) end return false end if beepingTrucksArray[getElementModel( elementVehicle )] and (isObjectGoingBackwards(elementVehicle, true)) then setElementData( localPlayer, "backupbleepers:goingBackwards", true ) elseif getElementData( localPlayer, "backupbleepers:goingBackwards" ) and not isObjectGoingBackwards(elementVehicle, true) then setElementData( localPlayer, "backupbleepers:goingBackwards", false ) end end addEventHandler( "onClientResourceStart", getResourceRootElement( ), -- getElementRoot() makes it trigger for every loaded resource... function() setTimer( doBeep, 400, 0 ) end ) addEventHandler ( "onClientElementDataChange", getRootElement(), function ( elementData ) if elementData ~= "backupbleepers:goingBackwards" then return false end if not isVehicleThatBeeps( getPedOccupiedVehicle( source ) ) then return false end for idx, i in ipairs(getElementsByType( "player" )) do -- Looping through all players to attach the sound. local elementVehicle = getPedOccupiedVehicle ( i ) if getElementData( i, "backupbleepers:goingBackwards" ) then -- if goingBackwards was set to true. if not soundElement[elementVehicle] then local x, y, z = getElementPosition(elementVehicle) soundElement[elementVehicle] = playSound3D( "TruckBackingUpBeep.mp3", x, y, z, true ) attachElements( soundElement[elementVehicle], elementVehicle ) end elseif not getElementData( i, "backupbleepers:goingBackwards" ) then -- if goingBackwards was set to false. stopSound(soundElement[elementVehicle]) soundElement[elementVehicle] = nil end end end ) function isObjectGoingBackwards( theVehicle, second ) if not theVehicle or not isElement (theVehicle) or not getVehicleOccupant ( theVehicle, 0 ) or not getControlState("brake_reverse") then return false end x, y, z = getElementVelocity ( theVehicle ) z = ( function( a, b, c ) return c end ) ( getElementRotation ( theVehicle ) ) local returnValue = false if x == 0 or y == 0 then return false end local xx, yy, zz = getElementRotation( theVehicle ) if (xx == 90 or yy == 90) or (xx == 180 or yy == 180) or (xx == 270 or yy == 270) or (xx == 0 or yy == 0) then return false end if z > 0 and z < 90 and not (x < 0 and y > 0) then -- Front left --outputDebugString("a x:"..x.." y:"..y.." z:"..z) returnValue = true elseif z > 90 and z < 180 and not (x < 0 and y < 0) then -- Back left --outputDebugString("B x:"..x.." y:"..y.." z:"..z) returnValue = true elseif z > 180 and z < 270 and not (x > 0 and y < 0) then -- Back right --outputDebugString("c x:"..x.." y:"..y.." z:"..z) returnValue = true elseif z > 270 and z < 360 and not (x > 0 and y > 0) then -- Back right --outputDebugString("d x:"..x.." y:"..y.." z:"..z) returnValue = true end if not second then returnValue = isObjectGoingBackwards( theVehicle, true ) end return returnValue end fileDelete("c_backup_bleepers.lua")
gpl-2.0
NamefulTeam/PortoGameJam2015
initial_menu_view.lua
1
1781
-- imports active_screen = require 'active_screen' game_view = require 'game_view' level_select_view = require 'level_select_view' level_list = require 'level_list' function exports() local instance = {} local background = love.graphics.newImage('background/title_background.png') local newGameButton = love.graphics.newImage('initial_menu/new_game.png') local levelSelectButton = love.graphics.newImage('initial_menu/level_select.png') local endGameButton = love.graphics.newImage('initial_menu/exit.png') local newGameX = 470 local newGameY = 300 local newGameWidth = 300 local newGameHeight = 100 local gap = 10 local levelSelectY = newGameY + newGameHeight + gap local endGameY = levelSelectY + newGameHeight + gap function instance:draw() love.graphics.setColor(255,255,255) love.graphics.draw(background, 0, 0) love.graphics.draw(newGameButton, newGameX, newGameY) love.graphics.draw(levelSelectButton, newGameX, levelSelectY) love.graphics.draw(endGameButton, newGameX, endGameY) end function is_menu_option_selected(mouse_x, mouse_y, start_x, start_y) return love.mouse.isDown("l") and mouse_x > start_x and mouse_x <= start_x + newGameWidth and mouse_y > start_y and mouse_y <= start_y + newGameHeight end function instance:update() mouse_x, mouse_y = love.mouse.getPosition() if is_menu_option_selected(mouse_x, mouse_y, newGameX, newGameY) then game_view = require 'game_view' active_screen.set(game_view(level_list.first_level())) return end if is_menu_option_selected(mouse_x, mouse_y, newGameX, levelSelectY) then active_screen.set(level_select_view()) return end if is_menu_option_selected(mouse_x, mouse_y, newGameX, endGameY) then love.event.quit() end end return instance end return exports
mit
stephank/luci
libs/httpclient/luasrc/httpclient/receiver.lua
93
6049
--[[ LuCI - Lua Development Framework Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require "nixio.util" local nixio = require "nixio" local httpc = require "luci.httpclient" local ltn12 = require "luci.ltn12" local print, tonumber, require, unpack = print, tonumber, require, unpack module "luci.httpclient.receiver" local function prepare_fd(target) -- Open fd for appending local oflags = nixio.open_flags("wronly", "creat") local file, code, msg = nixio.open(target, oflags) if not file then return file, code, msg end -- Acquire lock local stat, code, msg = file:lock("tlock") if not stat then return stat, code, msg end file:seek(0, "end") return file end local function splice_async(sock, pipeout, pipein, file, cb) local ssize = 65536 local smode = nixio.splice_flags("move", "more", "nonblock") -- Set pipe non-blocking otherwise we might end in a deadlock local stat, code, msg = pipein:setblocking(false) if stat then stat, code, msg = pipeout:setblocking(false) end if not stat then return stat, code, msg end local pollsock = { {fd=sock, events=nixio.poll_flags("in")} } local pollfile = { {fd=file, events=nixio.poll_flags("out")} } local done local active -- Older splice implementations sometimes don't detect EOS repeat active = false -- Socket -> Pipe repeat nixio.poll(pollsock, 15000) stat, code, msg = nixio.splice(sock, pipeout, ssize, smode) if stat == nil then return stat, code, msg elseif stat == 0 then done = true break elseif stat then active = true end until stat == false -- Pipe -> File repeat nixio.poll(pollfile, 15000) stat, code, msg = nixio.splice(pipein, file, ssize, smode) if stat == nil then return stat, code, msg elseif stat then active = true end until stat == false if cb then cb(file) end if not active then -- We did not splice any data, maybe EOS, fallback to default return false end until done pipein:close() pipeout:close() sock:close() file:close() return true end local function splice_sync(sock, pipeout, pipein, file, cb) local os = require "os" local ssize = 65536 local smode = nixio.splice_flags("move", "more") local stat -- This is probably the only forking http-client ;-) local pid, code, msg = nixio.fork() if not pid then return pid, code, msg elseif pid == 0 then pipein:close() file:close() repeat stat, code = nixio.splice(sock, pipeout, ssize, smode) until not stat or stat == 0 pipeout:close() sock:close() os.exit(stat or code) else pipeout:close() sock:close() repeat stat, code, msg = nixio.splice(pipein, file, ssize, smode) if cb then cb(file) end until not stat or stat == 0 pipein:close() file:close() if not stat then nixio.kill(pid, 15) nixio.wait(pid) return stat, code, msg else pid, msg, code = nixio.wait(pid) if msg == "exited" then if code == 0 then return true else return nil, code, nixio.strerror(code) end else return nil, -0x11, "broken pump" end end end end function request_to_file(uri, target, options, cbs) options = options or {} cbs = cbs or {} options.headers = options.headers or {} local hdr = options.headers local file, code, msg if target then file, code, msg = prepare_fd(target) if not file then return file, code, msg end local off = file:tell() -- Set content range if off > 0 then hdr.Range = hdr.Range or ("bytes=" .. off .. "-") end end local code, resp, buffer, sock = httpc.request_raw(uri, options) if not code then -- No success if file then file:close() end return code, resp, buffer elseif hdr.Range and code ~= 206 then -- We wanted a part but we got the while file sock:close() if file then file:close() end return nil, -4, code, resp elseif not hdr.Range and code ~= 200 then -- We encountered an error sock:close() if file then file:close() end return nil, -4, code, resp end if cbs.on_header then local stat = {cbs.on_header(file, code, resp)} if stat[1] == false then if file then file:close() end sock:close() return unpack(stat) elseif stat[2] then file = file and stat[2] end end if not file then return nil, -5, "no target given" end local chunked = resp.headers["Transfer-Encoding"] == "chunked" local stat -- Write the buffer to file file:writeall(buffer) repeat if not options.splice or not sock:is_socket() or chunked then break end -- This is a plain TCP socket and there is no encoding so we can splice local pipein, pipeout, msg = nixio.pipe() if not pipein then sock:close() file:close() return pipein, pipeout, msg end -- Adjust splice values local ssize = 65536 local smode = nixio.splice_flags("move", "more") -- Splicing 512 bytes should never block on a fresh pipe local stat, code, msg = nixio.splice(sock, pipeout, 512, smode) if stat == nil then break end -- Now do the real splicing local cb = cbs.on_write if options.splice == "asynchronous" then stat, code, msg = splice_async(sock, pipeout, pipein, file, cb) elseif options.splice == "synchronous" then stat, code, msg = splice_sync(sock, pipeout, pipein, file, cb) else break end if stat == false then break end return stat, code, msg until true local src = chunked and httpc.chunksource(sock) or sock:blocksource() local snk = file:sink() if cbs.on_write then src = ltn12.source.chain(src, function(chunk) cbs.on_write(file) return chunk end) end -- Fallback to read/write stat, code, msg = ltn12.pump.all(src, snk) file:close() sock:close() return stat and true, code, msg end
apache-2.0
artynet/luci
applications/luci-app-uhttpd/luasrc/model/cbi/uhttpd/uhttpd.lua
7
9354
-- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com> -- Licensed to the public under the Apache License 2.0. local fs = require("nixio.fs") local m = Map("uhttpd", translate("uHTTPd"), translate("A lightweight single-threaded HTTP(S) server")) local ucs = m:section(TypedSection, "uhttpd", "") ucs.addremove = true ucs.anonymous = false local lhttp = nil local lhttps = nil local cert_file = nil local key_file = nil ucs:tab("general", translate("General Settings")) ucs:tab("server", translate("Full Web Server Settings"), translate("For settings primarily geared to serving more than the web UI")) ucs:tab("advanced", translate("Advanced Settings"), translate("Settings which are either rarely needed or which affect serving the WebUI")) lhttp = ucs:taboption("general", DynamicList, "listen_http", translate("HTTP listeners (address:port)"), translate("Bind to specific interface:port (by specifying interface address")) lhttp.datatype = "list(ipaddrport(1))" function lhttp.validate(self, value, section) local have_https_listener = false local have_http_listener = false if lhttp and lhttp:formvalue(section) and (#(lhttp:formvalue(section)) > 0) then for k, v in pairs(lhttp:formvalue(section)) do if v and (v ~= "") then have_http_listener = true break end end end if lhttps and lhttps:formvalue(section) and (#(lhttps:formvalue(section)) > 0) then for k, v in pairs(lhttps:formvalue(section)) do if v and (v ~= "") then have_https_listener = true break end end end if not (have_http_listener or have_https_listener) then return nil, "must listen on at least one address:port" end return DynamicList.validate(self, value, section) end lhttps = ucs:taboption("general", DynamicList, "listen_https", translate("HTTPS listener (address:port)"), translate("Bind to specific interface:port (by specifying interface address")) lhttps.datatype = "list(ipaddrport(1))" lhttps:depends("cert") lhttps:depends("key") function lhttps.validate(self, value, section) local have_https_listener = false local have_http_listener = false if lhttps and lhttps:formvalue(section) and (#(lhttps:formvalue(section)) > 0) then for k, v in pairs(lhttps:formvalue(section)) do if v and (v ~= "") then have_https_listener = true break end end if have_https_listener and ((not cert_file) or (not cert_file:formvalue(section)) or (cert_file:formvalue(section) == "")) then return nil, "must have certificate when using https" end if have_https_listener and ((not key_file) or (not key_file:formvalue(section)) or (key_file:formvalue(section) == "")) then return nil, "must have key when using https" end end if lhttp and (lhttp:formvalue(section)) and (#lhttp:formvalue(section) > 0) then for k, v in pairs(lhttp:formvalue(section)) do if v and (v ~= "") then have_http_listener = true break end end end if not (have_http_listener or have_https_listener) then return nil, "must listen on at least one address:port" end return DynamicList.validate(self, value, section) end o = ucs:taboption("general", Flag, "redirect_https", translate("Redirect all HTTP to HTTPS")) o.default = o.enabled o.rmempty = false o = ucs:taboption("general", Flag, "rfc1918_filter", translate("Ignore private IPs on public interface"), translate("Prevent access from private (RFC1918) IPs on an interface if it has an public IP address")) o.default = o.enabled o.rmempty = false cert_file = ucs:taboption("general", FileUpload, "cert", translate("HTTPS Certificate (DER Encoded)")) key_file = ucs:taboption("general", FileUpload, "key", translate("HTTPS Private Key (DER Encoded)")) o = ucs:taboption("general", Button, "remove_old", translate("Remove old certificate and key"), translate("uHTTPd will generate a new self-signed certificate using the configuration shown below.")) o.inputstyle = "remove" function o.write(self, section) if cert_file:cfgvalue(section) and fs.access(cert_file:cfgvalue(section)) then fs.unlink(cert_file:cfgvalue(section)) end if key_file:cfgvalue(section) and fs.access(key_file:cfgvalue(section)) then fs.unlink(key_file:cfgvalue(section)) end luci.sys.call("/etc/init.d/uhttpd restart") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "uhttpd")) end o = ucs:taboption("general", Button, "remove_conf", translate("Remove configuration for certificate and key"), translate("This permanently deletes the cert, key, and configuration to use same.")) o.inputstyle = "remove" function o.write(self, section) if cert_file:cfgvalue(section) and fs.access(cert_file:cfgvalue(section)) then fs.unlink(cert_file:cfgvalue(section)) end if key_file:cfgvalue(section) and fs.access(key_file:cfgvalue(section)) then fs.unlink(key_file:cfgvalue(section)) end self.map:del(section, "cert") self.map:del(section, "key") self.map:del(section, "listen_https") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "uhttpd")) end o = ucs:taboption("server", DynamicList, "index_page", translate("Index page(s)"), translate("E.g specify with index.html and index.php when using PHP")) o.optional = true o.placeholder = "index.html" o = ucs:taboption("server", DynamicList, "interpreter", translate("CGI filetype handler"), translate("Interpreter to associate with file endings ('suffix=handler', e.g. '.php=/usr/bin/php-cgi')")) o.optional = true o = ucs:taboption("server", Flag, "no_symlinks", translate("Do not follow symlinks outside document root")) o.optional = true o = ucs:taboption("server", Flag, "no_dirlists", translate("Do not generate directory listings.")) o.default = o.disabled o = ucs:taboption("server", DynamicList, "alias", translate("Aliases"), translate("(/old/path=/new/path) or (just /old/path which becomes /cgi-prefix/old/path)")) o.optional = true o = ucs:taboption("server", Value, "realm", translate("Realm for Basic Auth")) o.optional = true o.placeholder = luci.sys.hostname() or "OpenWrt" local httpconfig = ucs:taboption("server", Value, "config", translate("Config file (e.g. for credentials for Basic Auth)"), translate("Will not use HTTP authentication if not present")) httpconfig.optional = true o = ucs:taboption("server", Value, "error_page", translate("404 Error"), translate("Virtual URL or CGI script to display on status '404 Not Found'. Must begin with '/'")) o.optional = true o = ucs:taboption("advanced", Value, "home", translate("Document root"), translate("Base directory for files to be served")) o.default = "/www" o.datatype = "directory" o = ucs:taboption("advanced", Value, "cgi_prefix", translate("Path prefix for CGI scripts"), translate("CGI is disabled if not present.")) o.optional = true o = ucs:taboption("advanced", Value, "lua_prefix", translate("Virtual path prefix for Lua scripts")) o.placeholder = "/lua" o.optional = true o = ucs:taboption("advanced", Value, "lua_handler", translate("Full real path to handler for Lua scripts"), translate("Embedded Lua interpreter is disabled if not present.")) o.optional = true o = ucs:taboption("advanced", Value, "ubus_prefix", translate("Virtual path prefix for ubus via JSON-RPC integration"), translate("ubus integration is disabled if not present")) o.optional = true o = ucs:taboption("advanced", Value, "ubus_socket", translate("Override path for ubus socket")) o.optional = true o = ucs:taboption("advanced", Flag, "ubus_cors", translate("Enable JSON-RPC Cross-Origin Resource Support")) o.default = o.disabled o.optional = true o = ucs:taboption("advanced", Flag, "no_ubusauth", translate("Disable JSON-RPC authorization via ubus session API")) o.optional= true o.default = o.disabled o = ucs:taboption("advanced", Value, "script_timeout", translate("Maximum wait time for Lua, CGI, or ubus execution")) o.placeholder = 60 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "network_timeout", translate("Maximum wait time for network activity")) o.placeholder = 30 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "http_keepalive", translate("Connection reuse")) o.placeholder = 20 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "tcp_keepalive", translate("TCP Keepalive")) o.optional = true o.datatype = "uinteger" o.default = 1 o = ucs:taboption("advanced", Value, "max_connections", translate("Maximum number of connections")) o.optional = true o.datatype = "uinteger" o = ucs:taboption("advanced", Value, "max_requests", translate("Maximum number of script requests")) o.optional = true o.datatype = "uinteger" local s = m:section(TypedSection, "cert", translate("uHTTPd Self-signed Certificate Parameters")) s.template = "cbi/tsection" s.anonymous = true o = s:option(Value, "days", translate("Valid for # of Days")) o.default = 730 o.datatype = "uinteger" o = s:option(Value, "bits", translate("Length of key in bits")) o.default = 2048 o.datatype = "min(1024)" o = s:option(Value, "commonname", translate("Server Hostname"), translate("a.k.a CommonName")) o.default = luci.sys.hostname() o = s:option(Value, "country", translate("Country")) o.default = "ZZ" o = s:option(Value, "state", translate("State")) o.default = "Unknown" o = s:option(Value, "location", translate("Location")) o.default = "Unknown" return m
apache-2.0
marshmellow42/proxmark3
client/scripts/ndef_dump.lua
12
7084
-- Ability to read what card is there local getopt = require('getopt') local cmds = require('commands') local taglib = require('taglib') local desc = [[This script will automatically recognize and dump full content of a NFC NDEF Initialized tag; non-initialized tags will be ignored. It also write the dump to an eml-file <uid>.eml. (The difference between an .eml-file and a .bin-file is that the eml file contains ASCII representation of the hex-data, with linebreaks between 'rows'. A .bin-file contains the raw data, but when saving into that for, we lose the infromation about how the memory is structured. For example: 24 bytes could be 6 blocks of 4 bytes, or vice versa. Therefore, the .eml is better to use file when saving dumps.) Arguments: -d debug logging on -h this help ]] local example = "script run xxx" local author = "Martin Holst Swende & Asper" --- -- PrintAndLog function prlog(...) -- TODO; replace this with a call to the proper PrintAndLog print(...) end --- -- This is only meant to be used when errors occur function oops(err) prlog("ERROR: ",err) return nil,err end -- Perhaps this will be moved to a separate library at one point local utils = { --- Writes an eml-file. -- @param uid - the uid of the tag. Used in filename -- @param blockData. Assumed to be on the format {'\0\1\2\3,'\b\e\e\f' ..., -- that is, blockData[row] contains a string with the actual data, not ascii hex representation -- return filename if all went well, -- @reurn nil, error message if unsuccessfull writeDumpFile = function(uid, blockData) local destination = string.format("%s.eml", uid) local file = io.open(destination, "w") if file == nil then return nil, string.format("Could not write to file %s", destination) end local rowlen = string.len(blockData[1]) for i,block in ipairs(blockData) do if rowlen ~= string.len(block) then prlog(string.format("WARNING: Dumpdata seems corrupted, line %d was not the same length as line 1",i)) end local formatString = string.format("H%d", string.len(block)) local _,hex = bin.unpack(formatString,block) file:write(hex.."\n") end file:close() return destination end, } --- -- Usage help function help() prlog(desc) prlog("Example usage") prlog(example) end function debug(...) if DEBUG then prlog("debug:", ...) end end local function show(data) if DEBUG then local formatString = ("H%d"):format(string.len(data)) local _,hexdata = bin.unpack(formatString, data) debug("Hexdata" , hexdata) end end --- Fire up a connection with a tag, return uid -- @return UID if successfull -- @return nil, errormessage if unsuccessfull local function open() debug("Opening connection") core.clearCommandBuffer() local x = string.format("hf 14a raw -r -p -s") debug(x) core.console(x) debug("done") data, err = waitCmd(true) if err then return oops(err) end show(data) local formatString = ("H%d"):format(string.len(data)) local _,uid = bin.unpack(formatString, data) return uid end --- Shut down tag communication -- return no return values local function close() debug("Closing connection") core.clearCommandBuffer() local x = string.format("hf 14a raw -r") debug(x) core.console(x) debug("done") --data, err = waitCmd(true) --data, err = waitCmd(false) end ---_ Gets data from a block -- @return {block, block+1, block+2, block+3} if successfull -- @return nil, errormessage if unsuccessfull local function getBlock(block) local data, err core.clearCommandBuffer() local x = string.format("hf 14a raw -r -c -p 30 %02x", block) debug(x) core.console(x) debug("done") -- By now, there should be an ACK waiting from the device, since -- we used the -r flag (don't read response). data, err = waitCmd(false) if err then return oops(err) end show(data) if string.len(data) < 18 then return nil, ("Expected at least 18 bytes, got %d - this tag is not NDEF-compliant"):format(string.len(data)) end -- Now, parse out the block data -- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155 -- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC b0 = string.sub(data,1,4) b1 = string.sub(data,5,8) b2 = string.sub(data,9,12) b3 = string.sub(data,13,16) return {b0,b1,b2,b3} end --- This function is a lua-implementation of -- cmdhf14a.c:waitCmd(uint8_t iSelect) function waitCmd(iSelect) local response = core.WaitForResponseTimeout(cmds.CMD_ACK,1000) if response then local count,cmd,arg0,arg1,arg2 = bin.unpack('LLLL',response) local iLen = arg0 if iSelect then iLen = arg1 end debug(("Received %i octets (arg0:%d, arg1:%d)"):format(iLen, arg0, arg1)) if iLen == 0 then return nil, "No response from tag" end local recv = string.sub(response,count, iLen+count-1) return recv end return nil, "No response from device" end local function main( args) debug("script started") local err, data, data2,k,v,i -- Read the parameters for o, a in getopt.getopt(args, 'hd') do if o == "h" then help() return end if o == "d" then DEBUG = true end end -- Info contained within the tag (block 0 example) -- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155 -- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC -- MM?? ???? ???? ???? ???? ???? NNVV SS?? ---- -- M = Manufacturer info -- N = NDEF-Structure-Compliant (if value is E1) -- V = NFC Forum Specification version (if 10 = v1.0) -- First, 'connect' (fire up the field) and get the uid local uidHexstr = open() -- First, get blockt 3 byte 2 local blocks, err = getBlock(0) if err then return oops(err) end -- Block 3 contains number of blocks local b3chars = {string.byte(blocks[4], 1,4)} local numBlocks = b3chars[3] * 2 + 6 prlog("Number of blocks:", numBlocks) -- NDEF compliant? if b3chars[1] ~= 0xE1 then return oops("This tag is not NDEF-Compliant") end local ndefVersion = b3chars[2] -- Block 1, byte 1 contains manufacturer info local bl1_b1 = string.byte(blocks[1], 1) local manufacturer = taglib.lookupManufacturer(bl1_b1) -- Reuse existing info local blockData = {blocks[1],blocks[2],blocks[3],blocks[4]} --[[ Due to the infineon my-d move bug (if I send 30 0F i receive block0f+block00+block01+block02 insted of block0f+block10+block11+block12) the only way to avoid this is to send the read command as many times as block numbers removing bytes from 5 to 18 from each answer. --]] prlog("Dumping data...please wait") for i=4,numBlocks-1,1 do blocks, err = getBlock(i) if err then return oops(err) end table.insert(blockData,blocks[1]) end -- Deactivate field close() -- Print results prlog(string.format("Tag manufacturer: %s", manufacturer)) prlog(string.format("Tag UID: %s", uidHexstr)) prlog(string.format("Tag NDEF version: 0x%02x", ndefVersion)) for k,v in ipairs(blockData) do prlog(string.format("Block %02x: %02x %02x %02x %02x",k-1, string.byte(v, 1,4))) end local filename, err = utils.writeDumpFile(uidHexstr, blockData) if err then return oops(err) end prlog(string.format("Dumped data into %s", filename)) end main(args)
gpl-2.0
cdeng/webscript.io
bestbuy/bestbuy.lua
1
1238
-- -- Check specific product in store pick up availability at nearby BestBuy stores. -- -- sku: Product SKU number. -- zipcode: Your zip code. -- api: BBYOPEN API key ( If you don't have, register one from https://remix.mashery.com/member/register ) -- mile: Default 50 miles; Location must be within 50 miles of a Best Buy store. -- local sku = '1755302' local zipcode = '12345' local api = 'PleaseReplaceMeWithYourOwnAPIKey' local mile = '50' local underscore = require 'underscore' local response = http.request { url = 'http://api.remix.bestbuy.com/v1/stores(area(' .. zipcode .. ',' .. mile .. '))+products(sku=' .. sku .. ')?format=json&apiKey=' .. api .. '' } local data = json.parse(response.content) if #data.stores > 0 then local store = underscore.detect(data.stores, function(store) local product = underscore.detect(store.products, function(product) if product.inStoreAvailability == true then log('SKU ' .. sku .. ' that you are tracking is available at ' .. store.name .. '.') alert.email('SKU ' .. sku .. ' that you are tracking is available at ' .. store.name .. '.') else log('SKU ' .. sku .. ' is not available at any Best Buy location in your area.') end end) end) end
mit
AVGP/gabble
node_modules/node-xmpp-client/test/resources/mod_websocket.lua
4
11956
-- Prosody IM -- Copyright (C) 2012 Florian Zeitz -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); local add_filter = require "util.filters".add_filter; local sha1 = require "util.hashes".sha1; local base64 = require "util.encodings".base64.encode; local softreq = require "util.dependencies".softreq; local st = require "util.stanza"; local parse_xml = require "util.xml".parse; local portmanager = require "core.portmanager"; local sm_destroy_session = sessionmanager.destroy_session; local log = module._log; local bit; pcall(function() bit = require"bit"; end); bit = bit or softreq"bit32" if not bit then module:log("error", "No bit module found. Either LuaJIT 2, lua-bitop or Lua 5.2 is required"); end local band = bit.band; local bxor = bit.bxor; local rshift = bit.rshift; local t_concat = table.concat; local s_byte = string.byte; local s_char= string.char; local consider_websocket_secure = module:get_option_boolean("consider_websocket_secure"); local cross_domain = module:get_option("cross_domain_websocket"); if cross_domain then if cross_domain == true then cross_domain = "*"; elseif type(cross_domain) == "table" then cross_domain = t_concat(cross_domain, ", "); end if type(cross_domain) ~= "string" then cross_domain = nil; end end local xmlns_framing = "urn:ietf:params:xml:ns:xmpp-framing"; local xmlns_streams = "http://etherx.jabber.org/streams"; local xmlns_client = "jabber:client"; local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'}; module:depends("c2s") local sessions = module:shared("c2s/sessions"); local c2s_listener = portmanager.get_service("c2s").listener; -- Websocket helpers local function parse_frame(frame) local result = {}; local pos = 1; local length_bytes = 0; local tmp_byte; if #frame < 2 then return; end tmp_byte = s_byte(frame, pos); result.FIN = band(tmp_byte, 0x80) > 0; result.RSV1 = band(tmp_byte, 0x40) > 0; result.RSV2 = band(tmp_byte, 0x20) > 0; result.RSV3 = band(tmp_byte, 0x10) > 0; result.opcode = band(tmp_byte, 0x0F); pos = pos + 1; tmp_byte = s_byte(frame, pos); result.MASK = band(tmp_byte, 0x80) > 0; result.length = band(tmp_byte, 0x7F); if result.length == 126 then length_bytes = 2; result.length = 0; elseif result.length == 127 then length_bytes = 8; result.length = 0; end if #frame < (2 + length_bytes) then return; end for i = 1, length_bytes do pos = pos + 1; result.length = result.length * 256 + s_byte(frame, pos); end if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end if result.MASK then local counter = 0; local data = {}; local key = {s_byte(frame, pos+1), s_byte(frame, pos+2), s_byte(frame, pos+3), s_byte(frame, pos+4)} result.key = key; pos = pos + 5; for i = pos, pos + result.length - 1 do data[#data+1] = s_char(bxor(key[counter+1], s_byte(frame, i))); counter = (counter + 1) % 4; end result.data = t_concat(data, ""); else result.data = frame:sub(pos + 1, pos + result.length); end return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length; end local function build_frame(desc) local length; local result = {}; local data = desc.data or ""; result[#result+1] = s_char(0x80 * (desc.FIN and 1 or 0) + desc.opcode); length = #data; if length <= 125 then -- 7-bit length result[#result+1] = s_char(length); elseif length <= 0xFFFF then -- 2-byte length result[#result+1] = s_char(126); result[#result+1] = s_char(rshift(length, 8)) .. s_char(length%0x100); else -- 8-byte length result[#result+1] = s_char(127); local length_bytes = {}; for i = 8, 1, -1 do length_bytes[i] = s_char(length % 0x100); length = rshift(length, 8); end result[#result+1] = t_concat(length_bytes, ""); end result[#result+1] = data; return t_concat(result, ""); end --- Session methods local function session_open_stream(session) local attr = { xmlns = xmlns_framing, version = "1.0", id = session.streamid or "", from = session.host }; session.send(st.stanza("open", attr)); end local function session_close(session, reason) local log = session.log or log; if session.conn then if session.notopen then session:open_stream(); end if reason then -- nil == no err, initiated by us, false == initiated by client local stream_error = st.stanza("stream:error"); if type(reason) == "string" then -- assume stream error stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }); elseif type(reason) == "table" then if reason.condition then stream_error:tag(reason.condition, stream_xmlns_attr):up(); if reason.text then stream_error:tag("text", stream_xmlns_attr):text(reason.text):up(); end if reason.extra then stream_error:add_child(reason.extra); end elseif reason.name then -- a stanza stream_error = reason; end end log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stream_error)); session.send(stream_error); end session.send(st.stanza("close", { xmlns = xmlns_framing })); function session.send() return false; end local reason = (reason and (reason.name or reason.text or reason.condition)) or reason; session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed"); -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote local conn = session.conn; if reason == nil and not session.notopen and session.type == "c2s" then -- Grace time to process data from authenticated cleanly-closed stream add_task(stream_close_timeout, function () if not session.destroyed then session.log("warn", "Failed to receive a stream close response, closing connection anyway..."); sm_destroy_session(session, reason); -- Sends close with code 1000 and message "Stream closed" local data = s_char(0x03) .. s_char(0xe8) .. "Stream closed"; conn:write(build_frame({opcode = 0x8, FIN = true, data = data})); conn:close(); end end); else sm_destroy_session(session, reason); -- Sends close with code 1000 and message "Stream closed" local data = s_char(0x03) .. s_char(0xe8) .. "Stream closed"; conn:write(build_frame({opcode = 0x8, FIN = true, data = data})); conn:close(); end end end --- Filter stuff local function filter_open_close(data) if not data:find(xmlns_framing, 1, true) then return data; end local oc = parse_xml(data); if not oc then return data; end if oc.attr.xmlns ~= xmlns_framing then return data; end if oc.name == "close" then return "</stream:stream>"; end if oc.name == "open" then oc.name = "stream:stream"; oc.attr.xmlns = nil; oc.attr["xmlns:stream"] = xmlns_streams; return oc:top_tag(); end return data; end function handle_request(event, path) local request, response = event.request, event.response; local conn = response.conn; if not request.headers.sec_websocket_key then response.headers.content_type = "text/html"; return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body> <p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p> </body></html>]]; end local wants_xmpp = false; (request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto) if proto == "xmpp" then wants_xmpp = true; end end); if not wants_xmpp then return 501; end local function websocket_close(code, message) local data = s_char(rshift(code, 8)) .. s_char(code%0x100) .. message; conn:write(build_frame({opcode = 0x8, FIN = true, data = data})); conn:close(); end local dataBuffer; local function handle_frame(frame) local opcode = frame.opcode; local length = frame.length; module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data); -- Error cases if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero websocket_close(1002, "Reserved bits not zero"); return false; end if opcode == 0x8 then if length == 1 then websocket_close(1002, "Close frame with payload, but too short for status code"); return false; elseif length >= 2 then local status_code = s_byte(frame.data, 1) * 256 + s_byte(frame.data, 2) if status_code < 1000 then websocket_close(1002, "Closed with invalid status code"); return false; elseif ((status_code > 1003 and status_code < 1007) or status_code > 1011) and status_code < 3000 then websocket_close(1002, "Closed with reserved status code"); return false; end end end if opcode >= 0x8 then if length > 125 then -- Control frame with too much payload websocket_close(1002, "Payload too large"); return false; end if not frame.FIN then -- Fragmented control frame websocket_close(1002, "Fragmented control frame"); return false; end end if (opcode > 0x2 and opcode < 0x8) or (opcode > 0xA) then websocket_close(1002, "Reserved opcode"); return false; end if opcode == 0x0 and not dataBuffer then websocket_close(1002, "Unexpected continuation frame"); return false; end if (opcode == 0x1 or opcode == 0x2) and dataBuffer then websocket_close(1002, "Continuation frame expected"); return false; end -- Valid cases if opcode == 0x0 then -- Continuation frame dataBuffer[#dataBuffer+1] = frame.data; elseif opcode == 0x1 then -- Text frame dataBuffer = {frame.data}; elseif opcode == 0x2 then -- Binary frame websocket_close(1003, "Only text frames are supported"); return; elseif opcode == 0x8 then -- Close request websocket_close(1000, "Goodbye"); return; elseif opcode == 0x9 then -- Ping frame frame.opcode = 0xA; conn:write(build_frame(frame)); return ""; elseif opcode == 0xA then -- Pong frame module:log("warn", "Received unexpected pong frame: " .. tostring(frame.data)); return ""; else log("warn", "Received frame with unsupported opcode %i", opcode); return ""; end if frame.FIN then local data = t_concat(dataBuffer, ""); dataBuffer = nil; return data; end return ""; end conn:setlistener(c2s_listener); c2s_listener.onconnect(conn); local session = sessions[conn]; session.secure = consider_websocket_secure or session.secure; session.open_stream = session_open_stream; session.close = session_close; local frameBuffer = ""; add_filter(session, "bytes/in", function(data) local cache = {}; frameBuffer = frameBuffer .. data; local frame, length = parse_frame(frameBuffer); while frame do frameBuffer = frameBuffer:sub(length + 1); local result = handle_frame(frame); if not result then return; end cache[#cache+1] = filter_open_close(result); frame, length = parse_frame(frameBuffer); end return t_concat(cache, ""); end); add_filter(session, "bytes/out", function(data) return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)}); end); add_filter(session, "stanzas/out", function(stanza) local attr = stanza.attr; attr.xmlns = attr.xmlns or xmlns_client; if stanza.name:find("^stream:") then attr["xmlns:stream"] = attr["xmlns:stream"] or xmlns_streams; end return stanza; end); response.status_code = 101; response.headers.upgrade = "websocket"; response.headers.connection = "Upgrade"; response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); response.headers.sec_webSocket_protocol = "xmpp"; response.headers.access_control_allow_origin = cross_domain; return ""; end function module.add_host(module) module:depends("http"); module:provides("http", { name = "websocket"; default_path = "xmpp-websocket"; route = { ["GET"] = handle_request; ["GET /"] = handle_request; }; }); end
mit
BlubBlab/rom-bot
classes/bankitem.lua
1
1381
include("item.lua"); CBankItem = class(CItem, function( self, slot ) self.Location = "bank" self.SlotNumber = slot self.BagId = slot self.Available = false if ( self.BagId ~= nil and self.BagId ~= 0 ) then self:update(); end; end ); function CBankItem:update() self.Address = addresses.staticBankbase + ( (self.BagId - 1) * 68 ); -- Check if available if self.BagId > 40 and self.BagId <= 200 then self.Available = memoryReadUInt(getProc(), addresses.rentBankBase + math.floor((self.BagId - 41)/40) * 4) ~= 0xFFFFFFFF else self.Available = true end CItem.update(self) if( settings.profile.options.DEBUG_INV ) then if ( self.Empty ) then printf( "Slot: %d <EMPTY>.\n", self.SlotNumber ); else local _color = cli.white; printf( "Slot: %d\tcontains: %d\t (%d) ", self.SlotNumber, self.ItemCount, self.Id ); if ( self.Quality == 1 ) then _color = cli.lightgreen; elseif ( self.Quality == 2 ) then _color = cli.blue; elseif ( self.Quality == 3 ) then _color = cli.purple; elseif ( self.Quality == 4 ) then _color = cli.yellow; elseif ( self.Quality == 5 ) then _color = cli.forestgreen; end; cprintf( _color, "[%s]", self.Name ); printf( "\tDura: %d\n", self.Durability ); end; end; end function CBankItem:use() self:moveTo("bags") end
mit
jiuaiwo1314/skynet
lualib/http/httpc.lua
42
2906
local socket = require "http.sockethelper" local url = require "http.url" local internal = require "http.internal" local string = string local table = table local httpc = {} local function request(fd, method, host, url, recvheader, header, content) local read = socket.readfunc(fd) local write = socket.writefunc(fd) local header_content = "" if header then if not header.host then header.host = host end for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end else header_content = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n%s", method, url, header_content, #content, content) write(data) else local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content) write(request_header) end local tmpline = {} local body = internal.recvheader(read, tmpline, "") if not body then error(socket.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = internal.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = internal.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end else body = nil end end return code, body end function httpc.request(method, host, url, recvheader, header, content) local hostname, port = host:match"([^:]+):?(%d*)$" if port == "" then port = 80 else port = tonumber(port) end local fd = socket.connect(hostname, port) local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content) socket.close(fd) if ok then return statuscode, body else error(statuscode) end end function httpc.get(...) return httpc.request("GET", ...) end local function escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02X", string.byte(c)) end)) end function httpc.post(host, url, form, recvheader) local header = { ["content-type"] = "application/x-www-form-urlencoded" } local body = {} for k,v in pairs(form) do table.insert(body, string.format("%s=%s",escape(k),escape(v))) end return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&")) end return httpc
mit
mattjw79/luaLibs
tests/test_emailaddress.lua
1
1680
local lu = require 'luaunit' local emailaddress = require 'lib.emailaddress' test_emailaddress = {} function test_emailaddress:test_full_rcpt_to() local email = emailaddress:new('RCPT TO: User One <uone@example.com>') lu.assertEquals(email.localpart, 'uone') lu.assertEquals(email.domain, 'example.com') lu.assertEquals(email.full, 'uone@example.com') end function test_emailaddress:test_full_rcpt_to_with_quoted_address() local email = emailaddress:new('RCPT TO: User One <"user one"@example.com>') lu.assertEquals(email.localpart, 'user one') lu.assertEquals(email.domain, 'example.com') lu.assertEquals(email.full, '"user one"@example.com') end function test_emailaddress:test_full_rcpt_to_with_single_quoted_address() local email = emailaddress:new("RCPT TO: User One <'user one'@example.com>") lu.assertEquals(email.localpart, 'user one') lu.assertEquals(email.domain, 'example.com') lu.assertEquals(email.full, '"user one"@example.com') end function test_emailaddress:test_bracketed_rcpt_to() local email = emailaddress:new('RCPT TO: <uone@example.com>') lu.assertEquals(email.localpart, 'uone') lu.assertEquals(email.domain, 'example.com') lu.assertEquals(email.full, 'uone@example.com') end function test_emailaddress:test_min_rcpt_to() local email = emailaddress:new('RCPT TO: uone@example.com') lu.assertEquals(email.localpart, 'uone') lu.assertEquals(email.domain, 'example.com') lu.assertEquals(email.full, 'uone@example.com') end function test_emailaddress:test_tostring() local email = emailaddress:new('RCPT TO: User One <uone@example.com>') lu.assertEquals(tostring(email), 'emailaddress: uone@example.com') end
mit
ahmedcharles/Mudlet
src/mudlet-lua/lua/geyser/GeyserColor.lua
3
5960
-------------------------------------- -- -- -- The Geyser Layout Manager by guy -- -- -- -------------------------------------- Geyser.Color = {} --- Converts color to 3 hex values as a string, no alpha, css style -- @return The color formatted as a hex string, as accepted by html/css function Geyser.Color.hex (r,g,b) return string.format("#%02x%02x%02x", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 hex values as a string, with alpha, css style -- @return The color formatted as a hex string, as accepted by html/css function Geyser.Color.hexa (r,g,b,a) return string.format("#%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a)) end --- Converts color to 3 hex values as a string, no alpha, hecho style -- @return The color formatted as a hex string, as accepted by hecho function Geyser.Color.hhex (r,g,b) return string.format("|c%02x%02x%02x", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 hex values as a string, with alpha, hecho style -- @return The color formatted as a hex string, as accepted by hecho function Geyser.Color.hhexa (r,g,b,a) return string.format("|c%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a)) end --- Converts color to 3 decimal values as a string, no alpha, decho style -- @return The color formatted as a decho() style string function Geyser.Color.hdec (r,g,b) return string.format("<%d,%d,%d>", Geyser.Color.parse(r, g, b)) end --- Converts color to 4 decimal values as a string, with alpha, decho style -- @return The color formatted as a decho() style string function Geyser.Color.hdeca (r,g,b,a) return string.format("<%d,%d,%d,%d>", Geyser.Color.parse(r, g, b, a)) end --- Returns 4 color components from (nearly any) acceptable format. Colors can be -- specified in two ways. First: as a single word in english ("purple") or -- hex ("#AA00FF", "|cAA00FF", or "0xAA00FF") or decimal ("<190,0,255>"). If -- the hex or decimal representations contain a fourth element then alpha is -- set too - otherwise alpha can't be set this way. Second: by passing in -- distinct components as unsigned integers (e.g. 23 or 0xA7). When using the -- second way, at least three values must be passed. If only three are -- passed, then alpha is 255. Third: by passing in a table that has explicit -- values for some, all or none of the keys r,g,b, and a. -- @param red Either a valid string representation or the red component. -- @param green The green component. -- @param blue The blue component. -- @param alpha The alpha component. function Geyser.Color.parse(red, green, blue, alpha) local r,g,b,a = 0,0,0,255 -- have to have something to set, else can't do anything! if not red then return nil, "No color supplied" end -- function to return next number local next_num = nil local base = 10 -- assigns all the colors, used after we figure out how the color is -- represented as a string local assign_colors = function () r = tonumber(next_num(), base) g = tonumber(next_num(), base) b = tonumber(next_num(), base) local has_a = next_num() if has_a then a = tonumber(has_a, base) end end -- Check if we were passed a string or table that needs to be parsed, i.e., -- there is only a valid red value, and other params are nil. if not green or not blue then if type(red) == "table" then -- Here just copy over the appropriate values with sensible defaults r = red.r or 127 g = red.g or 127 b = red.b or 127 a = red.a or 255 return r,g,b,a elseif type(red) == "string" then -- first case is a hex string, where first char is '#' if string.find(red, "^#") then local pure_hex = string.sub(red, 2) -- strip format char next_num = string.gmatch(pure_hex, "%w%w") base = 16 -- second case is a hex string, where first chars are '|c' or '0x' elseif string.find(red, "^[|0][cx]") then local pure_hex = string.sub(red, 3) -- strip format chars next_num = string.gmatch(pure_hex, "%w%w") base = 16 -- third case is a decimal string, of the format "<dd,dd,dd>" elseif string.find(red, "^<") then next_num = string.gmatch(red, "%d+") -- fourth case is a named string elseif color_table[red] then local i = 0 local n = #color_table[red] next_num = function () -- create a simple iterator i = i + 1 if i <= n then return color_table[red][i] else return nil end end else -- finally, no matches, do nothing return end end else -- Otherwise we weren't passed a complete string, but instead discrete -- components as either decimal or hex -- Yes, this is a little silly to do this way, but it fits with the -- rest of the parsing going on... local i = 0 next_num = function () i = i + 1 if i == 1 then return red elseif i == 2 then return green elseif i == 3 then return blue elseif i == 4 then return alpha else return nil end end end assign_colors() return r,g,b,a end --- Applies colors to a window drawing from defaults and overridden values. -- @param cons The window to apply colors to function Geyser.Color.applyColors(cons) cons:setFgColor(cons.fgColor) cons:setBgColor(cons.bgColor) cons:setColor(cons.color) end
gpl-2.0
moltafet35/ssssis
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
dxmgame/dxm-cocos-demo
src/lua-coin-tree/Resources/src/cocos/cocostudio/DeprecatedCocoStudioFunc.lua
61
3456
if nil == ccs then return end --tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of GUIReader will be deprecated begin local GUIReaderDeprecated = { } function GUIReaderDeprecated.shareReader() deprecatedTip("GUIReader:shareReader","ccs.GUIReader:getInstance") return ccs.GUIReader:getInstance() end GUIReader.shareReader = GUIReaderDeprecated.shareReader function GUIReaderDeprecated.purgeGUIReader() deprecatedTip("GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end GUIReader.purgeGUIReader = GUIReaderDeprecated.purgeGUIReader --functions of GUIReader will be deprecated end --functions of SceneReader will be deprecated begin local SceneReaderDeprecated = { } function SceneReaderDeprecated.sharedSceneReader() deprecatedTip("SceneReader:sharedSceneReader","ccs.SceneReader:getInstance") return ccs.SceneReader:getInstance() end SceneReader.sharedSceneReader = SceneReaderDeprecated.sharedSceneReader function SceneReaderDeprecated.purgeSceneReader(self) deprecatedTip("SceneReader:purgeSceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end SceneReader.purgeSceneReader = SceneReaderDeprecated.purgeSceneReader --functions of SceneReader will be deprecated end --functions of ccs.GUIReader will be deprecated begin local CCSGUIReaderDeprecated = { } function CCSGUIReaderDeprecated.purgeGUIReader() deprecatedTip("ccs.GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end ccs.GUIReader.purgeGUIReader = CCSGUIReaderDeprecated.purgeGUIReader --functions of ccs.GUIReader will be deprecated end --functions of ccs.ActionManagerEx will be deprecated begin local CCSActionManagerExDeprecated = { } function CCSActionManagerExDeprecated.destroyActionManager() deprecatedTip("ccs.ActionManagerEx:destroyActionManager","ccs.ActionManagerEx:destroyInstance") return ccs.ActionManagerEx:destroyInstance() end ccs.ActionManagerEx.destroyActionManager = CCSActionManagerExDeprecated.destroyActionManager --functions of ccs.ActionManagerEx will be deprecated end --functions of ccs.SceneReader will be deprecated begin local CCSSceneReaderDeprecated = { } function CCSSceneReaderDeprecated.destroySceneReader(self) deprecatedTip("ccs.SceneReader:destroySceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end ccs.SceneReader.destroySceneReader = CCSSceneReaderDeprecated.destroySceneReader --functions of ccs.SceneReader will be deprecated end --functions of CCArmatureDataManager will be deprecated begin local CCArmatureDataManagerDeprecated = { } function CCArmatureDataManagerDeprecated.sharedArmatureDataManager() deprecatedTip("CCArmatureDataManager:sharedArmatureDataManager","ccs.ArmatureDataManager:getInstance") return ccs.ArmatureDataManager:getInstance() end CCArmatureDataManager.sharedArmatureDataManager = CCArmatureDataManagerDeprecated.sharedArmatureDataManager function CCArmatureDataManagerDeprecated.purge() deprecatedTip("CCArmatureDataManager:purge","ccs.ArmatureDataManager:destoryInstance") return ccs.ArmatureDataManager:destoryInstance() end CCArmatureDataManager.purge = CCArmatureDataManagerDeprecated.purge --functions of CCArmatureDataManager will be deprecated end
mit
artynet/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
4
3222
-- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.nut",package.seeall) function item() return luci.i18n.translate("UPS") end function rrdargs( graph, plugin, plugin_instance, dtype ) local voltages_ac = { title = "%H: AC voltages on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local voltages_dc = { title = "%H: Battery voltage on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "battery" } }, options = { voltage = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true } } } } local currents = { title = "%H: Current on UPS \"%pi\"", vlabel = "A", number_format = "%5.3lfA", data = { instances = { current = { "battery", "output" } }, options = { current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true }, current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true } } } } local percentage = { title = "%H: Battery charge/load on UPS \"%pi\"", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { percent = { "charge", "load" } }, options = { percent_charge = { color = "00ff00", title = "Charge level", noarea=true, overlay=true }, percent_load = { color = "ff0000", title = "Load", noarea=true, overlay=true } } } } -- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century. local temperature = { title = "%H: Battery temperature on UPS \"%pi\"", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = "battery" }, options = { temperature_battery = { color = "ffb000", title = "Battery temperature", noarea=true } } } } local timeleft = { title = "%H: Time left on UPS \"%pi\"", vlabel = "Minutes", number_format = "%.1lfm", data = { instances = { timeleft = { "battery" } }, options = { timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/", noarea=true } } } } local power = { title = "%H: Power on UPS \"%pi\"", vlabel = "Power", number_format = "%5.1lf%%", data = { instances = { power = { "ups" } }, options = { power_ups = { color = "00ff00", title = "Power level" } } } } local frequencies = { title = "%H: Frequencies on UPS \"%pi\"", vlabel = "Hz", number_format = "%5.1lfHz", data = { instances = { frequency = { "input", "output" } }, options = { frequency_output = { color = "00e000", title = "Output frequency", noarea=true, overlay=true }, frequency_input = { color = "ffb000", title = "Input frequency", noarea=true, overlay=true } } } } return { voltages_ac, voltages_dc, currents, percentage, temperature, timeleft, power, frequencies } end
apache-2.0
akh00/kong
kong/cmd/utils/nginx_signals.lua
5
3322
local log = require "kong.cmd.utils.log" local kill = require "kong.cmd.utils.kill" local meta = require "kong.meta" local pl_path = require "pl.path" local version = require "version" local pl_utils = require "pl.utils" local fmt = string.format local nginx_bin_name = "nginx" local nginx_search_paths = { "/usr/local/openresty/nginx/sbin", "" } local nginx_version_pattern = "^nginx.-openresty.-([%d%.]+)" local nginx_compatible = version.set(unpack(meta._DEPENDENCIES.nginx)) local function is_openresty(bin_path) local cmd = fmt("%s -v", bin_path) local ok, _, _, stderr = pl_utils.executeex(cmd) log.debug("%s: '%s'", cmd, stderr:sub(1, -2)) if ok and stderr then local version_match = stderr:match(nginx_version_pattern) if not version_match or not nginx_compatible:matches(version_match) then log.verbose("incompatible OpenResty found at %s. Kong requires version" .. " %s, got %s", bin_path, tostring(nginx_compatible), version_match) return false end return true end log.debug("OpenResty 'nginx' executable not found at %s", bin_path) end local function send_signal(kong_conf, signal) if not kill.is_running(kong_conf.nginx_pid) then return nil, "nginx not running in prefix: " .. kong_conf.prefix end log.verbose("sending %s signal to nginx running at %s", signal, kong_conf.nginx_pid) local code = kill.kill(kong_conf.nginx_pid, "-s " .. signal) if code ~= 0 then return nil, "could not send signal" end return true end local _M = {} local function find_nginx_bin() log.debug("searching for OpenResty 'nginx' executable") local found for _, path in ipairs(nginx_search_paths) do local path_to_check = pl_path.join(path, nginx_bin_name) if is_openresty(path_to_check) then found = path_to_check log.debug("found OpenResty 'nginx' executable at %s", found) break end end if not found then return nil, ("could not find OpenResty 'nginx' executable. Kong requires" .. " version %s"):format(tostring(nginx_compatible)) end return found end function _M.start(kong_conf) local nginx_bin, err = find_nginx_bin() if not nginx_bin then return nil, err end if kill.is_running(kong_conf.nginx_pid) then return nil, "nginx is already running in " .. kong_conf.prefix end local cmd = fmt("%s -p %s -c %s", nginx_bin, kong_conf.prefix, "nginx.conf") log.debug("starting nginx: %s", cmd) local ok, _, _, stderr = pl_utils.executeex(cmd) if not ok then return nil, stderr end log.debug("nginx started") return true end function _M.stop(kong_conf) return send_signal(kong_conf, "TERM") end function _M.quit(kong_conf, graceful) return send_signal(kong_conf, "QUIT") end function _M.reload(kong_conf) if not kill.is_running(kong_conf.nginx_pid) then return nil, "nginx not running in prefix: " .. kong_conf.prefix end local nginx_bin, err = find_nginx_bin() if not nginx_bin then return nil, err end local cmd = fmt("%s -p %s -c %s -s %s", nginx_bin, kong_conf.prefix, "nginx.conf", "reload") log.debug("reloading nginx: %s", cmd) local ok, _, _, stderr = pl_utils.executeex(cmd) if not ok then return nil, stderr end return true end return _M
apache-2.0
master041/tele-master
plugins/stats.lua
866
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
kennethlombardi/moai-components
Data/Scripts/Factory.lua
1
2005
local m = { handlers = {} } -- entity is a default parameter that will be ignored most of the time -- entity used for things like creating components that need to know who -- they are attached to function m.create(typeName, definition, entity, attributeKey) assert(typeName ~= nil, "Factory.create typeName is nil") assert(m.handlers[typeName] ~= nil, "Handler for typeName: "..(typeName or "nil").." not definied.") -- not all handlers need or use entity e.g AttributeHandlers return m.handlers[typeName].create(typeName, definition, entity, attributeKey) end function m.createFromFile(type, file) local function getDefinition(file) local char = "" while char ~= "{" do char = file:read(1) assert(char ~= nil, "Read to end of file looking for definition of entity") end local definition = char local scope = 1 while scope ~= 0 do char = file:read(1) if char == "}" then scope = scope - 1 elseif char == "{" then scope = scope + 1 end assert(char ~= nil, "Read to end of file looking for entity definition") definition = definition..char end return definition end local definition = getDefinition(file) return m.create(type, loadstring("return"..definition)()) end function m.initialize() m.handlers = {} local handlers = require("EntityHandlers") for k,v in pairs(handlers) do m.registerHandler(k, v) end handlers = require("ComponentHandlers") for k,v in pairs(handlers) do m.registerHandler(k, v) end handlers = require("AttributeHandlers") for k,v in pairs(handlers) do m.registerHandler(k, v) end end function m.registerHandler(type, handler) m.handlers[type] = handler end function m.shutdown() m.handlers = nil end function m.update(dt) end return m
mit
ondravondra/vlc
share/lua/playlist/bbc_co_uk.lua
112
1468
--[[ $Id$ Copyright © 2008 the VideoLAN team Authors: Dominique Leuenberger <dominique-vlc.suse@leuenberger.net> 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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "bbc.co.uk/iplayer/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "title: " ) then _,_,name = string.find( line, "title: \"(.*)\"" ) end if string.match( line, "metaFile: \".*%.ram\"" ) then _,_,video = string.find( line, "metaFile: \"(.-)\"" ) table.insert( p, { path = video; name = name } ) end end return p end
gpl-2.0
Dadido3/D3mc
Lua/Physic/Standart/Game of Life.lua
1
2619
local Physic_Game_Of_Life_Syncer = {} function Physic_Game_Of_Life(World_ID, X, Y, Z, Type, Metadata, Current_Trigger_Time) -- 0 Alive -- 8 Born next generation -- 15 Dead -- 12 Dead next generation if Physic_Game_Of_Life_Syncer[World_ID] == nil then Physic_Game_Of_Life_Syncer[World_ID] = {} end --Message_Send_2_All(tostring(Current_Trigger_Time)) if Physic_Game_Of_Life_Syncer[World_ID].Time ~= Current_Trigger_Time then --Message_Send_2_All("§cDebug: "..tostring(Current_Trigger_Time)) Physic_Game_Of_Life_Syncer[World_ID].Time = Current_Trigger_Time if Physic_Game_Of_Life_Syncer[World_ID].State == nil or Physic_Game_Of_Life_Syncer[World_ID].State == 1 then Physic_Game_Of_Life_Syncer[World_ID].State = 0 --Message_Send_2_All("§cDebug: A") else Physic_Game_Of_Life_Syncer[World_ID].State = 1 --Message_Send_2_All("§cDebug: B") end end if Physic_Game_Of_Life_Syncer[World_ID].State == 0 then local Counter = 0 for ix = -1, 1 do for iy = -1, 1 do for iz = -1, 1 do if ix ~= 0 or iy ~= 0 or iz ~= 0 then local Result, Temp_Type, Temp_Metadata = World_Block_Get(World_ID, X+ix, Y+iy, Z+iz) if Result == 1 and Temp_Type == 255 and (Temp_Metadata == 0 or Temp_Metadata == 12) then Counter = Counter + 1 end end end end end --Message_Send_2_All("§cDebug: X="..tostring(X).." Y="..tostring(Y)) if Metadata == 8 or Metadata == 12 then -- Not the correct type, try it next time (readding to the queue) World_Physic_Queue_Add(World_ID, X, Y, Z, Current_Trigger_Time, 10) elseif Metadata == 0 and (Counter < 2 or Counter > 3) then Metadata = 12 World_Block_Set(World_ID, X, Y, Z, -1, Metadata, -1, -1, -1, 1, 1, 1, Current_Trigger_Time) elseif Metadata == 15 and Counter == 3 then Metadata = 8 World_Block_Set(World_ID, X, Y, Z, -1, Metadata, -1, -1, -1, 1, 1, 1, Current_Trigger_Time) end else --Message_Send_2_All("§cDebug: B") if Metadata == 0 or Metadata == 15 then --Message_Send_2_All("§casd: X="..tostring(X).." Y="..tostring(Y)) -- Not the correct type, try it next time (readding to the queue) World_Physic_Queue_Add(World_ID, X, Y, Z, Current_Trigger_Time, 10) elseif Metadata == 8 then Metadata = 0 World_Block_Set(World_ID, X, Y, Z, -1, Metadata, -1, -1, -1, 1, 1, 1, Current_Trigger_Time) elseif Metadata == 12 then Metadata = 15 World_Block_Set(World_ID, X, Y, Z, -1, Metadata, -1, -1, -1, 1, 1, 1, Current_Trigger_Time) end end --Message_Send_2_All("§cDoor-Building: Metadata="..tostring(Metadata).." X="..tostring(X).." Y="..tostring(Y)) end
mit
Whit3Tig3R/SpammBot
plugins/id.lua
226
4260
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' for k,v in pairs(result.members) do text = text .. v.print_name .. " (user#id" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')' if is_chat_msg(msg) then text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end elseif matches[1] == "member" and matches[2] == "@" then local nick = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local receiver = extra.receiver local nick = extra.nick local found for k,user in pairs(result.members) do if user.username == nick then found = user end end if not found then send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "ID: "..found.id send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, nick=nick}) elseif matches[1] == "members" and matches[2] == "name" then local text = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local members = result.members local receiver = extra.receiver local text = extra.text local founds = {} for k,member in pairs(members) do local fields = {'first_name', 'print_name', 'username'} for k,field in pairs(fields) do if member[field] and type(member[field]) == "string" then if member[field]:match(text) then local id = tostring(member.id) founds[id] = member end end end end if next(founds) == nil then -- Empty table send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "" for k,user in pairs(founds) do local first_name = user.first_name or "" local print_name = user.print_name or "" local user_name = user.user_name or "" local id = user.id or "" -- This would be funny text = text.."First name: "..first_name.."\n" .."Print name: "..print_name.."\n" .."User name: "..user_name.."\n" .."ID: "..id end send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, text=text}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id member @<user_name>: Return the member @<user_name> ID from the current chat", "!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat" }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (member) (@)(.+)", "^!id (members) (name) (.+)" }, run = run }
gpl-2.0
stephank/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-voice.lua
80
1493
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") voicegeneral = cbimap:section(TypedSection, "voicegeneral", "Voicemail general options", "") serveremail = voicegeneral:option(Value, "serveremail", "From Email address of server", "") voicemail = cbimap:section(TypedSection, "voicemail", "Voice Mail boxes", "") voicemail.addremove = true attach = voicemail:option(Flag, "attach", "Email contains attachment", "") attach.rmempty = true email = voicemail:option(Value, "email", "Email", "") email.rmempty = true name = voicemail:option(Value, "name", "Display Name", "") name.rmempty = true password = voicemail:option(Value, "password", "Password", "") password.rmempty = true zone = voicemail:option(ListValue, "zone", "Voice Zone", "") cbimap.uci:foreach( "asterisk", "voicezone", function(s) zone:value(s['.name']) end ) voicezone = cbimap:section(TypedSection, "voicezone", "Voice Zone settings", "") voicezone.addremove = true message = voicezone:option(Value, "message", "Message Format", "") message.rmempty = true zone = voicezone:option(Value, "zone", "Time Zone", "") zone.rmempty = true return cbimap
apache-2.0
moltafet35/ssssis
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
dmccuskey/dmc-wamp
examples/dmc-wamp-subscribe/dmc_corona/lib/dmc_lua/lua_patch.lua
44
7239
--====================================================================-- -- lua_patch.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library : Lua Patch --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== Imports local Utils = {} -- make copying easier --====================================================================-- --== Setup, Constants local lua_patch_data = { string_format_active = false, table_pop_active = false, print_output_active = false } local PATCH_TABLE_POP = 'table-pop' local PATCH_STRING_FORMAT = 'string-format' local PATCH_PRINT_OUTPUT = 'print-output' local addTablePopPatch, removeTablePopPatch local addStringFormatPatch, removeStringFormatPatch local addPrintOutputPatch, removePrintOutputPatch local sfmt = string.format local tstr = tostring --====================================================================-- --== Support Functions --== Start: copy from lua_utils ==-- -- stringFormatting() -- implement Python-style string replacement -- http://lua-users.org/wiki/StringInterpolation -- function Utils.stringFormatting( a, b ) if not b then return a elseif type(b) == "table" then return string.format(a, unpack(b)) else return string.format(a, b) end end --== End: copy from lua_utils ==-- local function addLuaPatch( input ) -- print( "Patch.addLuaPatch" ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT } else error( sfmt( "Lua Patch:: unknown patch type '%s'", type(input) ) ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then addTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then addStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then addPrintOutputPatch() else error( sfmt( "Lua Patch:: unknown patch name '%s'", tostring( patch ) ) ) end end end local function addAllLuaPatches() addLuaPatch( nil ) end local function removeLuaPatch( input ) -- print( "Patch.removeLuaPatch", input ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT } else error( "Lua Patch:: unknown patch type '" .. type(input) .. "'" ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then removeTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then removeStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then removePrintOutputPatch() else error( "Lua Patch:: unknown patch name '" .. tostring( patch ) .. "'" ) end end end local function removeAllLuaPatches() addAllLuaPatches( nil ) end --====================================================================-- --== Setup Patches --====================================================================-- --======================================================-- -- Python-style string formatting addStringFormatPatch = function() if lua_patch_data.string_format_active == false then print( "Lua Patch::activating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = Utils.stringFormatting lua_patch_data.string_format_active = true end end removeStringFormatPatch = function() if lua_patch_data.string_format_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = nil lua_patch_data.string_format_active = false end end --======================================================-- -- Python-style table pop() method -- tablePop() -- local function tablePop( t, v ) assert( type(t)=='table', "Patch:tablePop, expected table arg for pop()") assert( v, "Patch:tablePop, expected key" ) local res = t[v] t[v] = nil return res end addTablePopPatch = function() if lua_patch_data.table_pop_active == false then print( "Lua Patch::activating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = tablePop lua_patch_data.table_pop_active = true end end removeTablePopPatch = function() if lua_patch_data.table_pop_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = nil lua_patch_data.table_pop_active = false end end --======================================================-- -- Print Output functions local function printNotice( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "NOTICE" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end local function printWarning( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "WARNING" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end addPrintOutputPatch = function() if lua_patch_data.print_output_active == false then _G.pnotice = printNotice _G.pwarn = printWarning lua_patch_data.print_output_active = true end end removePrintOutputPatch = function() if lua_patch_data.print_output_active == true then _G.pnotice = nil _G.pwarn = nil lua_patch_data.print_output_active = false end end --====================================================================-- --== Patch Facade --====================================================================-- return { PATCH_TABLE_POP=PATCH_TABLE_POP, PATCH_STRING_FORMAT=PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT=PATCH_PRINT_OUTPUT, addPatch = addLuaPatch, addAllPatches=addAllLuaPatches, removePatch=removeLuaPatch, removeAllPatches=removeAllLuaPatch, }
mit
VurtualRuler98/kswep2
lua/calibers/vammo_545x39.lua
1
1183
hook.Add("VurtualAmmotypes","vammo_545x39", function() local tbl = table.Copy(kswep_default_ammo) tbl.vestpenetration=KSWEP_ARMOR_III --TODO make this different tbl.dmgbase=10 tbl.dmgvitalmin=5 tbl.dmgvitalmax=8 tbl.name = "vammo_545x39_7n6" tbl.printname = "5.45x39mm 7N6" tbl.diameter = 0.22 tbl.caliber = "vammo_545x39" tbl.projectiles = 1 tbl.spreadscale = 1 tbl.chokescale = 0 tbl.hitscale = 1 tbl.damagescale = 1 tbl.coefficient=0.338 --JBM calculated tbl.recoil = 4 tbl.mass=53 tbl.velocity = 2900 --16.3in barrel tbl.wallbang = 6 AddAmmodata(tbl) local tbl = table.Copy(kswep_default_ammo) tbl.vestpenetration=KSWEP_ARMOR_III tbl.dmgbase=10 tbl.dmgvitalmin=5 tbl.dmgvitalmax=8 tbl.name = "vammo_545x39_7n6m" tbl.printname = "5.45x39mm 7N6M" tbl.diameter = 0.22 tbl.caliber = "vammo_545x39" tbl.projectiles = 1 tbl.spreadscale = 1 tbl.chokescale = 0 tbl.hitscale = 1 tbl.damagescale = 1 tbl.coefficient=0.338 --JBM calculated tbl.recoil = 4 tbl.mass=53 tbl.velocity = 2900 --16.3in barrel tbl.wallbang = 6 --AddAmmodata(tbl) --this isn't different yet because I can't get penetration data end)
apache-2.0
pchote/OpenRA
mods/ra/maps/allies-10a/allies10a-AI.lua
2
4719
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroup = { } AttackGroupSize = 10 BGAttackGroup = { } BGAttackGroupSize = 6 SovietInfantry = { "e1", "e2", "e4" } SovietVehicles = { "4tnk", "3tnk", "3tnk", "3tnk" } SovietAircraftType = { "mig" } Migs = { } ProductionInterval = { easy = DateTime.Seconds(30), normal = DateTime.Seconds(24), hard = DateTime.Seconds(15) } SendBGAttackGroup = function() if #BGAttackGroup < BGAttackGroupSize then return end Utils.Do(BGAttackGroup, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end) BGAttackGroup = { } end ProduceBadGuyInfantry = function() if BadGuyRax.IsDead or BadGuyRax.Owner ~= BadGuy then return end BadGuy.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(BGAttackGroup, units[1]) SendBGAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceBadGuyInfantry) end) end AttackWaypoints = { AttackWaypoint1, AttackWaypoint2 } SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end local way = Utils.Random(AttackWaypoints) Utils.Do(AttackGroup, function(unit) if not unit.IsDead then unit.AttackMove(way.Location) Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceInfantry = function() if (USSRRax1.IsDead or USSRRax1.Owner ~= USSR) and (USSRRax2.IsDead or USSRRax2.Owner ~= USSR) then return end USSR.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceInfantry) end) end ProduceVehicles = function() if USSRWarFactory.IsDead or USSRWarFactory.Owner ~= USSR then return end USSR.Build({ Utils.Random(SovietVehicles) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end ProduceAircraft = function() if (Airfield1.IsDead or Airfield1.Owner ~= BadGuy) and (Airfield2.IsDead or Airfield2.Owner ~= BadGuy) and (Airfield3.IsDead or Airfield3.Owner ~= BadGuy) and (Airfield4.IsDead or Airfield4.Owner ~= BadGuy) then return end BadGuy.Build(SovietAircraftType, function(units) local mig = units[1] Migs[#Migs + 1] = mig Trigger.OnKilled(mig, ProduceAircraft) local alive = Utils.Where(Migs, function(y) return not y.IsDead end) if #alive < 2 then Trigger.AfterDelay(DateTime.Seconds(ProductionInterval[Difficulty] / 2), ProduceAircraft) end InitializeAttackAircraft(mig, Greece) end) end ParadropDelay = { easy = { DateTime.Minutes(1), DateTime.Minutes(2) }, normal = { DateTime.Seconds(45), DateTime.Minutes(1) }, hard = { DateTime.Seconds(30), DateTime.Seconds(45) } } ParadropLZs = { ParaLZ1.CenterPosition, ParaLZ2.CenterPosition, ParaLZ3.CenterPosition, ParaLZ4.CenterPosition, ParaLZ5.CenterPosition } Paradrop = function() local aircraft = StandardDrop.TargetParatroopers(Utils.Random(ParadropLZs), Angle.NorthWest) Utils.Do(aircraft, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) Trigger.AfterDelay(Utils.RandomInteger(ParadropDelay[1], ParadropDelay[2]), Paradrop) end BombDelays = { easy = 4, normal = 3, hard = 2 } SendParabombs = function() local targets = Utils.Where(Greece.GetActors(), function(actor) return actor.HasProperty("Sell") and actor.Type ~= "brik" and actor.Type ~= "sbag" end) if #targets > 0 then local proxy = Actor.Create("powerproxy.parabombs", false, { Owner = USSR }) proxy.TargetAirstrike(Utils.Random(targets).CenterPosition, Angle.NorthWest) proxy.Destroy() end Trigger.AfterDelay(DateTime.Minutes(BombDelays), SendParabombs) end ActivateAI = function() ParadropDelay = ParadropDelay[Difficulty] BombDelays = BombDelays[Difficulty] local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == USSR and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == USSR and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) end) ProduceBadGuyInfantry() Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(4), ProduceVehicles) Trigger.AfterDelay(DateTime.Minutes(6), ProduceAircraft) end
gpl-3.0
helkarakse/TickProfilerDisplay
src/json.lua
3
15155
----------------------------------------------------------------------------- -- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- Please see LICENCE.txt for details. -- -- USAGE: -- This module exposes two functions: -- encode(o) -- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. -- decode(json_string) -- Returns a Lua object populated with the data encoded in the JSON string json_string. -- -- REQUIREMENTS: -- compat-5.1 if using Lua 5.0 -- -- CHANGELOG -- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). -- Fixed Lua 5.1 compatibility issues. -- Introduced json.null to have null values in associative arrays. -- encode() performance improvement (more than 50%) through table.concat rather than .. -- Introduced decode ability to ignore /**/ comments in the JSON string. -- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Imports and dependencies ----------------------------------------------------------------------------- --local math = require('math') --local string = require("string") --local table = require("table") local base = _G ----------------------------------------------------------------------------- -- Module declaration ----------------------------------------------------------------------------- --module("json") -- Public functions -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace local encodeString local isArray local isEncodable ----------------------------------------------------------------------------- -- PUBLIC FUNCTIONS ----------------------------------------------------------------------------- --- Encodes an arbitrary Lua object / variable. -- @param v The Lua object / variable to be JSON encoded. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) function encode (v) -- Handle nil values if v==nil then return "null" end local vtype = base.type(v) -- Handle strings if vtype=='string' then return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string end -- Handle booleans if vtype=='number' or vtype=='boolean' then return base.tostring(v) end -- Handle tables if vtype=='table' then local rval = {} -- Consider arrays separately local bArray, maxCount = isArray(v) if bArray then for i = 1,maxCount do table.insert(rval, encode(v[i])) end else -- An object, not an array for i,j in base.pairs(v) do if isEncodable(i) and isEncodable(j) then table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j)) end end end if bArray then return '[' .. table.concat(rval,',') ..']' else return '{' .. table.concat(rval,',') .. '}' end end -- Handle null values if vtype=='function' and v==null then return 'null' end base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v)) end --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function null() return null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') object, startPos = decode(s,startPos) table.insert(array,object) until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in base.pairs(constNames) do --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = decode(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) base.assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') local escaped = false local endPos = startPos + 1 local bEnded = false local stringLen = string.len(s) repeat local curChar = string.sub(s,endPos,endPos) -- Character escaping is only used to escape the string delimiters if not escaped then if curChar==[[\]] then escaped = true else bEnded = curChar==startChar end else -- If we're escaped, we accept the current character come what may escaped = false end endPos = endPos + 1 base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) until bEnded local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = 0 if (s ~= nil) then stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end end return startPos end --- Encodes a string to be JSON-compatible. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) -- @param s The string to return as a JSON encoded (i.e. backquoted string) -- @return The string appropriately escaped. function encodeString(s) s = string.gsub(s,'\\','\\\\') s = string.gsub(s,'"','\\"') s = string.gsub(s,"'","\\'") s = string.gsub(s,'\n','\\n') s = string.gsub(s,'\t','\\t') return s end -- Determines whether the given Lua type is an array or a table / dictionary. -- We consider any table an array if it has indexes 1..n for its n items, and no -- other data in the table. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet... -- @param t The table to evaluate as an array -- @return boolean, number True if the table can be represented as an array, false otherwise. If true, -- the second returned value is the maximum -- number of indexed elements in the array. function isArray(t) -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable -- (with the possible exception of 'n') local maxIndex = 0 for k,v in base.pairs(t) do if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair if (not isEncodable(v)) then return false end -- All array elements must be encodable maxIndex = math.max(maxIndex,k) else if (k=='n') then if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements else -- Else of (k=='n') if isEncodable(v) then return false end end -- End of (k~='n') end -- End of k,v not an indexed pair end -- End of loop across all pairs return true, maxIndex end --- Determines whether the given Lua object / table / variable can be JSON encoded. The only -- types that are JSON encodable are: string, boolean, number, nil, table and json.null. -- In this implementation, all other types are ignored. -- @param o The object to examine. -- @return boolean True if the object should be JSON encoded, false if it should be ignored. function isEncodable(o) local t = base.type(o) return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null) end
gpl-2.0
Ialong/shogun
examples/undocumented/lua_modular/kernel_comm_word_string_modular.lua
21
1375
require 'modshogun' require 'load' traindat = load_dna('../data/fm_train_dna.dat') testdat = load_dna('../data/fm_test_dna.dat') parameter_list = {{traindat,testdat,4,0,false, false},{traindat,testdat,4,0,False,False}} function kernel_comm_word_string_modular (fm_train_dna,fm_test_dna, order, gap, reverse, use_sign) --charfeat=modshogun.StringCharFeatures(modshogun.DNA) --charfeat:set_features(fm_train_dna) --feats_train=modshogun.StringWordFeatures(charfeat:get_alphabet()) --feats_train:obtain_from_char(charfeat, order-1, order, gap, reverse) -- --preproc=modshogun.SortWordString() --preproc:init(feats_train) --feats_train:add_preprocessor(preproc) --feats_train:apply_preprocessor() -- --charfeat=modshogun.StringCharFeatures(modshogun.DNA) --charfeat:set_features(fm_test_dna) --feats_test=modshogun.StringWordFeatures(charfeat:get_alphabet()) --feats_test:obtain_from_char(charfeat, order-1, order, gap, reverse) --feats_test:add_preprocessor(preproc) --feats_test:apply_preprocessor() -- --kernel=modshogun.CommWordStringKernel(feats_train, feats_train, use_sign) -- --km_train=kernel:get_kernel_matrix() --kernel:init(feats_train, feats_test) --km_test=kernel:get_kernel_matrix() --return km_train,km_test,kernel end if debug.getinfo(3) == nill then print 'CommWordString' kernel_comm_word_string_modular(unpack(parameter_list[1])) end
gpl-3.0
UnluckyNinja/PathOfBuilding
Classes/TreeTab.lua
1
10473
-- Path of Building -- -- Module: Tree Tab -- Passive skill tree tab for the current build. -- local launch, main = ... local ipairs = ipairs local t_insert = table.insert local m_min = math.min local TreeTabClass = common.NewClass("TreeTab", "ControlHost", function(self, build) self.ControlHost() self.build = build self.viewer = common.New("PassiveTreeView") self.specList = { } self.specList[1] = common.New("PassiveSpec", build) self:SetActiveSpec(1) self.anchorControls = common.New("Control", nil, 0, 0, 0, 20) self.controls.specSelect = common.New("DropDownControl", {"LEFT",self.anchorControls,"RIGHT"}, 0, 0, 150, 20, nil, function(index, value) if self.specList[index] then self.build.modFlag = true self:SetActiveSpec(index) else self:OpenSpecManagePopup() end end) self.controls.specSelect.tooltipFunc = function(tooltip, mode, selIndex, selVal) tooltip:Clear() if mode ~= "OUT" then local spec = self.specList[selIndex] if spec then local used, ascUsed, sockets = spec:CountAllocNodes() tooltip:AddLine(16, "Class: "..spec.curClassName) tooltip:AddLine(16, "Ascendancy: "..spec.curAscendClassName) tooltip:AddLine(16, "Points used: "..used) if sockets > 0 then tooltip:AddLine(16, "Jewel sockets: "..sockets) end if selIndex ~= self.activeSpec then local calcFunc, calcBase = self.build.calcsTab:GetMiscCalculator() if calcFunc then local output = calcFunc({ spec = spec }) self.build:AddStatComparesToTooltip(tooltip, calcBase, output, "^7Switching to this tree will give you:") end if spec.curClassId == self.build.spec.curClassId then local respec = 0 for nodeId, node in pairs(self.build.spec.allocNodes) do if node.type ~= "classStart" and node.type ~= "ascendClassStart" and not spec.allocNodes[nodeId] then if node.ascendancyName then respec = respec + 5 else respec = respec + 1 end end end if respec > 0 then tooltip:AddLine(16, "^7Switching to this tree requires "..respec.." refund points.") end end end end end end self.controls.reset = common.New("ButtonControl", {"LEFT",self.controls.specSelect,"RIGHT"}, 8, 0, 60, 20, "Reset", function() main:OpenConfirmPopup("Reset Tree", "Are you sure you want to reset your passive tree?", "Reset", function() self.build.spec:ResetNodes() self.build.spec:AddUndoState() self.build.buildFlag = true end) end) self.controls.import = common.New("ButtonControl", {"LEFT",self.controls.reset,"RIGHT"}, 8, 0, 90, 20, "Import Tree", function() self:OpenImportPopup() end) self.controls.export = common.New("ButtonControl", {"LEFT",self.controls.import,"RIGHT"}, 8, 0, 90, 20, "Export Tree", function() self:OpenExportPopup() end) self.controls.treeSearch = common.New("EditControl", {"LEFT",self.controls.export,"RIGHT"}, 8, 0, 300, 20, "", "Search", "%c%(%)", 100, function(buf) self.viewer.searchStr = buf end) self.controls.treeHeatMap = common.New("CheckBoxControl", {"LEFT",self.controls.treeSearch,"RIGHT"}, 130, 0, 20, "Show Node Power:", function(state) self.viewer.showHeatMap = state end) self.controls.treeHeatMap.tooltipText = function() local offCol, defCol = main.nodePowerTheme:match("(%a+)/(%a+)") return "When enabled, an estimate of the offensive and defensive strength of\neach unallocated passive is calculated and displayed visually.\nOffensive power shows as "..offCol:lower()..", defensive power as "..defCol:lower().."." end end) function TreeTabClass:Draw(viewPort, inputEvents) self.anchorControls.x = viewPort.x + 4 self.anchorControls.y = viewPort.y + viewPort.height - 24 for id, event in ipairs(inputEvents) do if event.type == "KeyDown" then if event.key == "z" and IsKeyDown("CTRL") then self.build.spec:Undo() self.build.buildFlag = true inputEvents[id] = nil elseif event.key == "y" and IsKeyDown("CTRL") then self.build.spec:Redo() self.build.buildFlag = true inputEvents[id] = nil end end end self:ProcessControlsInput(inputEvents, viewPort) local treeViewPort = { x = viewPort.x, y = viewPort.y, width = viewPort.width, height = viewPort.height - 32 } self.viewer:Draw(self.build, treeViewPort, inputEvents) self.controls.specSelect.selIndex = self.activeSpec wipeTable(self.controls.specSelect.list) for id, spec in ipairs(self.specList) do t_insert(self.controls.specSelect.list, spec.title or "Default") end t_insert(self.controls.specSelect.list, "Manage trees...") if not self.controls.treeSearch.hasFocus then self.controls.treeSearch:SetText(self.viewer.searchStr) end self.controls.treeHeatMap.state = self.viewer.showHeatMap SetDrawLayer(1) SetDrawColor(0.05, 0.05, 0.05) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 28, viewPort.width, 28) SetDrawColor(0.85, 0.85, 0.85) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 32, viewPort.width, 4) self:DrawControls(viewPort) end function TreeTabClass:Load(xml, dbFileName) self.specList = { } if xml.elem == "Spec" then -- Import single spec from old build self.specList[1] = common.New("PassiveSpec", self.build) self.specList[1]:Load(xml, dbFileName) self.activeSpec = 1 self.build.spec = self.specList[1] return end for _, node in pairs(xml) do if type(node) == "table" then if node.elem == "Spec" then local newSpec = common.New("PassiveSpec", self.build) newSpec:Load(node, dbFileName) t_insert(self.specList, newSpec) end end end if not self.specList[1] then self.specList[1] = common.New("PassiveSpec", self.build) end self:SetActiveSpec(tonumber(xml.attrib.activeSpec) or 1) end function TreeTabClass:PostLoad() for _, spec in ipairs(self.specList) do spec:BuildAllDependsAndPaths() end end function TreeTabClass:Save(xml) xml.attrib = { activeSpec = tostring(self.activeSpec) } for specId, spec in ipairs(self.specList) do if specId == self.activeSpec then -- Update this spec's jewels from the socket slots for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then spec.jewels[slot.nodeId] = slot.selItemId end end end local child = { elem = "Spec" } spec:Save(child) t_insert(xml, child) end self.modFlag = false end function TreeTabClass:SetActiveSpec(specId) local prevSpec = self.build.spec self.activeSpec = m_min(specId, #self.specList) local curSpec = self.specList[self.activeSpec] self.build.spec = curSpec self.build.buildFlag = true for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then if prevSpec then -- Update the previous spec's jewel for this slot prevSpec.jewels[slot.nodeId] = slot.selItemId end if curSpec.jewels[slot.nodeId] then -- Socket the jewel for the new spec slot.selItemId = curSpec.jewels[slot.nodeId] end end end if self.build.itemsTab.itemOrderList[1] then -- Update item slots if items have been loaded already self.build.itemsTab:PopulateSlots() end end function TreeTabClass:OpenSpecManagePopup() main:OpenPopup(370, 290, "Manage Passive Trees", { common.New("PassiveSpecList", nil, 0, 50, 350, 200, self), common.New("ButtonControl", nil, 0, 260, 90, 20, "Done", function() main:ClosePopup() end), }) end function TreeTabClass:OpenImportPopup() local controls = { } local function decodeTreeLink(treeLink) local errMsg = self.build.spec:DecodeURL(treeLink) if errMsg then controls.msg.label = "^1"..errMsg else self.build.spec:AddUndoState() self.build.buildFlag = true main:ClosePopup() end end controls.editLabel = common.New("LabelControl", nil, 0, 20, 0, 16, "Enter passive tree link:") controls.edit = common.New("EditControl", nil, 0, 40, 350, 18, "", nil, nil, nil, function(buf) controls.msg.label = "" end) controls.msg = common.New("LabelControl", nil, 0, 58, 0, 16, "") controls.import = common.New("ButtonControl", nil, -45, 80, 80, 20, "Import", function() local treeLink = controls.edit.buf if #treeLink == 0 then return end if treeLink:match("poeurl%.com/") then controls.import.enabled = false controls.msg.label = "Resolving PoEURL link..." local id = LaunchSubScript([[ local treeLink = ... local curl = require("lcurl.safe") local easy = curl.easy() easy:setopt_url(treeLink) easy:setopt_writefunction(function(data) return true end) easy:perform() local redirect = easy:getinfo(curl.INFO_REDIRECT_URL) easy:close() if not redirect or redirect:match("poeurl%.com/") then return nil, "Failed to resolve PoEURL link" end return redirect ]], "", "", treeLink) if id then launch:RegisterSubScript(id, function(treeLink, errMsg) if errMsg then controls.msg.label = "^1"..errMsg controls.import.enabled = true else decodeTreeLink(treeLink) end end) end else decodeTreeLink(treeLink) end end) controls.cancel = common.New("ButtonControl", nil, 45, 80, 80, 20, "Cancel", function() main:ClosePopup() end) main:OpenPopup(380, 110, "Import Tree", controls, "import", "edit") end function TreeTabClass:OpenExportPopup() local treeLink = self.build.spec:EncodeURL("https://www.pathofexile.com/passive-skill-tree/"..(self.build.targetVersion == "2_6" and "2.6.2/" or "3.0.0/")) local popup local controls = { } controls.label = common.New("LabelControl", nil, 0, 20, 0, 16, "Passive tree link:") controls.edit = common.New("EditControl", nil, 0, 40, 350, 18, treeLink, nil, "%Z") controls.shrink = common.New("ButtonControl", nil, -90, 70, 140, 20, "Shrink with PoEURL", function() controls.shrink.enabled = false controls.shrink.label = "Shrinking..." launch:DownloadPage("http://poeurl.com/shrink.php?url="..treeLink, function(page, errMsg) controls.shrink.label = "Done" if errMsg or not page:match("%S") then main:OpenMessagePopup("PoEURL Shortener", "Failed to get PoEURL link. Try again later.") else treeLink = "http://poeurl.com/"..page controls.edit:SetText(treeLink) popup:SelectControl(controls.edit) end end) end) controls.copy = common.New("ButtonControl", nil, 30, 70, 80, 20, "Copy", function() Copy(treeLink) end) controls.done = common.New("ButtonControl", nil, 120, 70, 80, 20, "Done", function() main:ClosePopup() end) popup = main:OpenPopup(380, 100, "Export Tree", controls, "done", "edit") end
mit
matthewjwoodruff/language-of-choice
lua/bdd1.lua
2
5196
local dbg = require 'dbg' local printf = dbg.printf local log = dbg.log local optimize = true local infinity = 1/0 local function pp(node) local c, memo = 0, {} local function walk(p) local id = memo[p] if id == nil then id = c; c = c + 1 memo[p] = id if p.rank < infinity then walk(p.if0) walk(p.if1) end end end walk(node) local shown = {} local function show(p) if shown[p] == nil then shown[p] = true if p.rank < infinity then printf("%d: v%d -> %d, %d\n", memo[p], p.rank, memo[p.if0], memo[p.if1]) show(p.if0) show(p.if1) else printf("%d: %d\n", memo[p], p.value) end end end show(node) printf("\n") end local function build_constant(value) local function choose(if0, if1) if value == 0 then return if0 elseif value == 1 then return if1 else assert(false) end end local function evaluate(env) return value end return { rank = infinity, value = value, choose = choose, evaluate = evaluate, } end local lit0, lit1 = build_constant(0), build_constant(1) local function make_constant(value) if value == 0 then return lit0 elseif value == 1 then return lit1 else assert(false) end end local function dedup(memo, k1, k2, k3) local mem1 = memo[k1]; if mem1 == nil then mem1 = {}; memo[k1] = mem1 end local mem2 = mem1[k2]; if mem2 == nil then mem2 = {}; mem1[k2] = mem2 end local mem3 = mem2[k3] return mem3, mem2 end local choice_memo = {} local choose local function build_choice(rank, if0, if1) local already, memo_table = dedup(choice_memo, rank, if0, if1) if already then return already end local node local function do_choose(if0, if1) if optimize then if if0 == if1 then return if0 end if if0 == lit0 and if1 == lit1 then return node end end return choose(node, if0, if1) end local function evaluate(env) local value = env[rank] if value == 0 then return if0.evaluate(env) elseif value == 1 then return if1.evaluate(env) else assert(false) end end node = { rank = rank, if0 = if0, if1 = if1, choose = do_choose, evaluate = evaluate, } memo_table[if1] = node return node end local function make_choice(rank, if0, if1) if if0 == if1 then return if0 end return build_choice(rank, if0, if1) end local function make_variable(rank) return build_choice(rank, lit0, lit1) end local function subst(rank, replacement, node) local result if rank < node.rank then return node elseif rank == node.rank then return replacement.choose(node.if0, node.if1) else return make_choice(node.rank, subst(rank, replacement, node.if0), subst(rank, replacement, node.if1)) end end local choose_memo = {} local function really_choose(node, if0, if1) local already, memo_table = dedup(choose_memo, node, if0, if1) if already then return already end assert(node.rank < infinity) local top = math.min(node.rank, if0.rank, if1.rank) local on0 = subst(top, lit0, node).choose(subst(top, lit0, if0), subst(top, lit0, if1)) local on1 = subst(top, lit1, node).choose(subst(top, lit1, if0), subst(top, lit1, if1)) local result = make_choice(top, on0, on1) memo_table[if1] = result return result end choose = really_choose -- Return the lexicographically first env such that -- node.evaluate(env) == goal, if there's any; else nil. -- The env may have nils for variables that don't matter. local function satisfy_first(node, goal) local env = {} while node.rank ~= infinity do local if0 = node.if0 if if0.rank < infinity or if0.value == goal then env[node.rank] = 0 node = if0 else env[node.rank] = 1 node = node.if1 end end if node.value ~= goal then return nil end return env end local function bdd_and(node1, node2) return node2.choose(lit0, node1) end -- local function bdd_and(node1, node2) return node1.choose(lit0, node2) end local function bdd_or (node1, node2) return node2.choose(node1, lit1) end -- Return a node that's true just when env's vars have their given values. local function match(env, max_rank) local node = lit1 for rank = max_rank, 1, -1 do if env[rank] == nil then elseif env[rank] == 0 then node = make_choice(rank, node, lit0) elseif env[rank] == 1 then node = make_choice(rank, lit0, node) else assert(false) end end return node end return { lit0 = lit0, lit1 = lit1, make_constant = make_constant, make_variable = make_variable, subst = subst, satisfy_first = satisfy_first, bdd_and = bdd_and, bdd_or = bdd_or, match = match, pp = pp, choose = function(node, if0, if1) return node.choose(if0, if1) end }
gpl-3.0
marshmellow42/proxmark3
client/scripts/mfkeys.lua
5
5595
--[[ This is an example of Lua-scripting within proxmark3. This is a lua-side implementation of hf mf chk This code is licensed to you under the terms of the GNU GPL, version 2 or, at your option, any later version. See the LICENSE.txt file for the text of the license. Copyright (C) 2013 m h swende <martin at swende.se> --]] -- Loads the commands-library local cmds = require('commands') -- Load the default keys local keys = require('mf_default_keys') -- Ability to read what card is there local reader = require('read14a') -- Asks the user for input local utils = require('utils') local desc = ("This script implements check keys. \ It utilises a large list of default keys (currently %d keys).\ If you want to add more, just put them inside mf_default_keys.lua. "):format(#keys) local TIMEOUT = 10000 -- 10 seconds local function checkCommand(command) --print("Sending this command : " .. tostring(command)) local usbcommand = command:getBytes() core.SendCommand(usbcommand) local result = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) if result then local count,cmd,arg0 = bin.unpack('LL',result) if(arg0==1) then local count,arg1,arg2,data = bin.unpack('LLH511',result,count) key = data:sub(1,12) return key else --print("Key not found...") return nil end else print("Timeout while waiting for response. Increase TIMEOUT in keycheck.lua to wait longer") return nil, "Timeout while waiting for device to respond" end end function checkBlock(blockNo, keys, keyType) -- The command data is only 512 bytes, each key is 6 bytes, meaning that we can send max 85 keys in one go. -- If there's more, we need to split it up local start, remaining= 1, #keys local arg1 = bit32.bor(bit32.lshift(keyType, 8), blockNo) local packets = {} while remaining > 0 do local n,data = remaining, nil if remaining > 85 then n = 85 end local data = table.concat(keys, "", start, start + n - 1) --print("data",data) --print("data len", #data) print(("Testing block %d, keytype %d, with %d keys"):format(blockNo, keyType, n)) local command = Command:new{cmd = cmds.CMD_MIFARE_CHKKEYS, arg1 = arg1, arg2 = 1, arg3 = n, data = data} local status = checkCommand(command) if status then return status, blockNo end start = start + n remaining = remaining - n end return nil end -- A function to display the results local function displayresults(results) local sector, blockNo, keyA, keyB,_ print("________________________________________") print("|Sector|Block| A | B |") print("|--------------------------------------|") for sector,_ in pairs(results) do blockNo, keyA, keyB = unpack(_) print(("| %3d | %3d |%12s|%12s|"):format(sector, blockNo, keyA, keyB)) end print("|--------------------------------------|") end -- A little helper to place an item first in the list local function placeFirst(akey, list) akey = akey:lower() if list[1] == akey then -- Already at pole position return list end local result = {akey} --print(("Putting '%s' first"):format(akey)) for i,v in ipairs(list) do if v ~= akey then result[#result+1] = v end end return result end local function dumptofile(results) local sector, blockNo, keyA, keyB,_ if utils.confirm("Do you wish to save the keys to dumpfile?") then local destination = utils.input("Select a filename to store to", "dumpkeys.bin") local file = io.open(destination, "w") if file == nil then print("Could not write to file ", destination) return end local key_a = "" local key_b = "" for sector,_ in pairs(results) do blockNo, keyA, keyB = unpack(_) key_a = key_a .. bin.pack("H",keyA); key_b = key_b .. bin.pack("H",keyB); end file:write(key_a) file:write(key_b) file:close() end end local function main(args) print(desc); result, err = reader.read14443a(false, true) if not result then print(err) return end print(("Found a %s tag"):format(result.name)) core.clearCommandBuffer() local blockNo local keyType = 0 -- A=0, B=1 local numSectors = 16 if 0x18 == result.sak then -- NXP MIFARE Classic 4k | Plus 4k -- IFARE Classic 4K offers 4096 bytes split into forty sectors, -- of which 32 are same size as in the 1K with eight more that are quadruple size sectors. numSectors = 40 elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k -- 1K offers 1024 bytes of data storage, split into 16 sector numSectors = 16 elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k -- MIFARE Classic mini offers 320 bytes split into five sectors. numSectors = 5 elseif 0x10 == result.sak then -- NXP MIFARE Plus 2k numSectors = 32 else print("I don't know how many sectors there are on this type of card, defaulting to 16") end result = {} for sector=1,numSectors,1 do --[[ The mifare Classic 1k card has 16 sectors of 4 data blocks each. The first 32 sectors of a mifare Classic 4k card consists of 4 data blocks and the remaining 8 sectors consist of 16 data blocks. --]] local blockNo = sector * 4 - 1 if sector > 32 then blockNo = 32*4 + (sector-32)*16 - 1 end local keyA = checkBlock(blockNo, keys, 0) if keyA then keys = placeFirst(keyA, keys) end keyA = keyA or "" local keyB = checkBlock(blockNo, keys, 1) if keyB then keys = placeFirst(keyB, keys) end keyB = keyB or "" result[sector] = {blockNo, keyA, keyB} -- Check if user aborted if core.ukbhit() then print("Aborted by user") break end end displayresults(result) dumptofile(result) end main(args)
gpl-2.0
delram/crii
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
pchote/OpenRA
mods/ra/maps/soviet-04a/soviet04a-reinforcements_teams.lua
2
3086
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] Civs = { civ1, civ2, civ3 } Village = { civ1, civ2, civ3, village1, village2, village5 } SovietMCV = { "mcv" } InfantryReinfGreece = { "e1", "e1", "e1", "e1", "e1" } Avengers = { "jeep", "1tnk", "2tnk", "2tnk", "1tnk" } Patrol1Group = { "jeep", "jeep", "2tnk", "2tnk" } Patrol2Group = { "jeep", "1tnk", "1tnk", "1tnk" } AlliedInfantryTypes = { "e1", "e3" } AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" } InfAttack = { } ArmorAttack = { } SovietStartToBasePath = { StartPoint.Location, SovietBasePoint.Location } InfReinfPath = { SWRoadPoint.Location, InVillagePoint.Location } ArmorReinfPath = { NRoadPoint.Location, CrossroadsNorthPoint.Location } Patrol1Path = { NearRadarPoint.Location, ToRadarPoint.Location, InVillagePoint.Location, ToRadarPoint.Location } Patrol2Path = { BridgeEntrancePoint.Location, NERoadTurnPoint.Location, CrossroadsEastPoint.Location, BridgeEntrancePoint.Location } VillageCamArea = { CPos.New(68, 75),CPos.New(68, 76),CPos.New(68, 77),CPos.New(68, 78),CPos.New(68, 79), CPos.New(68, 80), CPos.New(68, 81), CPos.New(68, 82) } if Difficulty == "easy" then ArmorReinfGreece = { "jeep", "1tnk", "1tnk" } else ArmorReinfGreece = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" } end AttackPaths = { { VillageEntrancePoint }, { BridgeEntrancePoint, NERoadTurnPoint, CrossroadsEastPoint } } ReinfInf = function() if RadarDome.IsDead or RadarDome.Owner ~= Greece then return end Reinforcements.Reinforce(Greece, InfantryReinfGreece, InfReinfPath, 0, function(soldier) soldier.Hunt() end) end ReinfArmor = function() if not RadarDome.IsDead and RadarDome.Owner == Greece then RCheck = true Reinforcements.Reinforce(Greece, ArmorReinfGreece, ArmorReinfPath, 0, function(soldier) soldier.Hunt() end) end end BringPatrol1 = function() if RadarDome.IsDead or RadarDome.Owner ~= Greece then return end local units = Reinforcements.Reinforce(Greece, Patrol1Group, { SWRoadPoint.Location }, 0) Utils.Do(units, function(patrols) patrols.Patrol(Patrol1Path, true, 250) end) Trigger.OnAllKilled(units, function() if Difficulty == "hard" then Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol1) else Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol1) end end) end BringPatrol2 = function() if RadarDome.IsDead or RadarDome.Owner ~= Greece then return end local units = Reinforcements.Reinforce(Greece, Patrol2Group, { NRoadPoint.Location }, 0) Utils.Do(units, function(patrols) patrols.Patrol(Patrol2Path, true, 250) end) Trigger.OnAllKilled(units, function() if Difficulty == "hard" then Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol2) else Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol2) end end) end
gpl-3.0
artynet/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/apcups.lua
5
4060
-- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.apcups",package.seeall) function item() return luci.i18n.translate("APC UPS") end function rrdargs( graph, plugin, plugin_instance ) local lu = require("luci.util") local rv = { } -- Types and instances supported by APC UPS -- e.g. ups_types -> { 'timeleft', 'charge', 'percent', 'voltage' } -- e.g. ups_inst['voltage'] -> { 'input', 'battery' } local ups_types = graph.tree:data_types( plugin, plugin_instance ) local ups_inst = {} for _, t in ipairs(ups_types) do ups_inst[t] = graph.tree:data_instances( plugin, plugin_instance, t ) end -- Check if hash table or array is empty or nil-filled local function empty( t ) for _, v in pairs(t) do if type(v) then return false end end return true end -- Append graph definition but only types/instances which are -- supported and available to the plugin and UPS. local function add_supported( t, defs ) local def_inst = defs['data']['instances'] if type(def_inst) == "table" then for k, v in pairs( def_inst ) do if lu.contains( ups_types, k) then for j = #v, 1, -1 do if not lu.contains( ups_inst[k], v[j] ) then table.remove( v, j ) end end if #v == 0 then def_inst[k] = nil -- can't assign v: immutable end else def_inst[k] = nil -- can't assign v: immutable end end if empty(def_inst) then return end end table.insert( t, defs ) end -- Graph definitions for APC UPS measurements MUST use only 'instances': -- e.g. instances = { voltage = { "input", "output" } } local voltagesdc = { title = "%H: Voltages on APC UPS - Battery", vlabel = "Volts DC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "battery" } }, options = { voltage = { title = "Battery voltage", noarea=true } } } } add_supported( rv, voltagesdc ) local voltagesac = { title = "%H: Voltages on APC UPS - AC", vlabel = "Volts AC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } add_supported( rv, voltagesac ) local percentload = { title = "%H: Load on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { percent = { "load" } }, options = { percent_load = { color = "00ff00", title = "Load level" } } } } add_supported( rv, percentload ) local charge_percent = { title = "%H: Battery charge on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { charge = { "" } }, options = { charge = { color = "00ff0b", title = "Charge level" } } } } add_supported( rv, charge_percent ) local temperature = { title = "%H: Battery temperature on APC UPS ", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = { "" } }, options = { temperature = { color = "ffb000", title = "Battery temperature" } } } } add_supported( rv, temperature ) local timeleft = { title = "%H: Time left on APC UPS ", vlabel = "Minutes", number_format = "%.1lfm", data = { instances = { timeleft = { "" } }, options = { timeleft = { color = "0000ff", title = "Time left" } } } } add_supported( rv, timeleft ) local frequency = { title = "%H: Incoming line frequency on APC UPS ", vlabel = "Hz", number_format = "%5.0lfhz", data = { instances = { frequency = { "input" } }, options = { frequency_input = { color = "000fff", title = "Line frequency" } } } } add_supported( rv, frequency ) return rv end
apache-2.0
artynet/luci
applications/luci-app-dnscrypt-proxy/luasrc/controller/dnscrypt-proxy.lua
5
2121
-- Copyright 2017-2019 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 module("luci.controller.dnscrypt-proxy", package.seeall) local util = require("luci.util") local i18n = require("luci.i18n") local templ = require("luci.template") function index() if not nixio.fs.access("/etc/config/dnscrypt-proxy") then nixio.fs.writefile("/etc/config/dnscrypt-proxy", "") end entry({"admin", "services", "dnscrypt-proxy"}, firstchild(), _("DNSCrypt-Proxy"), 60).dependent = false entry({"admin", "services", "dnscrypt-proxy", "tab_from_cbi"}, cbi("dnscrypt-proxy/overview_tab", {hideresetbtn=true, hidesavebtn=true}), _("Overview"), 10).leaf = true entry({"admin", "services", "dnscrypt-proxy", "logfile"}, call("logread"), _("View Logfile"), 20).leaf = true entry({"admin", "services", "dnscrypt-proxy", "advanced"}, firstchild(), _("Advanced"), 100) entry({"admin", "services", "dnscrypt-proxy", "advanced", "configuration"}, form("dnscrypt-proxy/configuration_tab"), _("Edit DNSCrypt-Proxy Configuration"), 110).leaf = true entry({"admin", "services", "dnscrypt-proxy", "advanced", "cfg_dnsmasq"}, form("dnscrypt-proxy/cfg_dnsmasq_tab"), _("Edit Dnsmasq Configuration"), 120).leaf = true entry({"admin", "services", "dnscrypt-proxy", "advanced", "cfg_resolvcrypt"}, form("dnscrypt-proxy/cfg_resolvcrypt_tab"), _("Edit Resolvcrypt Configuration"), 130).leaf = true entry({"admin", "services", "dnscrypt-proxy", "advanced", "view_reslist"}, call("view_reslist"), _("View Resolver List"), 140).leaf = true end function view_reslist() local reslist = util.trim(util.exec("cat /usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv")) templ.render("dnscrypt-proxy/view_reslist", {title = i18n.translate("DNSCrypt-Proxy Resolver List"), content = reslist}) end function logread() local logfile = util.trim(util.exec("logread -e 'dnscrypt-proxy' 2>/dev/null")) or "" if logfile == "" then logfile = "No DNSCrypt-Proxy related logs yet!" end templ.render("dnscrypt-proxy/logread", {title = i18n.translate("DNSCrypt-Proxy Logfile"), content = logfile}) end
apache-2.0
ldurniat/My-Pong-Game
scene/result.lua
2
3005
-- -- Ekran wyświetlający wyniki. -- -- Wymagane moduły local app = require( 'lib.app' ) local preference = require( 'preference' ) local composer = require( 'composer' ) local fx = require( 'com.ponywolf.ponyfx' ) local tiled = require( 'com.ponywolf.ponytiled' ) local json = require( 'json' ) local translations = require( 'translations' ) -- Lokalne zmienne local scene = composer.newScene() local info, ui function scene:create( event ) local sceneGroup = self.view -- Wczytanie mapy local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/result.json', system.ResourceDirectory ) ) info = tiled.new( uiData, 'scene/menu/ui' ) info.x, info.y = _CX - info.designedWidth * 0.5, _CY - info.designedHeight * 0.5 -- Obsługa przycisków info.extensions = 'scene.menu.lib.' info:extend( 'button', 'label' ) function ui( event ) local phase = event.phase local name = event.buttonName if phase == 'released' then app.playSound( 'button' ) if ( name == 'restart' ) then fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.refresh', { params = {} } ) end ) elseif ( name == 'menu' ) then fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.menu', { params = {} } ) end ) end end return true end local background = display.newRect( _CX, _CY, _W - 2 * _L, _H - 2 * _T ) background:setFillColor( 0 ) background.alpha = 0.9 sceneGroup:insert( background ) sceneGroup:insert( info ) end function scene:show( event ) local phase = event.phase local textId = event.params.textId local newScore = event.params.newScore local totalPoints = preference:get( 'totalPoints' ) local lang = preference:get( 'language' ) if ( phase == 'will' ) then totalPoints = totalPoints + newScore local message = { win = translations[lang]['winMessage'], lost = translations[lang]['loseMessage'], } info:findObject('message').text = message[textId] info:findObject('totalPoints').text = totalPoints -- zlicza wszystkie zdobyte punkty preference:set('totalPoints', totalPoints ) elseif ( phase == 'did' ) then app.addRuntimeEvents( {'ui', ui} ) end end function scene:hide( event ) local phase = event.phase if ( phase == 'will' ) then app.removeAllRuntimeEvents() elseif ( phase == 'did' ) then end end function scene:destroy( event ) --collectgarbage() end scene:addEventListener( 'create' ) scene:addEventListener( 'show' ) scene:addEventListener( 'hide' ) scene:addEventListener( 'destroy' ) return scene
mit
RicoP/vlcfork
share/lua/playlist/mpora.lua
97
2565
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video%.mpora%.com/watch/" ) end -- Parse function. function parse() p = {} 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=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "video_src" ) then _,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' ) end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } ) end return p end
gpl-2.0
Nostrademous/Dota2-WebAI
helper/global_helper.lua
1
4359
------------------------------------------------------------------------------- --- AUTHORS: iSarCasm, Nostrademous --- GITHUB REPO: https://github.com/Nostrademous/Dota2-WebAI ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- --- CODE SPECIFIC ------------------------------------------------------------------------------- globalInit = false function InitializeGlobalVars() heroData = require( GetScriptDirectory().."/hero_data" ) globalInit = true end --- TABLE RELATED function InTable(tab, val) if not tab then return false end for index, value in ipairs (tab) do if value == val then return true end end return false end function PosInTable(tab, val) for index,value in ipairs(tab) do if value == val then return index end end return -1 end --- USED BY: --- InventoryHelper:BuyItem() function GetTableKeyNameFromID( hTable, iIndex ) if hTable == nil or iIndex == nil then return "nil" end for key, value in pairs(hTable) do if value == iIndex then return tostring(key) end end return nil end --- USED BY: --- decision.lua - Atomic_BuyItems() function TableConcat(t1, t2) for i = 1, #t2 do t1[#t1+1] = t2[i] end return t1 end ------------------------------------------------------------------------------- --- MATH & TIME RELATED -- checks if a specific bit is set in a bitmask function CheckBitmask(bitmask, bit) return ((bitmask/bit) % 2) >= 1 end function GetSeconds() return math.floor(DotaTime()) % 60 end function Round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end ------------------------------------------------------------------------------- --- DOTA2 SPECIFIC ------------------------------------------------------------------------------- --- TARGET RELATED function ValidTarget( hUnit ) -- handle to the unit cannot be nil and null, and unit has to be alive return hUnit ~= nil and not hUnit:IsNull() and hUnit:IsAlive() end function GetUnitName( hUnit ) local sName = hUnit:GetUnitName() return string.sub(sName, 15, string.len(sName)) end --- SHOP RELATED function GetShop() if (GetTeam() == TEAM_RADIANT) then return SHOP_RADIANT elseif (GetTeam() == TEAM_DIRE) then return SHOP_DIRE end end function ShopDistance( hUnit, iShop ) if (iShop == SHOP_DIRE or iShop == SHOP_RADIANT) then return hUnit:DistanceFromFountain() elseif (iShop == SHOP_SIDE_BOT or iShop == SHOP_SIDE_TOP) then return hUnit:DistanceFromSideShop() else return hUnit:DistanceFromSecretShop() end end --- MAP & GAME ORIENTATION RELATED function GetEnemyTeam() if (GetTeam() == TEAM_RADIANT) then return TEAM_DIRE elseif (GetTeam() == TEAM_DIRE) then return TEAM_RADIANT end end function GetFront(Team, Lane) return GetLaneFrontLocation(Team, Lane, GetLaneFrontAmount(Team, Lane, true)) end function Safelane() return ((GetTeam() == TEAM_RADIANT) and LANE_BOT or LANE_TOP) end function Hardlane() return ((GetTeam() == TEAM_RADIANT) and LANE_TOP or LANE_BOT) end function MyGetNearbyHeroes(range, bEnemies) if range <= 1600 then return GetBot():GetNearbyHeroes(1599, bEnemies, BOT_MODE_NONE) else local botInfo = GetBot().mybot.botInfo local result_heroes = {} local heroes = (bEnemies and botInfo.enemy_heroes or botInfo.ally_heroes) for i = 1, #heroes do if (GetUnitToUnitDistance(bot, heroes[i]) < range) then table.insert(result_heroes, heroes[i]) end end return result_heroes end end function MyGetNearbyCreeps(range, bEnemy) if range <= 1600 then return GetBot():GetNearbyCreeps(range, bEnemy) else local botInfo = GetBot().mybot.botInfo local result_creeps = {} local creeps = (bEnemy and botInfo.enemy_creeps or botInfo.ally_creeps) for i = 1, #creeps do if (GetUnitToUnitDistance(bot, creeps[i]) < range) then table.insert(result_creeps, creeps[i]) end end return result_creeps end end
mit
UnluckyNinja/PathOfBuilding
Data/2_6/Skills/sup_int.lua
1
39862
-- This file is automatically generated, do not edit! -- Path of Building -- -- Intelligence support gems -- Skill data (c) Grinding Gear Games -- local skills, mod, flag, skill = ... skills["SupportAddedChaosDamage"] = { name = "Added Chaos Damage", gemTags = { chaos = true, intelligence = true, support = true, }, gemTagString = "Chaos, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), }, qualityMods = { mod("ChaosDamage", "INC", 0.5), --"chaos_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("ChaosMin", "BASE", nil), --"global_minimum_added_chaos_damage" [3] = mod("ChaosMax", "BASE", nil), --"global_maximum_added_chaos_damage" }, levels = { [1] = { 31, 18, 26, }, [2] = { 34, 21, 32, }, [3] = { 36, 24, 36, }, [4] = { 38, 27, 41, }, [5] = { 40, 31, 46, }, [6] = { 42, 35, 52, }, [7] = { 44, 39, 59, }, [8] = { 46, 44, 67, }, [9] = { 48, 50, 75, }, [10] = { 50, 56, 84, }, [11] = { 52, 63, 94, }, [12] = { 54, 71, 106, }, [13] = { 56, 79, 118, }, [14] = { 58, 88, 132, }, [15] = { 60, 99, 148, }, [16] = { 62, 110, 165, }, [17] = { 64, 123, 185, }, [18] = { 66, 137, 206, }, [19] = { 68, 153, 229, }, [20] = { 70, 170, 256, }, [21] = { 72, 190, 284, }, [22] = { 74, 211, 316, }, [23] = { 76, 234, 352, }, [24] = { 78, 260, 391, }, [25] = { 80, 289, 434, }, [26] = { 82, 321, 482, }, [27] = { 84, 356, 534, }, [28] = { 86, 395, 592, }, [29] = { 88, 438, 657, }, [30] = { 90, 485, 728, }, }, } skills["SupportAddedLightningDamage"] = { name = "Added Lightning Damage", gemTags = { lightning = true, intelligence = true, support = true, }, gemTagString = "Lightning, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 1, 10, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), }, qualityMods = { mod("LightningDamage", "INC", 0.5), --"lightning_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("LightningMin", "BASE", nil), --"global_minimum_added_lightning_damage" [3] = mod("LightningMax", "BASE", nil), --"global_maximum_added_lightning_damage" }, levels = { [1] = { 8, 1, 8, }, [2] = { 10, 1, 9, }, [3] = { 13, 1, 12, }, [4] = { 17, 1, 16, }, [5] = { 21, 1, 22, }, [6] = { 25, 1, 28, }, [7] = { 29, 2, 36, }, [8] = { 33, 2, 47, }, [9] = { 37, 3, 59, }, [10] = { 40, 4, 70, }, [11] = { 43, 4, 83, }, [12] = { 46, 5, 98, }, [13] = { 49, 6, 116, }, [14] = { 52, 7, 136, }, [15] = { 55, 8, 159, }, [16] = { 58, 10, 186, }, [17] = { 61, 11, 218, }, [18] = { 64, 13, 253, }, [19] = { 67, 16, 295, }, [20] = { 70, 18, 342, }, [21] = { 72, 20, 378, }, [22] = { 74, 22, 417, }, [23] = { 76, 24, 459, }, [24] = { 78, 27, 506, }, [25] = { 80, 29, 557, }, [26] = { 82, 32, 614, }, [27] = { 84, 36, 675, }, [28] = { 86, 39, 743, }, [29] = { 88, 43, 816, }, [30] = { 90, 47, 897, }, }, } skills["SupportBlasphemy"] = { name = "Blasphemy", gemTags = { intelligence = true, support = true, curse = true, aura = true, }, gemTagString = "Support, Curse, Aura", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 32, }, addSkillTypes = { 15, 16, 31, 44, }, excludeSkillTypes = { }, baseMods = { skill("manaCostOverride", 35), skill("cooldown", 0.5), --"curse_apply_as_aura" = ? }, qualityMods = { mod("CurseEffect", "INC", 0.5), --"curse_effect_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("AreaOfEffect", "INC", nil, 0, KeywordFlag.Curse), --"curse_area_of_effect_+%" }, levels = { [1] = { 31, 0, }, [2] = { 34, 4, }, [3] = { 36, 8, }, [4] = { 38, 12, }, [5] = { 40, 16, }, [6] = { 42, 20, }, [7] = { 44, 24, }, [8] = { 46, 28, }, [9] = { 48, 32, }, [10] = { 50, 36, }, [11] = { 52, 40, }, [12] = { 54, 44, }, [13] = { 56, 48, }, [14] = { 58, 52, }, [15] = { 60, 56, }, [16] = { 62, 60, }, [17] = { 64, 64, }, [18] = { 66, 68, }, [19] = { 68, 72, }, [20] = { 70, 76, }, [21] = { 72, 80, }, [22] = { 74, 84, }, [23] = { 76, 88, }, [24] = { 78, 92, }, [25] = { 80, 96, }, [26] = { 82, 100, }, [27] = { 84, 104, }, [28] = { 86, 108, }, [29] = { 88, 112, }, [30] = { 90, 116, }, }, } skills["SupportCastOnStunned"] = { name = "Cast when Stunned", gemTags = { intelligence = true, support = true, spell = true, trigger = true, }, gemTagString = "Support, Spell, Trigger", gemStr = 0, gemDex = 40, gemInt = 60, color = 3, support = true, requireSkillTypes = { 36, }, addSkillTypes = { 42, }, excludeSkillTypes = { 37, 41, 30, 44, 61, }, baseMods = { skill("cooldown", 0.25), skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ? skill("showAverage", true), --"base_skill_show_average_damage_instead_of_dps" = ? }, qualityMods = { mod("Damage", "INC", 0.5, 0, 0, nil), --"damage_+%" = 0.5 }, levelMods = { [1] = nil, --[2] = "cast_on_stunned_%" }, levels = { [1] = { 38, 50, }, [2] = { 40, 51, }, [3] = { 42, 52, }, [4] = { 44, 53, }, [5] = { 46, 54, }, [6] = { 48, 55, }, [7] = { 50, 56, }, [8] = { 52, 57, }, [9] = { 54, 58, }, [10] = { 56, 59, }, [11] = { 58, 60, }, [12] = { 60, 61, }, [13] = { 62, 62, }, [14] = { 64, 63, }, [15] = { 65, 64, }, [16] = { 66, 65, }, [17] = { 67, 66, }, [18] = { 68, 67, }, [19] = { 69, 68, }, [20] = { 70, 69, }, [21] = { 72, 70, }, [22] = { 74, 71, }, [23] = { 76, 72, }, [24] = { 78, 73, }, [25] = { 80, 74, }, [26] = { 82, 75, }, [27] = { 84, 76, }, [28] = { 86, 77, }, [29] = { 88, 78, }, [30] = { 90, 79, }, }, } skills["SupportCastWhileChannelling"] = { name = "Cast while Channelling", gemTags = { intelligence = true, support = true, channelling = true, spell = true, }, gemTagString = "Support, Channelling, Spell", gemStr = 0, gemDex = 40, gemInt = 60, color = 3, support = true, requireSkillTypes = { 58, 36, }, addSkillTypes = { }, excludeSkillTypes = { 30, 61, }, baseMods = { mod("ManaCost", "MORE", 40), skill("triggered", true, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"spell_uncastable_if_triggerable" = ? }, qualityMods = { mod("Damage", "INC", 0.5, 0, 0, nil), --"damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = skill("timeOverride", nil, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"cast_while_channelling_time_ms" [3] = mod("Damage", "MORE", nil, 0, 0, { type = "SkillType", skillType = SkillType.TriggerableSpell }), --"support_cast_while_channelling_triggered_skill_damage_+%_final" }, levels = { [1] = { 38, 0.45, 0, }, [2] = { 40, 0.44, 0, }, [3] = { 42, 0.44, 1, }, [4] = { 44, 0.43, 1, }, [5] = { 46, 0.43, 2, }, [6] = { 48, 0.42, 2, }, [7] = { 50, 0.42, 3, }, [8] = { 52, 0.41, 3, }, [9] = { 54, 0.41, 4, }, [10] = { 56, 0.4, 4, }, [11] = { 58, 0.4, 5, }, [12] = { 60, 0.39, 5, }, [13] = { 62, 0.39, 6, }, [14] = { 64, 0.38, 6, }, [15] = { 65, 0.38, 7, }, [16] = { 66, 0.37, 7, }, [17] = { 67, 0.37, 8, }, [18] = { 68, 0.36, 8, }, [19] = { 69, 0.36, 9, }, [20] = { 70, 0.35, 9, }, [21] = { 72, 0.35, 10, }, [22] = { 74, 0.34, 10, }, [23] = { 76, 0.34, 11, }, [24] = { 78, 0.33, 11, }, [25] = { 80, 0.33, 12, }, [26] = { 82, 0.32, 12, }, [27] = { 84, 0.32, 13, }, [28] = { 86, 0.31, 13, }, [29] = { 88, 0.31, 14, }, [30] = { 90, 0.3, 14, }, }, } skills["SupportChanceToIgnite"] = { name = "Chance to Ignite", gemTags = { fire = true, intelligence = true, support = true, }, gemTagString = "Fire, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 10), }, qualityMods = { mod("FireDamage", "INC", 0.5, ModFlag.Dot), --"burn_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("EnemyIgniteChance", "BASE", nil), --"base_chance_to_ignite_%" }, levels = { [1] = { 31, 30, }, [2] = { 34, 31, }, [3] = { 36, 32, }, [4] = { 38, 33, }, [5] = { 40, 34, }, [6] = { 42, 35, }, [7] = { 44, 36, }, [8] = { 46, 37, }, [9] = { 48, 38, }, [10] = { 50, 39, }, [11] = { 52, 40, }, [12] = { 54, 41, }, [13] = { 56, 42, }, [14] = { 58, 43, }, [15] = { 60, 44, }, [16] = { 62, 45, }, [17] = { 64, 46, }, [18] = { 66, 47, }, [19] = { 68, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportConcentratedEffect"] = { name = "Concentrated Effect", gemTags = { intelligence = true, support = true, area = true, }, gemTagString = "Support, AoE", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 11, 21, 53, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), mod("AreaOfEffect", "MORE", -30), --"support_concentrated_effect_skill_area_of_effect_+%_final" = -30 }, qualityMods = { mod("Damage", "INC", 0.5, ModFlag.Area), --"area_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Damage", "MORE", nil, ModFlag.Area), --"support_area_concentrate_area_damage_+%_final" }, levels = { [1] = { 18, 35, }, [2] = { 22, 36, }, [3] = { 26, 37, }, [4] = { 29, 38, }, [5] = { 32, 39, }, [6] = { 35, 40, }, [7] = { 38, 41, }, [8] = { 41, 42, }, [9] = { 44, 43, }, [10] = { 47, 44, }, [11] = { 50, 45, }, [12] = { 53, 46, }, [13] = { 56, 47, }, [14] = { 58, 48, }, [15] = { 60, 49, }, [16] = { 62, 50, }, [17] = { 64, 51, }, [18] = { 66, 52, }, [19] = { 68, 53, }, [20] = { 70, 54, }, [21] = { 72, 55, }, [22] = { 74, 56, }, [23] = { 76, 57, }, [24] = { 78, 58, }, [25] = { 80, 59, }, [26] = { 82, 60, }, [27] = { 84, 61, }, [28] = { 86, 62, }, [29] = { 88, 63, }, [30] = { 90, 64, }, }, } skills["SupportControlledDestruction"] = { name = "Controlled Destruction", gemTags = { spell = true, intelligence = true, support = true, }, gemTagString = "Spell, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, 59, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), mod("CritChance", "INC", -100, 0, 0, nil), --"critical_strike_chance_+%" = -100 }, qualityMods = { mod("Damage", "INC", 0.5, ModFlag.Spell, 0, nil), --"spell_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Damage", "MORE", nil, ModFlag.Spell), --"support_controlled_destruction_spell_damage_+%_final" }, levels = { [1] = { 18, 25, }, [2] = { 22, 26, }, [3] = { 26, 27, }, [4] = { 29, 28, }, [5] = { 32, 29, }, [6] = { 35, 30, }, [7] = { 38, 31, }, [8] = { 41, 32, }, [9] = { 44, 33, }, [10] = { 47, 34, }, [11] = { 50, 35, }, [12] = { 53, 36, }, [13] = { 56, 37, }, [14] = { 58, 38, }, [15] = { 60, 39, }, [16] = { 62, 40, }, [17] = { 64, 41, }, [18] = { 66, 42, }, [19] = { 68, 43, }, [20] = { 70, 44, }, [21] = { 72, 45, }, [22] = { 74, 46, }, [23] = { 76, 47, }, [24] = { 78, 48, }, [25] = { 80, 49, }, [26] = { 82, 50, }, [27] = { 84, 51, }, [28] = { 86, 52, }, [29] = { 88, 53, }, [30] = { 90, 54, }, }, } skills["SupportCurseOnHit"] = { name = "Curse On Hit", gemTags = { curse = true, trigger = true, intelligence = true, support = true, }, gemTagString = "Curse, Trigger, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 1, 10, 32, }, addSkillTypes = { }, excludeSkillTypes = { 37, 41, 44, }, baseMods = { --"apply_linked_curses_on_hit_%" = 100 --"cannot_cast_curses" = ? }, qualityMods = { mod("CurseEffect", "INC", 0.5), --"curse_effect_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Duration", "INC", nil, 0, KeywordFlag.Curse), --"base_curse_duration_+%" }, levels = { [1] = { 38, -50, }, [2] = { 40, -48, }, [3] = { 42, -46, }, [4] = { 44, -44, }, [5] = { 46, -42, }, [6] = { 48, -40, }, [7] = { 50, -38, }, [8] = { 52, -36, }, [9] = { 54, -34, }, [10] = { 56, -32, }, [11] = { 58, -30, }, [12] = { 60, -28, }, [13] = { 62, -26, }, [14] = { 64, -24, }, [15] = { 65, -22, }, [16] = { 66, -20, }, [17] = { 67, -18, }, [18] = { 68, -16, }, [19] = { 69, -14, }, [20] = { 70, -12, }, [21] = { 72, -10, }, [22] = { 74, -8, }, [23] = { 76, -6, }, [24] = { 78, -4, }, [25] = { 80, -2, }, [26] = { 82, 0, }, [27] = { 84, 2, }, [28] = { 86, 4, }, [29] = { 88, 6, }, [30] = { 90, 8, }, }, } skills["SupportElementalFocus"] = { name = "Elemental Focus", gemTags = { intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, 29, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), --"cannot_inflict_status_ailments" = ? flag("CannotShock"), flag("CannotChill"), flag("CannotFreeze"), flag("CannotIgnite"), }, qualityMods = { mod("ElementalDamage", "INC", 0.5), --"elemental_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("ElementalDamage", "MORE", nil), --"support_gem_elemental_damage_+%_final" }, levels = { [1] = { 18, 30, }, [2] = { 22, 31, }, [3] = { 26, 32, }, [4] = { 29, 33, }, [5] = { 32, 34, }, [6] = { 35, 35, }, [7] = { 38, 36, }, [8] = { 41, 37, }, [9] = { 44, 38, }, [10] = { 47, 39, }, [11] = { 50, 40, }, [12] = { 53, 41, }, [13] = { 56, 42, }, [14] = { 58, 43, }, [15] = { 60, 44, }, [16] = { 62, 45, }, [17] = { 64, 46, }, [18] = { 66, 47, }, [19] = { 68, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportElementalProliferation"] = { name = "Elemental Proliferation", gemTags = { cold = true, fire = true, lightning = true, intelligence = true, support = true, area = true, }, gemTagString = "Cold, Fire, Lightning, Support, AoE", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, 20, }, addSkillTypes = { 11, }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), --"elemental_status_effect_aura_radius" = 16 --"display_what_elemental_proliferation_does" = 1 }, qualityMods = { mod("EnemyIgniteDuration", "INC", 0.5), --"ignite_duration_+%" = 0.5 mod("EnemyChillDuration", "INC", 0.5), --"chill_duration_+%" = 0.5 mod("EnemyFreezeDuration", "INC", 0.5), --"freeze_duration_+%" = 0.5 mod("EnemyShockDuration", "INC", 0.5), --"shock_duration_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Damage", "MORE", nil), --"support_elemental_proliferation_damage_+%_final" }, levels = { [1] = { 38, -30, }, [2] = { 40, -30, }, [3] = { 42, -29, }, [4] = { 44, -29, }, [5] = { 46, -28, }, [6] = { 48, -28, }, [7] = { 50, -27, }, [8] = { 52, -27, }, [9] = { 54, -26, }, [10] = { 56, -26, }, [11] = { 58, -25, }, [12] = { 60, -25, }, [13] = { 62, -24, }, [14] = { 64, -24, }, [15] = { 65, -23, }, [16] = { 66, -23, }, [17] = { 67, -22, }, [18] = { 68, -22, }, [19] = { 69, -21, }, [20] = { 70, -21, }, [21] = { 72, -20, }, [22] = { 74, -20, }, [23] = { 76, -19, }, [24] = { 78, -19, }, [25] = { 80, -18, }, [26] = { 82, -18, }, [27] = { 84, -17, }, [28] = { 86, -17, }, [29] = { 88, -16, }, [30] = { 90, -16, }, }, } skills["SupportAdditionalXP"] = { name = "Enlighten", gemTags = { low_max_level = true, intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { }, qualityMods = { --"local_gem_experience_gain_+%" = 5 }, levelMods = { [1] = nil, [2] = mod("ManaCost", "MORE", nil), }, levels = { [1] = { 1, nil, }, [2] = { 10, -4, }, [3] = { 45, -8, }, [4] = { 60, -12, }, [5] = { 75, -16, }, [6] = { 90, -20, }, [7] = { 100, -24, }, [8] = { 100, -28, }, [9] = { 100, -32, }, [10] = { 100, -36, }, }, } skills["SupportFasterCast"] = { name = "Faster Casting", gemTags = { intelligence = true, support = true, spell = true, }, gemTagString = "Support, Spell", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 2, 39, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 20), }, qualityMods = { mod("Speed", "INC", 0.5, ModFlag.Cast), --"base_cast_speed_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Speed", "INC", nil, ModFlag.Cast), --"base_cast_speed_+%" }, levels = { [1] = { 18, 20, }, [2] = { 22, 21, }, [3] = { 26, 22, }, [4] = { 29, 23, }, [5] = { 32, 24, }, [6] = { 35, 25, }, [7] = { 38, 26, }, [8] = { 41, 27, }, [9] = { 44, 28, }, [10] = { 47, 29, }, [11] = { 50, 30, }, [12] = { 53, 31, }, [13] = { 56, 32, }, [14] = { 58, 33, }, [15] = { 60, 34, }, [16] = { 62, 35, }, [17] = { 64, 36, }, [18] = { 66, 37, }, [19] = { 68, 38, }, [20] = { 70, 39, }, [21] = { 72, 40, }, [22] = { 74, 41, }, [23] = { 76, 42, }, [24] = { 78, 43, }, [25] = { 80, 44, }, [26] = { 82, 45, }, [27] = { 84, 46, }, [28] = { 86, 47, }, [29] = { 88, 48, }, [30] = { 90, 49, }, }, } skills["SupportIncreasedAreaOfEffect"] = { name = "Increased Area of Effect", gemTags = { intelligence = true, support = true, area = true, }, gemTagString = "Support, AoE", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 11, 21, 53, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), }, qualityMods = { mod("Damage", "INC", 0.5, ModFlag.Area), --"area_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("AreaOfEffect", "INC", nil), --"base_skill_area_of_effect_+%" }, levels = { [1] = { 38, 30, }, [2] = { 40, 31, }, [3] = { 42, 32, }, [4] = { 44, 33, }, [5] = { 46, 34, }, [6] = { 48, 35, }, [7] = { 50, 36, }, [8] = { 52, 37, }, [9] = { 54, 38, }, [10] = { 56, 39, }, [11] = { 58, 40, }, [12] = { 60, 41, }, [13] = { 62, 42, }, [14] = { 64, 43, }, [15] = { 65, 44, }, [16] = { 66, 45, }, [17] = { 67, 46, }, [18] = { 68, 47, }, [19] = { 69, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportIncreasedCriticalDamage"] = { name = "Increased Critical Damage", gemTags = { intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), }, qualityMods = { mod("CritMultiplier", "BASE", 0.75, 0, 0, nil), --"base_critical_strike_multiplier_+" = 0.75 }, levelMods = { [1] = nil, [2] = mod("CritMultiplier", "BASE", nil, 0, 0, nil), --"base_critical_strike_multiplier_+" }, levels = { [1] = { 18, 75, }, [2] = { 22, 76, }, [3] = { 26, 78, }, [4] = { 29, 79, }, [5] = { 32, 81, }, [6] = { 35, 82, }, [7] = { 38, 84, }, [8] = { 41, 85, }, [9] = { 44, 87, }, [10] = { 47, 88, }, [11] = { 50, 90, }, [12] = { 53, 91, }, [13] = { 56, 93, }, [14] = { 58, 94, }, [15] = { 60, 96, }, [16] = { 62, 97, }, [17] = { 64, 99, }, [18] = { 66, 100, }, [19] = { 68, 102, }, [20] = { 70, 103, }, [21] = { 72, 105, }, [22] = { 74, 106, }, [23] = { 76, 108, }, [24] = { 78, 109, }, [25] = { 80, 111, }, [26] = { 82, 112, }, [27] = { 84, 114, }, [28] = { 86, 115, }, [29] = { 88, 117, }, [30] = { 90, 118, }, }, } skills["SupportIncreasedCriticalStrikes"] = { name = "Increased Critical Strikes", gemTags = { intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 15), }, qualityMods = { mod("CritChance", "INC", 1, 0, 0, nil), --"critical_strike_chance_+%" = 1 }, levelMods = { [1] = nil, [2] = mod("CritChance", "INC", nil, 0, 0, nil), --"critical_strike_chance_+%" [3] = mod("CritChance", "BASE", nil, 0, 0, nil), --"additional_base_critical_strike_chance" }, levels = { [1] = { 8, 50, 1, }, [2] = { 10, 52, 1, }, [3] = { 13, 54, 1.1, }, [4] = { 17, 56, 1.1, }, [5] = { 21, 58, 1.2, }, [6] = { 25, 60, 1.2, }, [7] = { 29, 62, 1.3, }, [8] = { 33, 64, 1.3, }, [9] = { 37, 66, 1.4, }, [10] = { 40, 68, 1.4, }, [11] = { 43, 70, 1.5, }, [12] = { 46, 72, 1.5, }, [13] = { 49, 74, 1.6, }, [14] = { 52, 76, 1.6, }, [15] = { 55, 78, 1.7, }, [16] = { 58, 80, 1.7, }, [17] = { 61, 82, 1.8, }, [18] = { 64, 84, 1.8, }, [19] = { 67, 86, 1.9, }, [20] = { 70, 88, 1.9, }, [21] = { 72, 90, 2, }, [22] = { 74, 92, 2, }, [23] = { 76, 94, 2.1, }, [24] = { 78, 96, 2.1, }, [25] = { 80, 98, 2.2, }, [26] = { 82, 100, 2.2, }, [27] = { 84, 102, 2.3, }, [28] = { 86, 104, 2.3, }, [29] = { 88, 106, 2.4, }, [30] = { 90, 108, 2.4, }, }, } skills["SupportOnslaughtOnSlayingShockedEnemy"] = { name = "Innervate", gemTags = { lightning = true, intelligence = true, support = true, }, gemTagString = "Lightning, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 10), mod("EnemyShockChance", "BASE", 15), --"base_chance_to_shock_%" = 15 }, qualityMods = { mod("EnemyShockDuration", "INC", 1.5), --"shock_duration_+%" = 1.5 }, levelMods = { [1] = nil, --[2] = "onslaught_time_granted_on_killing_shocked_enemy_ms" }, levels = { [1] = { 31, 5000, }, [2] = { 34, 5100, }, [3] = { 36, 5200, }, [4] = { 38, 5300, }, [5] = { 40, 5400, }, [6] = { 42, 5500, }, [7] = { 44, 5600, }, [8] = { 46, 5700, }, [9] = { 48, 5800, }, [10] = { 50, 5900, }, [11] = { 52, 6000, }, [12] = { 54, 6100, }, [13] = { 56, 6200, }, [14] = { 58, 6300, }, [15] = { 60, 6400, }, [16] = { 62, 6500, }, [17] = { 64, 6600, }, [18] = { 66, 6700, }, [19] = { 68, 6800, }, [20] = { 70, 6900, }, [21] = { 72, 7000, }, [22] = { 74, 7100, }, [23] = { 76, 7200, }, [24] = { 78, 7300, }, [25] = { 80, 7400, }, [26] = { 82, 7500, }, [27] = { 84, 7600, }, [28] = { 86, 7700, }, [29] = { 88, 7800, }, [30] = { 90, 7900, }, }, } skills["SupportItemRarity"] = { name = "Item Rarity", gemTags = { intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, 40, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { }, qualityMods = { mod("LootRarity", "INC", 0.5), --"base_killed_monster_dropped_item_rarity_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("LootRarity", "INC", nil), --"base_killed_monster_dropped_item_rarity_+%" }, levels = { [1] = { 31, 40, }, [2] = { 34, 41, }, [3] = { 36, 42, }, [4] = { 38, 43, }, [5] = { 40, 44, }, [6] = { 42, 45, }, [7] = { 44, 46, }, [8] = { 46, 47, }, [9] = { 48, 48, }, [10] = { 50, 49, }, [11] = { 52, 50, }, [12] = { 54, 51, }, [13] = { 56, 52, }, [14] = { 58, 53, }, [15] = { 60, 54, }, [16] = { 62, 55, }, [17] = { 64, 56, }, [18] = { 66, 57, }, [19] = { 68, 58, }, [20] = { 70, 59, }, [21] = { 72, 60, }, [22] = { 74, 61, }, [23] = { 76, 62, }, [24] = { 78, 63, }, [25] = { 80, 64, }, [26] = { 82, 65, }, [27] = { 84, 66, }, [28] = { 86, 67, }, [29] = { 88, 68, }, [30] = { 90, 69, }, }, } skills["SupportLightningPenetration"] = { name = "Lightning Penetration", gemTags = { lightning = true, intelligence = true, support = true, }, gemTagString = "Lightning, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), }, qualityMods = { mod("LightningDamage", "INC", 0.5), --"lightning_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("LightningPenetration", "BASE", nil), --"base_reduce_enemy_lightning_resistance_%" }, levels = { [1] = { 31, 18, }, [2] = { 34, 19, }, [3] = { 36, 20, }, [4] = { 38, 21, }, [5] = { 40, 22, }, [6] = { 42, 23, }, [7] = { 44, 24, }, [8] = { 46, 25, }, [9] = { 48, 26, }, [10] = { 50, 27, }, [11] = { 52, 28, }, [12] = { 54, 29, }, [13] = { 56, 30, }, [14] = { 58, 31, }, [15] = { 60, 32, }, [16] = { 62, 33, }, [17] = { 64, 34, }, [18] = { 66, 35, }, [19] = { 68, 36, }, [20] = { 70, 37, }, [21] = { 72, 38, }, [22] = { 74, 39, }, [23] = { 76, 40, }, [24] = { 78, 41, }, [25] = { 80, 42, }, [26] = { 82, 43, }, [27] = { 84, 44, }, [28] = { 86, 45, }, [29] = { 88, 46, }, [30] = { 90, 47, }, }, } skills["SupportMinefield"] = { name = "Minefield", gemTags = { intelligence = true, support = true, mine = true, }, gemTagString = "Support, Mine", gemStr = 0, gemDex = 40, gemInt = 60, color = 3, support = true, requireSkillTypes = { 41, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 60), --"number_of_additional_mines_to_place" = 2 mod("ActiveMineLimit", "BASE", 2), --"number_of_additional_remote_mines_allowed" = 2 }, qualityMods = { mod("MineDetonationAreaOfEffect", "INC", 1), --"mine_detonation_radius_+%" = 1 }, levelMods = { [1] = nil, [2] = mod("Damage", "MORE", nil), --"support_minefield_mine_damage_+%_final" }, levels = { [1] = { 8, -40, }, [2] = { 10, -39, }, [3] = { 13, -38, }, [4] = { 17, -37, }, [5] = { 21, -36, }, [6] = { 25, -35, }, [7] = { 29, -34, }, [8] = { 33, -33, }, [9] = { 37, -32, }, [10] = { 40, -31, }, [11] = { 43, -30, }, [12] = { 46, -29, }, [13] = { 49, -28, }, [14] = { 52, -27, }, [15] = { 55, -26, }, [16] = { 58, -25, }, [17] = { 61, -24, }, [18] = { 64, -23, }, [19] = { 67, -22, }, [20] = { 70, -21, }, [21] = { 72, -20, }, [22] = { 74, -19, }, [23] = { 76, -18, }, [24] = { 78, -17, }, [25] = { 80, -16, }, [26] = { 82, -15, }, [27] = { 84, -14, }, [28] = { 86, -13, }, [29] = { 88, -12, }, [30] = { 90, -11, }, }, } skills["SupportMinionDamage"] = { name = "Minion Damage", gemTags = { intelligence = true, support = true, minion = true, }, gemTagString = "Support, Minion", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 9, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 30), }, qualityMods = { mod("MinionModifier", "LIST", { mod = mod("Damage", "INC", 0.75) }), --"minion_damage_+%" = 0.75 }, levelMods = { [1] = nil, [2] = mod("MinionModifier", "LIST", { mod = mod("Damage", "MORE", nil) }), --"support_minion_damage_+%_final" }, levels = { [1] = { 8, 30, }, [2] = { 10, 31, }, [3] = { 13, 32, }, [4] = { 17, 33, }, [5] = { 21, 34, }, [6] = { 25, 35, }, [7] = { 29, 36, }, [8] = { 33, 37, }, [9] = { 37, 38, }, [10] = { 40, 39, }, [11] = { 43, 40, }, [12] = { 46, 41, }, [13] = { 49, 42, }, [14] = { 52, 43, }, [15] = { 55, 44, }, [16] = { 58, 45, }, [17] = { 61, 46, }, [18] = { 64, 47, }, [19] = { 67, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportMinionLife"] = { name = "Minion Life", gemTags = { intelligence = true, support = true, minion = true, }, gemTagString = "Support, Minion", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 9, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), }, qualityMods = { mod("MinionModifier", "LIST", { mod = mod("Life", "INC", 0.75) }), --"minion_maximum_life_+%" = 0.75 }, levelMods = { [1] = nil, [2] = mod("MinionModifier", "LIST", { mod = mod("Life", "INC", nil) }), --"minion_maximum_life_+%" }, levels = { [1] = { 18, 30, }, [2] = { 22, 31, }, [3] = { 26, 32, }, [4] = { 29, 33, }, [5] = { 32, 34, }, [6] = { 35, 35, }, [7] = { 38, 36, }, [8] = { 41, 37, }, [9] = { 44, 38, }, [10] = { 47, 39, }, [11] = { 50, 40, }, [12] = { 53, 41, }, [13] = { 56, 42, }, [14] = { 58, 43, }, [15] = { 60, 44, }, [16] = { 62, 45, }, [17] = { 64, 46, }, [18] = { 66, 47, }, [19] = { 68, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportMinionSpeed"] = { name = "Minion Speed", gemTags = { movement = true, intelligence = true, support = true, minion = true, }, gemTagString = "Movement, Support, Minion", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 9, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), }, qualityMods = { mod("MinionModifier", "LIST", { mod = mod("MovementSpeed", "INC", 0.5) }), --"minion_movement_speed_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("MinionModifier", "LIST", { mod = mod("MovementSpeed", "INC", nil) }), --"minion_movement_speed_+%" [3] = mod("MinionModifier", "LIST", { mod = mod("Speed", "INC", nil, ModFlag.Attack) }), --"minion_attack_speed_+%" [4] = mod("MinionModifier", "LIST", { mod = mod("Speed", "INC", nil, ModFlag.Cast) }), --"minion_cast_speed_+%" }, levels = { [1] = { 18, 25, 10, 10, }, [2] = { 22, 26, 10, 10, }, [3] = { 26, 27, 11, 11, }, [4] = { 29, 28, 11, 11, }, [5] = { 32, 29, 12, 12, }, [6] = { 35, 30, 12, 12, }, [7] = { 38, 31, 13, 13, }, [8] = { 41, 32, 13, 13, }, [9] = { 44, 33, 14, 14, }, [10] = { 47, 34, 14, 14, }, [11] = { 50, 35, 15, 15, }, [12] = { 53, 36, 15, 15, }, [13] = { 56, 37, 16, 16, }, [14] = { 58, 38, 16, 16, }, [15] = { 60, 39, 17, 17, }, [16] = { 62, 40, 17, 17, }, [17] = { 64, 41, 18, 18, }, [18] = { 66, 42, 18, 18, }, [19] = { 68, 43, 19, 19, }, [20] = { 70, 44, 19, 19, }, [21] = { 72, 45, 20, 20, }, [22] = { 74, 46, 20, 20, }, [23] = { 76, 47, 21, 21, }, [24] = { 78, 48, 21, 21, }, [25] = { 80, 49, 22, 22, }, [26] = { 82, 50, 22, 22, }, [27] = { 84, 51, 23, 23, }, [28] = { 86, 52, 23, 23, }, [29] = { 88, 53, 24, 24, }, [30] = { 90, 54, 24, 24, }, }, } skills["SupportSummonElementalResistances"] = { name = "Minion and Totem Elemental Resistance", gemTags = { intelligence = true, support = true, minion = true, }, gemTagString = "Support, Minion", gemStr = 40, gemDex = 0, gemInt = 60, color = 3, support = true, requireSkillTypes = { 9, 30, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 40), }, qualityMods = { mod("MinionModifier", "LIST", { mod = mod("FireResist", "BASE", 0.5) }), --"summon_fire_resistance_+" = 0.5 mod("MinionModifier", "LIST", { mod = mod("ColdResist", "BASE", 0.5) }), --"summon_cold_resistance_+" = 0.5 mod("MinionModifier", "LIST", { mod = mod("LightningResist", "BASE", 0.5) }), --"summon_lightning_resistance_+" = 0.5 }, levelMods = { [1] = nil, [2] = mod("MinionModifier", "LIST", { mod = mod("FireResist", "BASE", nil) }), --"summon_fire_resistance_+" [3] = mod("MinionModifier", "LIST", { mod = mod("ColdResist", "BASE", nil) }), --"summon_cold_resistance_+" [4] = mod("MinionModifier", "LIST", { mod = mod("LightningResist", "BASE", nil) }), --"summon_lightning_resistance_+" [5] = { mod("ElementalDamage", "MORE", nil, 0, KeywordFlag.Totem), mod("MinionModifier", "LIST", { mod = mod("ElementalDamage", "MORE", nil) }) }, --"support_minion_totem_resistance_elemental_damage_+%_final" }, levels = { [1] = { 31, 25, 25, 25, 10, }, [2] = { 34, 26, 26, 26, 10, }, [3] = { 36, 27, 27, 27, 11, }, [4] = { 38, 28, 28, 28, 11, }, [5] = { 40, 29, 29, 29, 12, }, [6] = { 42, 30, 30, 30, 12, }, [7] = { 44, 31, 31, 31, 13, }, [8] = { 46, 32, 32, 32, 13, }, [9] = { 48, 33, 33, 33, 14, }, [10] = { 50, 34, 34, 34, 14, }, [11] = { 52, 35, 35, 35, 15, }, [12] = { 54, 36, 36, 36, 15, }, [13] = { 56, 37, 37, 37, 16, }, [14] = { 58, 38, 38, 38, 16, }, [15] = { 60, 39, 39, 39, 17, }, [16] = { 62, 40, 40, 40, 17, }, [17] = { 64, 41, 41, 41, 18, }, [18] = { 66, 42, 42, 42, 18, }, [19] = { 68, 43, 43, 43, 19, }, [20] = { 70, 44, 44, 44, 19, }, [21] = { 72, 45, 45, 45, 20, }, [22] = { 74, 46, 46, 46, 20, }, [23] = { 76, 47, 47, 47, 21, }, [24] = { 78, 48, 48, 48, 21, }, [25] = { 80, 49, 49, 49, 22, }, [26] = { 82, 50, 50, 50, 22, }, [27] = { 84, 51, 51, 51, 23, }, [28] = { 86, 52, 52, 52, 23, }, [29] = { 88, 53, 53, 53, 24, }, [30] = { 90, 54, 54, 54, 24, }, }, } skills["SupportPhysicalToLightning"] = { name = "Physical to Lightning", gemTags = { lightning = true, intelligence = true, support = true, }, gemTagString = "Lightning, Support", gemStr = 40, gemDex = 0, gemInt = 60, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 10), mod("SkillPhysicalDamageConvertToLightning", "BASE", 50), --"skill_physical_damage_%_to_convert_to_lightning" = 50 }, qualityMods = { mod("PhysicalDamage", "INC", 0.5), --"physical_damage_+%" = 0.5 mod("LightningDamage", "INC", 0.5), --"lightning_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("PhysicalDamageGainAsLightning", "BASE", nil, 0, 0, nil), --"physical_damage_%_to_add_as_lightning" }, levels = { [1] = { 18, 10, }, [2] = { 22, 11, }, [3] = { 26, 12, }, [4] = { 29, 13, }, [5] = { 32, 14, }, [6] = { 35, 15, }, [7] = { 38, 16, }, [8] = { 41, 17, }, [9] = { 44, 18, }, [10] = { 47, 19, }, [11] = { 50, 20, }, [12] = { 53, 21, }, [13] = { 56, 22, }, [14] = { 58, 23, }, [15] = { 60, 24, }, [16] = { 62, 25, }, [17] = { 64, 26, }, [18] = { 66, 27, }, [19] = { 68, 28, }, [20] = { 70, 29, }, [21] = { 72, 30, }, [22] = { 74, 31, }, [23] = { 76, 32, }, [24] = { 78, 33, }, [25] = { 80, 34, }, [26] = { 82, 35, }, [27] = { 84, 36, }, [28] = { 86, 37, }, [29] = { 88, 38, }, [30] = { 90, 39, }, }, } skills["SupportPowerChargeOnCrit"] = { name = "Power Charge On Critical", gemTags = { intelligence = true, support = true, }, gemTagString = "Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 10, 1, }, addSkillTypes = { }, excludeSkillTypes = { }, baseMods = { mod("ManaCost", "MORE", 10), }, qualityMods = { mod("CritChance", "INC", 1, 0, 0, nil), --"critical_strike_chance_+%" = 1 }, levelMods = { [1] = nil, --[2] = "add_power_charge_on_critical_strike_%" }, levels = { [1] = { 18, 35, }, [2] = { 22, 36, }, [3] = { 26, 37, }, [4] = { 29, 38, }, [5] = { 32, 39, }, [6] = { 35, 40, }, [7] = { 38, 41, }, [8] = { 41, 42, }, [9] = { 44, 43, }, [10] = { 47, 44, }, [11] = { 50, 45, }, [12] = { 53, 46, }, [13] = { 56, 47, }, [14] = { 58, 48, }, [15] = { 60, 49, }, [16] = { 62, 50, }, [17] = { 64, 51, }, [18] = { 66, 52, }, [19] = { 68, 53, }, [20] = { 70, 54, }, [21] = { 72, 55, }, [22] = { 74, 56, }, [23] = { 76, 57, }, [24] = { 78, 58, }, [25] = { 80, 59, }, [26] = { 82, 60, }, [27] = { 84, 61, }, [28] = { 86, 62, }, [29] = { 88, 63, }, [30] = { 90, 64, }, }, } skills["SupportRemoteMine"] = { name = "Remote Mine", gemTags = { intelligence = true, support = true, mine = true, duration = true, }, gemTagString = "Support, Mine, Duration", gemStr = 0, gemDex = 40, gemInt = 60, color = 3, support = true, requireSkillTypes = { 19, }, addSkillTypes = { 12, 41, }, excludeSkillTypes = { 61, }, addFlags = { mine = true, duration = true, }, baseMods = { mod("ManaCost", "MORE", 50), --"is_remote_mine" = 1 --"base_mine_duration" = 16000 --"mine_override_pvp_scaling_time_ms" = 900 --"base_skill_is_mined" = ? --"disable_skill_if_melee_attack" = ? skill("showAverage", true, { type = "SkillType", skillType = SkillType.SkillCanMine }), --"base_skill_show_average_damage_instead_of_dps" = ? }, qualityMods = { mod("MineLayingSpeed", "MORE", 0.5), --"mine_laying_speed_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Damage", "MORE", nil, ModFlag.Hit, KeywordFlag.Mine), --"support_remote_mine_hit_damage_+%_final" }, levels = { [1] = { 8, 30, }, [2] = { 10, 31, }, [3] = { 13, 32, }, [4] = { 17, 33, }, [5] = { 21, 34, }, [6] = { 25, 35, }, [7] = { 29, 36, }, [8] = { 33, 37, }, [9] = { 37, 38, }, [10] = { 40, 39, }, [11] = { 43, 40, }, [12] = { 46, 41, }, [13] = { 49, 42, }, [14] = { 52, 43, }, [15] = { 55, 44, }, [16] = { 58, 45, }, [17] = { 61, 46, }, [18] = { 64, 47, }, [19] = { 67, 48, }, [20] = { 70, 49, }, [21] = { 72, 50, }, [22] = { 74, 51, }, [23] = { 76, 52, }, [24] = { 78, 53, }, [25] = { 80, 54, }, [26] = { 82, 55, }, [27] = { 84, 56, }, [28] = { 86, 57, }, [29] = { 88, 58, }, [30] = { 90, 59, }, }, } skills["SupportMulticast"] = { name = "Spell Echo", gemTags = { spell = true, intelligence = true, support = true, }, gemTagString = "Spell, Support", gemStr = 0, gemDex = 0, gemInt = 100, color = 3, support = true, requireSkillTypes = { 26, }, addSkillTypes = { }, excludeSkillTypes = { 30, 37, 41, 42, 15, }, baseMods = { mod("ManaCost", "MORE", 40), skill("repeatCount", 1), --"base_spell_repeat_count" = 1 mod("Damage", "MORE", -10), --"support_echo_damage_+%_final" = -10 }, qualityMods = { mod("Damage", "INC", 0.5, ModFlag.Spell, 0, nil), --"spell_damage_+%" = 0.5 }, levelMods = { [1] = nil, [2] = mod("Speed", "MORE", nil, ModFlag.Cast), --"support_multicast_cast_speed_+%_final" }, levels = { [1] = { 38, 51, }, [2] = { 40, 52, }, [3] = { 42, 53, }, [4] = { 44, 54, }, [5] = { 46, 55, }, [6] = { 48, 56, }, [7] = { 50, 57, }, [8] = { 52, 58, }, [9] = { 54, 59, }, [10] = { 56, 60, }, [11] = { 58, 61, }, [12] = { 60, 62, }, [13] = { 62, 63, }, [14] = { 64, 64, }, [15] = { 65, 65, }, [16] = { 66, 66, }, [17] = { 67, 67, }, [18] = { 68, 68, }, [19] = { 69, 69, }, [20] = { 70, 70, }, [21] = { 72, 71, }, [22] = { 74, 72, }, [23] = { 76, 73, }, [24] = { 78, 74, }, [25] = { 80, 75, }, [26] = { 82, 76, }, [27] = { 84, 77, }, [28] = { 86, 78, }, [29] = { 88, 79, }, [30] = { 90, 80, }, }, }
mit
Whit3Tig3R/SpammBot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
theonlywild/erfaan
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
Daniex0r/project-roleplay-rp
resources/prp_ryby/client.lua
1
6810
local x,y=guiGetScreenSize() actual= { } respawn = 2 rysowanie_enable=0 przesuniecie=2 status_okregu=0 client_marker=nil ryby_zlowione=0 ryby_combo=0 kurs_ryb=1 function rybyStart(marker) setTimer(function() setElementFrozen(localPlayer,true) end,300,1) rybyTimer=setTimer(function() respawn=(respawn)-1 if respawn<0 then respawn=2 end end,300,0) kolko=guiCreateStaticImage(x/2-64,80,64,64,"circle.PNG",false) addEventHandler("onClientRender",root,rysujGre) addEventHandler("onClientRender",root,ryby) setTimer(function() zbindujKlawisze() end,500,1) client_marker=marker local a,b,c,a1,b1,c1=getCameraMatrix() local a2,b2,c2=getElementPosition(localPlayer) smoothMoveCamera(a,b,c,a1,b1,c1,a,b-15,c+2,a2,b2,c2,1000) toggleAllControls(false) ryby_zlowione=0 end addEvent("rybyStart",true) addEventHandler("rybyStart",root,rybyStart) function rysujGre() if respawn < 1 then if rysowanie_enable == 0 then rysowanie_enable = 1 setTimer(function() rysowanie_enable=0 end,300,1) typ_strzaly=math.random(1,4) if typ_strzaly==1 then strzala=guiCreateStaticImage(x/2+200,100,32,32,"arrow.PNG",false) setElementData(strzala,"kierunek","lewo") elseif typ_strzaly==2 then strzala=guiCreateStaticImage(x/2+200,100,32,32,"arrow2.PNG",false) setElementData(strzala,"kierunek","prawo") elseif typ_strzaly==3 then strzala=guiCreateStaticImage(x/2+200,100,32,32,"arrow3.PNG",false) setElementData(strzala,"kierunek","gora") elseif typ_strzaly==4 then strzala=guiCreateStaticImage(x/2+200,100,32,32,"arrow4.PNG",false) setElementData(strzala,"kierunek","dol") end setElementData(strzala,"ryby",1) end end for i,img in ipairs (getElementsByType('gui-staticimage')) do if getElementData(img,"ryby")==1 then local xg,yg=guiGetPosition(img,false) if xg<x/2-200 then destroyElement(img) else guiSetPosition(img,xg-przesuniecie,yg,false) end if xg > x/2-64 then if xg < x/2 then status_okregu=0 grot=getElementData(img,"kierunek") else status_okregu=1 end end end end end function zbindujKlawisze() bindKey("arrow_l","up",grajKolko) bindKey("arrow_r","up",grajKolko) bindKey("arrow_u","up",grajKolko) bindKey("arrow_d","up",grajKolko) bindKey("e","up",opuscGre) end klawisz=0 function grajKolko(key,keystate) if klawisz == 0 then if key == "arrow_l" then if grot == "lewo" then rybyCombo() end elseif key == "arrow_r" then if grot == "prawo" then rybyCombo() end elseif key == "arrow_u" then if grot == "gora" then rybyCombo() end elseif key == "arrow_d" then if grot == "dol" then rybyCombo() end end klawisz = 1 setTimer(function() klawisz=0 end,300,1) end end function opuscGre() killTimer(rybyTimer) outputChatBox("[INFO]Złowiłeś "..ryby_zlowione.." ryb(y)! Pamiętaj,aby je sprzedać!",255,255,255) removeEventHandler("onClientRender",root,rysujGre) removeEventHandler("onClientRender",root,ryby) destroyElement(kolko) unbindKey("arrow_l","up",grajKolko) unbindKey("arrow_r","up",grajKolko) unbindKey("arrow_u","up",grajKolko) unbindKey("arrow_d","up",grajKolko) unbindKey("e","up",opuscGre) setElementFrozen(localPlayer,false) setCameraTarget(localPlayer,localPlayer) setElementData(client_marker,"ryby_enabled",true) toggleAllControls(true) for i , img in ipairs (getElementsByType("gui-staticimage")) do destroyElement(img) end setElementData(localPlayer,"ryby_zlowione",getElementData(localPlayer,"ryby_zlowione")+ryby_zlowione) end local sm = {} sm.object1, sm.object2 = nil, nil local function camRender () local x1, y1, z1 = getElementPosition ( sm.object1 ) local x2, y2, z2 = getElementPosition ( sm.object2 ) setCameraMatrix ( x1, y1, z1, x2, y2, z2 ) end function smoothMoveCamera ( x1, y1, z1, x1t, y1t, z1t, x2, y2, z2, x2t, y2t, z2t, timez ) sm.object1 = createObject ( 1337, x1, y1, z1 ) sm.object2 = createObject ( 1337, x1t, y1t, z1t ) setElementAlpha ( sm.object1, 0 ) setElementAlpha ( sm.object2, 0 ) setObjectScale(sm.object1, 0.01) setObjectScale(sm.object2, 0.01) moveObject ( sm.object1, timez, x2, y2, z2, 0, 0, 0, "InOutQuad" ) moveObject ( sm.object2, timez, x2t, y2t, z2t, 0, 0, 0, "InOutQuad" ) addEventHandler ( "onClientPreRender", getRootElement(), camRender ) setTimer ( destroyElement, timez,1, sm.object1 ) setTimer ( destroyElement, timez, 1, sm.object2 ) setTimer(function() removeEventHandler ( "onClientPreRender", getRootElement(), camRender ) end,timez,1) return true end function rybyInfo() local x, y = guiGetScreenSize() local markery = getElementsByType("marker") for k,v in ipairs(markery) do local x1,y1,z1 = getElementPosition (getLocalPlayer()) local x2,y2,z2 = getElementPosition (v) local visibleto = getDistanceBetweenPoints3D(x1,y1,z1,x2,y2,z2) if visibleto > 40 then else local sx,sy = getScreenFromWorldPosition ( x2,y2,z2+1.05 ) if not sx and not sy then else if getElementData(v,"ryby_marker") == true then if getElementData(v,"ryby_enabled") == true then dxDrawText ( "Wędkarstwo", sx,sy-70,sx,sy, tocolor(255,255,255,255), 1.7-visibleto/50, "default-small", "center","top",false,false,false ) end if getElementData(v,"ryby_baza") == true then dxDrawText ( "Hurtownia ryb", sx,sy-70,sx,sy, tocolor(255,255,255,255), 1.7-visibleto/50, "default-small", "center","top",false,false,false ) end end end end end end addEventHandler("onClientRender",getRootElement(),rybyInfo) function ryby() local x, y = guiGetScreenSize() dxDrawText ( " Złowione ryby: "..ryby_zlowione..".", x/2+100,y-100,200,200, tocolor(255,255,255,255), 2, "default-small", "center","top",false,false,false ) dxDrawText ( "Używaj strzałek, aby łowić ryby.", x/2+100,y-50,200,200, tocolor(255,255,255,255), 2, "default-small", "center","top",false,false,false ) dxDrawText ( "Naciśnij E, aby opuścić wędkarstwo.", x/2+100,y-30,200,200, tocolor(255,255,255,255), 2, "default-small", "center","top",false,false,false ) end function rybyCombo() ryby_combo=(ryby_combo)+1 if ryby_combo == 10 then ryby_combo=0 local liczba = math.random(1,10) if liczba == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 then ryby_zlowione=(ryby_zlowione)+math.random(1,2) elseif liczba==10 then ryby_zlowione=(ryby_zlowione)+math.random(1,5) end end end function sprzedajRyby() local rybska = getElementData(localPlayer,"ryby_zlowione") if rybska then else rybska=0 end setElementData(localPlayer,"ryby_zlowione",0) --setPlayerMoney(getPlayerMoney(localPlayer)+rybska*kurs_ryb) -- KASA ZA RYBY ZMIEN TO !!!!!!!!!!!!!!!!!!!!!!!!!!! triggerServerEvent( "givePlayerMoney", getLocalPlayer(), rybska*kurs_ryb ) outputChatBox("[INFO]Sprzedałeś "..rybska.." ryb(y) za "..rybska*kurs_ryb.."$!",255,255,255) end addEvent("sprzedajRyby",true) addEventHandler("sprzedajRyby",root,sprzedajRyby)
gpl-2.0
stephank/luci
modules/admin-core/luasrc/controller/admin/servicectl.lua
9
1426
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.servicectl", package.seeall) function index() entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root" entry({"servicectl", "status"}, call("action_status")).leaf = true entry({"servicectl", "restart"}, call("action_restart")).leaf = true end function action_status() local data = nixio.fs.readfile("/var/run/luci-reload-status") if data then luci.http.write("/etc/config/") luci.http.write(data) else luci.http.write("finish") end end function action_restart() local uci = require "luci.model.uci".cursor() local rqp = luci.dispatcher.context.requestpath if rqp[3] then local service local services = { } for service in rqp[3]:gmatch("[%w_-]+") do services[#services+1] = service end local command = uci:apply(services, true) if nixio.fork() == 0 then local i = nixio.open("/dev/null", "r") local o = nixio.open("/dev/null", "w") nixio.dup(i, nixio.stdin) nixio.dup(o, nixio.stdout) i:close() o:close() nixio.exec("/bin/sh", unpack(command)) else luci.http.write("OK") os.exit(0) end end end
apache-2.0
jsphweid/finale-macros
lua/measure-numbers_LA-style.lua
2
7035
function plugindef() finaleplugin.Author = "Joseph Weidinger" finaleplugin.Version = "1.0" finaleplugin.Date = "May 05, 2015" finaleplugin.RequireSelection = false finaleplugin.CategoryTags = "use LA-style measure numbers" return "Measure Numbers - LA Style", "Measure Numbers - LA Style", "Measure Numbers - LA Style" end -- delete existing regions local mNumRegions = finale.FCMeasureNumberRegions() mNumRegions:LoadAll() local region = finale.FCMeasureNumberRegion() for k = mNumRegions.Count,1,-1 do region:Load(k) region:DeleteData(k) end --------------------- 1 - displayed region ------------------------------ -- establish font info for displayed measure numbers local multipleFontInfo = finale.FCFontInfo() multipleFontInfo.Bold = true multipleFontInfo.Name = "Times New Roman" multipleFontInfo.Size = 22 local multiAndMultiMeasureFontInfo = finale.FCFontInfo() multiAndMultiMeasureFontInfo.Italic = false multiAndMultiMeasureFontInfo.Name = "Times New Roman" multiAndMultiMeasureFontInfo.Size = 10 multiAndMultiMeasureFontInfo.EnigmaStyles = 2 multiAndMultiMeasureFontInfo.Hidden = false multiAndMultiMeasureFontInfo.SizeFloat = 10 multiAndMultiMeasureFontInfo.StrikeOut = false multiAndMultiMeasureFontInfo.Underline = false multiAndMultiMeasureFontInfo.Absolute = false multiAndMultiMeasureFontInfo.Bold = false newRegion = finale.FCMeasureNumberRegion() if newRegion then -- basics newRegion.StartMeasure = 1 newRegion.EndMeasure = 999 newRegion.UseScoreInfoForParts = false -- SCORE -- newRegion:SetExcludeOtherStaves(true) newRegion:SetShowOnBottomStaff(true) newRegion:SetShowOnMultiMeasureRests(true) newRegion:SetShowMultiples(true) -- multiple font info and position newRegion:SetMultipleFontInfo(multipleFontInfo, false) newRegion:SetMultipleFontInfo(multiAndMultiMeasureFontInfo, true) newRegion:SetMultipleAlignment(finale.MNALIGN_CENTER, false) --- BROKEN>>>?? newRegion:SetMultipleAlignment(finale.MNALIGN_CENTER, true) --- BROKEN>>>?? newRegion:SetMultipleJustification(finale.MNJUSTIFY_CENTER, false) newRegion:SetMultipleHorizontalPosition(0) newRegion:SetMultipleVerticalPosition(-270) newRegion:SetMultipleValue(1, true) newRegion:SetMultipleValue(1, false) newRegion:SetStartFontInfo(multiAndMultiMeasureFontInfo, true) newRegion:SetStartFontInfo(multiAndMultiMeasureFontInfo, false) newRegion:SetStartVerticalPosition(44, true) newRegion:SetStartVerticalPosition(44, false) -- LINKED PARTS -- newRegion:SetExcludeOtherStaves(true, true) newRegion:SetShowOnTopStaff(true, true) newRegion:SetShowMultiples(true, true) newRegion:SetShowMultiMeasureRange(true, true) -- multiple font info and position for parts newRegion:SetMultipleAlignment(finale.MNALIGN_CENTER, true) --- BROKEN>>>?? newRegion:SetMultipleJustification(finale.MNJUSTIFY_CENTER, true) newRegion:SetMultipleHorizontalPosition(0, true) newRegion:SetMultipleVerticalPosition(-175, true) -- multimeasure font info and position for parts newRegion:SetMultiMeasureFontInfo(multiAndMultiMeasureFontInfo, true) newRegion:SetMultiMeasureFontInfo(multiAndMultiMeasureFontInfo, false) newRegion:SetMultiMeasureAlignment(finale.MNALIGN_CENTER, true) --- BROKEN>>>?? newRegion:SetMultiMeasureAlignment(finale.MNALIGN_CENTER, false) --- BROKEN>>>?? newRegion:SetMultiMeasureJustification(finale.MNJUSTIFY_CENTER, true) newRegion:SetMultiMeasureHorizontalPosition(0, true) newRegion:SetMultiMeasureVerticalPosition(-175, true) newRegion:SetMultiMeasureVerticalPosition(44, false) newRegion:SaveNew() end --------------------- 2 - hidden region ------------------------------ -- establish font info for hidden measure numbers local hiddenFontInfo = finale.FCFontInfo() hiddenFontInfo.Bold = true hiddenFontInfo.Name = "Times New Roman" hiddenFontInfo.Size = 22 hiddenFontInfo.Hidden = true local hiddenFontInfoParts = finale.FCFontInfo() hiddenFontInfoParts.Absolute = false hiddenFontInfoParts.Bold = false hiddenFontInfoParts.EnigmaStyles = 2 hiddenFontInfoParts.Hidden = false hiddenFontInfoParts.Italic = true hiddenFontInfoParts.Size = 10 hiddenFontInfoParts.SizeFloat = 10 hiddenFontInfoParts.StrikeOut = false hiddenFontInfoParts.Underline = false local hiddenFontInfoMMPartsScore = finale.FCFontInfo() -- same for score and parts hiddenFontInfoMMPartsScore.Absolute = false hiddenFontInfoMMPartsScore.Bold = false hiddenFontInfoMMPartsScore.EnigmaStyles = 2 hiddenFontInfoMMPartsScore.Hidden = false hiddenFontInfoMMPartsScore.Italic = true hiddenFontInfoMMPartsScore.Size = 10 hiddenFontInfoMMPartsScore.SizeFloat = 10 hiddenFontInfoMMPartsScore.StrikeOut = false hiddenFontInfoMMPartsScore.Underline = false local hiddenStartFontInfoPartsScore = finale.FCFontInfo() -- same for score and parts hiddenStartFontInfoPartsScore.Absolute = false hiddenStartFontInfoPartsScore.Bold = false hiddenStartFontInfoPartsScore.EnigmaStyles = 2 hiddenStartFontInfoPartsScore.Hidden = false hiddenStartFontInfoPartsScore.Italic = true hiddenStartFontInfoPartsScore.Size = 10 hiddenStartFontInfoPartsScore.SizeFloat = 10 hiddenStartFontInfoPartsScore.StrikeOut = false hiddenStartFontInfoPartsScore.Underline = false newHiddenRegion = finale.FCMeasureNumberRegion() if newHiddenRegion then newHiddenRegion.StartMeasure = 1 newHiddenRegion.EndMeasure = 999 newHiddenRegion.UseScoreInfoForParts = false newHiddenRegion:SetShowOnMultiMeasureRests(true) newHiddenRegion:SetShowMultiples(true) -- multiple font info and position newHiddenRegion:SetMultipleFontInfo(hiddenFontInfoParts, true) newHiddenRegion:SetMultipleFontInfo(hiddenFontInfo, false) newHiddenRegion:SetStartFontInfo(hiddenStartFontInfoPartsScore, true) newHiddenRegion:SetStartFontInfo(hiddenStartFontInfoPartsScore, false) newHiddenRegion:SetMultiMeasureFontInfo(hiddenFontInfoMMPartsScore, true) -- parts newHiddenRegion:SetMultiMeasureFontInfo(hiddenFontInfoMMPartsScore, false) -- score newHiddenRegion:SetMultipleAlignment(finale.MNALIGN_CENTER, false) --- BROKEN>>>?? newHiddenRegion:SetMultipleAlignment(finale.MNALIGN_CENTER, true) --- BROKEN>>>?? newHiddenRegion:SetMultipleJustification(finale.MNJUSTIFY_CENTER, false) newHiddenRegion:SetMultipleJustification(finale.MNJUSTIFY_CENTER, true) newHiddenRegion:SetMultipleValue(1, true) newHiddenRegion:SetMultipleValue(1, false) newHiddenRegion:SetMultiMeasureJustification(2, true) newHiddenRegion:SetMultipleHorizontalPosition(0, false) newHiddenRegion:SetMultipleVerticalPosition(-270, false) newHiddenRegion:SetMultipleVerticalPosition(-175, true) newHiddenRegion:SetMultiMeasureVerticalPosition(44, false) newHiddenRegion:SetMultiMeasureVerticalPosition(-175, true) newHiddenRegion:SetStartVerticalPosition(44, true) newHiddenRegion:SetStartVerticalPosition(44, false) newHiddenRegion:SetMultiMeasureAlignment(1, true) --- BROKEN>>>?? newHiddenRegion:SaveNew() end
mit
ondravondra/vlc
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ 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, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = 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, nodename) 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
gpl-2.0
cristicbz/ld48
src/Game.lua
1
1881
------------------------------------------------------------------------------- -- File: game.lua -- Project: RatOut -- Author: Cristian Cobzarenco -- Description: Game rig, root rig which manages application state. -- -- All rights reserved. Copyright (c) 2011-2012 Cristian Cobzarenco. -- See http://www.nwydo.com ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Game rig ------------------------------------------------------------------------------- Game = { kPixelToWorld = settings.world.screen_width / settings.world.screen_pixel_width, kAspectRatio = settings.world.screen_pixel_height / settings.world.screen_pixel_width, kScreenPixelWidth = settings.world.screen_pixel_width, kScreenPixelHeight = settings.world.screen_pixel_height, kScreenWidth = settings.world.screen_width, } Game.kScreenHeight = settings.world.screen_pixel_height * Game.kPixelToWorld function Game.new() local self = setmetatable( {}, { __index = Game } ) MOAISim.setStep( Game.SMALL_STEP_SIZE ) MOAISim.clearLoopFlags() MOAISim.setLoopFlags( MOAISim.LOOP_FLAGS_FIXED ) MOAISim.setLoopFlags ( MOAISim.SIM_LOOP_ALLOW_SPIN ) MOAISim.openWindow("LD48", Game.kScreenPixelWidth, Game.kScreenPixelHeight) -- Create viewport self.viewport = MOAIViewport.new() self.viewport:setScale(Game.kScreenWidth, 0) self.viewport:setSize(Game.kScreenPixelWidth, Game.kScreenPixelHeight) if not settings.debug.no_sound then MOAIUntzSystem.initialize() MOAIUntzSystem.setVolume(1.0) end -- Create assets self.assets = Assets.new() -- Create game state. There will be multiple states (menu etc.). self.state = GameState.new(self.assets, self.viewport) return self end function Game:run() self.state:run() end
apache-2.0
Daniex0r/project-roleplay-rp
resources/system-domow/custom/restroom.lua
1
2397
local objects = { createObject(18020,2489.1943359375,-1690.2387695313,2032.4692382813,0,0,0,8), createObject(2515,2485.0329589844,-1686.2604980469,2031.47265625,0,0,180.54052734375,8), createObject(2515,2483.3227539063,-1686.259765625,2031.47265625,0,0,180.53833007813,8), createObject(2515,2486.6765136719,-1686.259765625,2031.47265625,0,0,180.53833007813,8), createObject(2515,2488.3532714844,-1686.259765625,2031.47265625,0,0,180.53833007813,8), createObject(2738,2484.275390625,-1680.228515625,2031.0825195313,0,0,0,8), createObject(2738,2486.275390625,-1680.228515625,2031.0825195313,0,0,0,8), createObject(2738,2488.3156738281,-1680.228515625,2031.0825195313,0,0,0,8), createObject(2741,2487.5024414063,-1686.7309570313,2032.0561523438,0,0,180.54052734375,8), createObject(2741,2484.2280273438,-1686.73046875,2032.0561523438,0,0,180.53833007813,8), createObject(2742,2489.1374511719,-1684.8503417969,2032.0458984375,0,0,270.27026367188,8), createObject(1533,2481.3510742188,-1687.6369628906,2030.4926757813,0,0,180,8), createObject(1533,2482.8510742188,-1687.6369628906,2030.4926757813,0,0,180,8), createObject(8555,2469.2863769531,-1662.1713867188,1990.4926757813,0,270,270,8), createObject(8555,2469.2524414063,-1708.8408203125,1990.4926757813,0,270,90,8) } local col = createColSphere(2480.6015625, -1687.2392578125, 2031.4916992188,100) local function watchChanges( ) if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then for key, value in pairs( objects ) do setElementDimension( value, getElementDimension( getLocalPlayer( ) ) ) end elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end end end addEventHandler( "onClientColShapeHit", col, function( element ) if element == getLocalPlayer( ) then addEventHandler( "onClientRender", root, watchChanges ) end end ) addEventHandler( "onClientColShapeLeave", col, function( element ) if element == getLocalPlayer( ) then removeEventHandler( "onClientRender", root, watchChanges ) end end ) -- Put them standby for now. for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end
gpl-2.0
Sponk/NeoEditor
3rdparty/sdl2-emscripten/premake/projects/testshape.lua
7
1153
-- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely. -- -- Meta-build system using premake created and maintained by -- Benjamin Henning <b.henning@digipen.edu> --[[ testshape.lua This file defines the testshape test project. It depends on the SDL2main and SDL2 projects. It will not build on iOS or Cygwin. This project has a unique SDL_copy directive, since it copies from a subdirectory and it copies all the files of a specific type. ]] SDL_project "testshape" SDL_kind "ConsoleApp" SDL_notos "ios|cygwin" SDL_language "C" SDL_sourcedir "../test" SDL_projectLocation "tests" -- a list of items to copy from the sourcedir to the destination SDL_copy { "shapes/*.bmp" } SDL_projectDependencies { "SDL2main", "SDL2" } SDL_files { "/testshape.*" }
gpl-2.0
RicoP/vlcfork
share/lua/playlist/pluzz.lua
105
3740
--[[ $Id$ Copyright © 2011 VideoLAN Authors: Ludovic Fauvet <etix at l0cal dot com> 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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "pluzz.fr/%w+" ) or string.match( vlc.path, "info.francetelevisions.fr/.+") or string.match( vlc.path, "france4.fr/%w+") end -- Helpers function key_match( line, key ) return string.match( line, "name=\"" .. key .. "\"" ) end function get_value( line ) local _,_,r = string.find( line, "content=\"(.*)\"" ) return r end -- Parse function. function parse() p = {} if string.match ( vlc.path, "www.pluzz.fr/%w+" ) then while true do line = vlc.readline() if not line then break end if string.match( line, "id=\"current_video\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "www.france4.fr/%w+" ) then while true do line = vlc.readline() if not line then break end -- maybe we should get id from tags having video/cappuccino type instead if string.match( line, "id=\"lavideo\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "info.francetelevisions.fr/.+" ) then title = "" arturl = "http://info.francetelevisions.fr/video-info/player_sl/Images/PNG/gene_ftv.png" while true do line = vlc.readline() if not line then break end -- Try to find the video's path if key_match( line, "urls--url--video" ) then video = get_value( line ) end -- Try to find the video's title if key_match( line, "vignette--titre--court" ) then title = get_value( line ) title = vlc.strings.resolve_xml_special_chars( title ) print ("playing: " .. title ) end -- Try to find the video's thumbnail if key_match( line, "vignette" ) then arturl = get_value( line ) if not string.match( line, "http://" ) then arturl = "http://info.francetelevisions.fr/" .. arturl end end end if video then -- base url is hardcoded inside a js source file -- see http://www.pluzz.fr/layoutftv/arches/common/javascripts/jquery.player-min.js base_url = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/" table.insert( p, { path = base_url .. video; name = title; arturl = arturl; } ) end end return p end
gpl-2.0
tudelft/chdkptp
lua/extras/msgtest.lua
5
4789
--[[ Copyright (C) 2010-2014 <reyalp (at) gmail dot com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ]] --[[ a script for stressing the usb layer and message system usage: !m=require'extras/msgtest' !m.test(options) opions:{ size=number -- initial message size sizemax=number -- end message size sizestep=number -- increment size by N count=number -- number of messages verbose=number -- level of verbosity, 2 = print a line for each message checkmem=bool -- check free memory and lua allocated memory for each message memverbose=bool -- print memory stats for each message gc=string|nil -- garbage collection mode, 'step', 'collect' or nil } example !m.test{size=100,sizeinc=10,sizemax=200,verbose=0,memverbose=true,checkmem=true,gc='step'} ]] local m={} local default_opts = { verbose = 2, checkmem = false, memverbose = false, gc = nil, } m.opts = {} m.detailmsg = util.make_msgf( function() return m.opts.verbose end, 2) function m.init_test() m.fail_count = 0 m.run_count = 0 if m.opts.checkmem then m.memstats = { free={}, count={} } end m.load() m.set_gc(m.opts.gc) m.t0=ustime.new() return true end function m.fmt_memstats(stats) local min=1000000000 local max=0 local total = 0 if #stats == 0 then return "no stats" end for i,v in ipairs(stats) do if v > max then max = v end if v < min then min = v end total = total + v end return string.format("min %d max %d avg %d",min, max, total/#stats) end function m.finish_test() m.quit() printf("ran %d fail %d time %.4f\n",m.run_count,m.fail_count,ustime.diff(m.t0)/1000000) if m.opts.checkmem then printf("free (bytes): %s\n",m.fmt_memstats(m.memstats.free)) printf("lua alloc (kb): %s\n",m.fmt_memstats(m.memstats.count)) end return (m.fail_count == 0) end function m.load() con:exec('msg_shell:run()',{libs={'msg_shell','serialize'}}) con:write_msg([[exec msg_shell.read_msg_timeout = nil msg_shell.default_cmd=function(msg) if msgtest_gc then collectgarbage(msgtest_gc) end write_usb_msg(msg) end msg_shell.cmds.memstats=function() write_usb_msg(serialize({mem=get_meminfo().free_size,lmem=collectgarbage('count')})) end ]]) end function m.quit() con:write_msg('quit') end function m.test_msg(len) m.run_count = m.run_count + 1 local s=string.rep('x',len) con:write_msg(s) local r = con:wait_msg({mtype='user'}) if s == r.value then m.detailmsg('ok\n') else m.fail_count = m.fail_count + 1 printf('failed\nmsg %d len %d not equal\n',m.run_count,len) end if m.opts.checkmem then con:write_msg('memstats') r = con:wait_msg({mtype='user',munserialize=true}) table.insert(m.memstats.free,r.mem) table.insert(m.memstats.count,r.lmem) if m.opts.memverbose then printf('free:%d lua alloc:%d kb\n',r.mem,r.lmem) end end end function m.test(opts) opts = util.extend_table(util.extend_table({},default_opts),opts) m.opts = opts if not opts.size then error("missing size") end if not opts.count then if opts.sizeinc and opts.sizemax then opts.count = math.floor((opts.sizemax - opts.size )/opts.sizeinc) else error("missing count") end end if opts.sizeinc == 0 then opts.sizeinc = nil end if opts.sizeinc and not opts.sizemax then opts.sizemax = opts.size + opts.count * opts.sizeinc end local size = opts.size printf("testing %d messages size %d",opts.count,size) if opts.sizeinc and opts.sizeinc > 0 then printf("-%d, inc %d",opts.sizemax,opts.sizeinc) end printf("\n") m.init_test() for i=1,opts.count do m.detailmsg("send %d...",i) local status,err=pcall(m.test_msg,size) if not status then printf("%s\n",tostring(err)) printf("aborted, communication error\n") m.finish_test() return false end if opts.sizeinc and size < opts.sizemax then size = size + opts.sizeinc end end return m.finish_test() end function m.set_gc(mode) if not mode then mode='nil' else mode = '"'..mode..'"' end con:write_msg('exec msgtest_gc='..mode) end return m
gpl-2.0
Daniex0r/project-roleplay-rp
resources/system-eventow/s_paintball.lua
1
7377
-- paintassignteam // startpaintgame // stoppaintgame local playersHit = { } local resetTimer = 10000 local points = { } local gameactive = false local theTimer = nil local teamName = {} local countdown = 0 local ammogiven = 0 local playerStats = { } table.insert(teamName, "RED") -- Team 1 table.insert(teamName, "BLUE") -- Team 2 function onPaintballHit(thePlayer) local attacker = client or source local paintball = getElementData(attacker, "paintball") if (paintball) and not (playersHit[thePlayer]) then toggleControl (thePlayer, "fire", false) exports['global']:sendLocalText(thePlayer, " * Got tagged by "..getPlayerName(attacker):gsub("_", " ").." * ((" .. getPlayerName(thePlayer):gsub("_", " ") .. "))", 255, 51, 102) local r, g, b = getTeamColor(attacker) local marker1 = createMarker ( 0, 0, 0, "corona", 0.5, r, g, b, 255 ) local marker2 = createMarker ( 0, 0, 0, "corona", 0.5, r, g, b, 255 ) setElementInterior(marker1, getElementInterior(thePlayer)) setElementInterior(marker2, getElementInterior(thePlayer)) setElementDimension(marker1, getElementDimension(thePlayer)) setElementDimension(marker2, getElementDimension(thePlayer)) attachElements(marker1, thePlayer,0,0,0.6) attachElements(marker2, thePlayer) setElementData(thePlayer, "paintball:marker1", marker1, false) setElementData(thePlayer, "paintball:marker2", marker2, false) playersHit[thePlayer] = true setTimer ( resetPaintballPlayer, resetTimer, 1, thePlayer ) handlePoints(attacker, thePlayer) end end addEvent("paintball:hit", true) addEventHandler( "paintball:hit", getRootElement(), onPaintballHit) function handlePoints(attacker, victim) if gameactive then local attackerTeam = getElementData(attacker, "paintball:team") local victimTeam = getElementData(victim, "paintball:team") if (attackerTeam) and (victimTeam) then if (attackerTeam == victimTeam) then -- TEAMKILL!! broadcastGameMessage("TEAMKILL: ".. getPlayerName(attacker):gsub("_", " ") .. " killed " .. getPlayerName(victim):gsub("_", " "),255,0,0) points[attackerTeam] = (points[attackerTeam] or 0) - 2 playerStats[attacker]["teamkills"] = (playerStats[attacker]["teamkills"] or 0) + 1 playerStats[victim]["deaths"] = (playerStats[victim]["deaths"] or 0) + 1 else points[attackerTeam] = (points[attackerTeam] or 0) + 1 playerStats[attacker]["kills"] = (playerStats[attacker]["kills"] or 0) + 1 playerStats[victim]["deaths"] = (playerStats[victim]["deaths"] or 0) + 1 end end end end function broadcastGameMessage(message, r,g,b) local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do local inPaintballGame = getElementData(thePlayer, "paintball") if (inPaintballGame) then outputChatBox(" >> ".. message, thePlayer, r, g, b) end end end function resetPaintballPlayer(thePlayer) if (playersHit[thePlayer]) then local marker1 = getElementData(thePlayer, "paintball:marker1") destroyElement(marker1) local marker2 = getElementData(thePlayer, "paintball:marker2") destroyElement(marker2) local marker3 = getElementData(thePlayer, "paintball:marker3") destroyElement(marker3) toggleControl(thePlayer, "fire", true) playersHit[thePlayer] = nil outputChatBox("Gogogo!", thePlayer,0,255,0) end end function assignTeam(theSource, commandName, maybeThePlayer, teamID) if not (teamID) then return end teamID = tonumber(teamID) if not (teamID) then return end local thePlayer, targetPlayerName = exports.global:findPlayerByPartialNick(theSource, maybeThePlayer) if not thePlayer then return end if (getElementDimension(thePlayer) == 1661) or (getElementDimension(thePlayer) == 1662) then -- in briefing room or game field setElementData(thePlayer, "paintball",true, true ) if (teamID == 1) then -- team red setElementData(thePlayer, "paintball:colors", {255, 0, 0}, true ) outputChatBox("You are assigned to team RED.", thePlayer, 0, 255, 0) elseif (teamID == 2) then -- team blue setElementData(thePlayer, "paintball:colors", {0, 0, 255}, true ) outputChatBox("You are assigned to team BLUE.", thePlayer, 0, 255, 0) else-- F4A team setElementData(thePlayer, "paintball:colors", {math.random(0,255), math.random(0,255), math.random(0,255)}, true ) outputChatBox("You are assigned to the paintball game.", thePlayer, 0, 255, 0) end exports['global']:sendLocalText(thePlayer, " * Got assigned to team "..(teamName[teamID] or teamID).." * ((" .. getPlayerName(thePlayer):gsub("_", " ") .. "))", 255, 51, 102) setElementData(thePlayer, "paintball:team", teamID, false ) end playerStats[thePlayer] = { } if (gameactive) then exports.global:takeWeapon(thePlayer, 33) local give = exports.global:giveWeapon(thePlayer, 33, 15 * timetake, true) end end addCommandHandler("paintassignteam", assignTeam, false, false) function startGame(theSource, commandName, timetake) if not (timetake) then return end timetake = tonumber(timetake) if not (timetake) then return end if (gameactive) then return end playerStats = { } broadcastGameMessage("Game has been started by ".. getPlayerName(theSource):gsub("_", " "), 0, 255, 0) broadcastGameMessage("This is a ".. timetake .." minutes game.", 0, 255, 0) broadcastGameMessage("Starting in 10 seconds!.", 0, 255, 0) local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do local inPaintballGame = getElementData(thePlayer, "paintball") if (inPaintballGame) then triggerClientEvent(thePlayer, "paintball:countdown", theSource, 10) end end setTimer(startGameReal, 10000, 1, timetake) end addCommandHandler("startpaintgame", startGame, false, false) function startGameReal( timetake ) points = { } gameactive = true ammogiven = timetake * 15 theTimer = setTimer ( stopGame, timetake * 60000, 1 ) local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do local inPaintballGame = getElementData(thePlayer, "paintball") if (inPaintballGame) then if (getElementDimension(thePlayer) == 1662) then exports.global:takeWeapon(thePlayer, 33) local give = exports.global:giveWeapon(thePlayer, 33, 15 * timetake, true) end end end end function stopGame() if (gameactive) then gameactive = false broadcastGameMessage("Game is over!!", 0, 255, 0) broadcastGameMessage("Points:", 0, 255, 0) for teamID, pointsInTotal in ipairs(points) do broadcastGameMessage("TEAM ".. (teamName[teamID] or teamID) .." - "..pointsInTotal, 0, 255, 0) end local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do local inPaintballGame = getElementData(thePlayer, "paintball") if (inPaintballGame) then exports.global:takeWeapon(thePlayer, 33) setElementData(thePlayer, "paintball", false, true) setElementData(thePlayer, "paintball:team", false, false) setElementData(thePlayer, "paintball:colors", false, true) end end -- playerStats[player]["teamkills"] ["kills"] ["deaths"] end end addCommandHandler("stoppaintgame", stopGame, false, false) function getTeamColor( thePlayer ) local colors = getElementData(thePlayer, "paintball:colors") if (colors) then return colors[1],colors[2], colors[3] end return 255,0,0 end
gpl-2.0
Sponk/NeoEditor
3rdparty/sdl2-emscripten/premake/premake4.lua
9
19887
-- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely. -- -- Meta-build system using premake created and maintained by -- Benjamin Henning <b.henning@digipen.edu> --[[ premake4.lua This script sets up the entire premake system. It's responsible for executing all of the definition scripts for the SDL2 library and the entire test suite, or demos for the iOS platform. It handles each specific platform and uses the setup state to generate both the configuration header file needed to build SDL2 and the premake lua script to generate the target project files. ]] -- string utility functions dofile "util/sdl_string.lua" -- utility file wrapper for some useful functions dofile "util/sdl_file.lua" -- system for defining SDL projects dofile "util/sdl_projects.lua" -- offers a utility function for finding dependencies specifically on windows dofile "util/sdl_depends.lua" -- system for generating a *config.h file used to build the SDL2 library dofile "util/sdl_gen_config.lua" -- functions to handle complicated dependency checks using CMake-esque functions dofile "util/sdl_check_compile.lua" -- a list of dependency functions for the SDL2 project and any other projects dofile "util/sdl_dependency_checkers.lua" -- the following are various options for configuring the meta-build system newoption { trigger = "to", value = "path", description = "Set the base output directory for the generated and executed lua file." } newoption { trigger = "mingw", description = "Runs the premake generation script targeted to MinGW." } newoption { trigger = "cygwin", description = "Runs the premake generation script targeted to Cygwin." } newoption { trigger = "ios", description = "Runs the premake generation script targeted to iOS." } -- determine the localized destination path local baseLoc = "./" if _OPTIONS["to"] then baseLoc = _OPTIONS["to"]:gsub("\\", "/") end local deps = SDL_getDependencies() for _,v in ipairs(deps) do newoption { trigger = v:lower(), description = "Force on the dependency: " .. v } end -- clean action if _ACTION == "clean" then -- this is kept the way it is because premake's default method of cleaning the -- build tree is not very good standalone, whereas the following correctly -- cleans every build option print("Cleaning the build environment...") os.rmdir(baseLoc .. "/SDL2") os.rmdir(baseLoc .. "/SDL2main") os.rmdir(baseLoc .. "/SDL2test") os.rmdir(baseLoc .. "/tests") os.rmdir(baseLoc .. "/Demos") os.rmdir(baseLoc .. "/ipch") -- sometimes shows up os.remove(baseLoc .. "/SDL.sln") os.remove(baseLoc .. "/SDL.suo") os.remove(baseLoc .. "/SDL.v11.suo") os.remove(baseLoc .. "/SDL.sdf") os.remove(baseLoc .. "/SDL.ncb") os.remove(baseLoc .. "/SDL-gen.lua") os.remove(baseLoc .. "/SDL_config_premake.h") os.remove(baseLoc .. "/Makefile") os.rmdir(baseLoc .. "/SDL.xcworkspace") os.exit() end -- only run through standard execution if not in help mode if _OPTIONS["help"] == nil then -- load all of the project definitions local results = os.matchfiles("projects/**.lua") for _,dir in ipairs(results) do dofile(dir) end -- figure out which configuration template to use local premakeConfigHeader = baseLoc .. "/SDL_config_premake.h" -- minimal configuration is the default local premakeTemplateHeader = "./config/SDL_config_minimal.template.h" if SDL_getos() == "windows" or SDL_getos() == "mingw" then premakeTemplateHeader = "./config/SDL_config_windows.template.h" elseif SDL_getos() == "macosx" then premakeTemplateHeader = "./config/SDL_config_macosx.template.h" elseif SDL_getos() == "ios" then premakeTemplateHeader = "./config/SDL_config_iphoneos.template.h" elseif os.get() == "linux" then premakeTemplateHeader = "./config/SDL_config_linux.template.h" elseif SDL_getos() == "cygwin" then premakeTemplateHeader = "./config/SDL_config_cygwin.template.h" end local genFile = baseLoc .. "/SDL-gen.lua" local file = fileopen(genFile, "wt") print("Generating " .. genFile .. "...") -- begin generating the config header file startGeneration(premakeConfigHeader, premakeTemplateHeader) -- begin generating the actual premake script file:print(0, "-- Premake script generated by Simple DirectMedia Layer meta-build script") file:print(1, 'solution "SDL"') local platforms = { } local platformsIndexed = { } for n,p in pairs(projects) do if p.platforms and #p.platforms ~= 0 then for k,v in pairs(p.platforms) do platforms[v] = true end end end for n,v in pairs(platforms) do platformsIndexed[#platformsIndexed + 1] = n end file:print(2, implode(platformsIndexed, 'platforms {', '"', '"', ', ', '}')) file:print(2, 'configurations { "Debug", "Release" }') for n,p in pairs(projects) do if p.compat then local proj = {} if p.projectLocation ~= nil then proj.location = p.projectLocation .. "/" .. p.name else proj.location = p.name .. "/" end proj.includedirs = { path.getrelative(baseLoc, path.getdirectory(premakeConfigHeader)), path.getrelative(baseLoc, "../include") } proj.libdirs = { } proj.files = { } local links = { } local dbgCopyTable = { } local relCopyTable = { } -- custom links that shouldn't exist... -- (these should always happen before dependencies) if p.customLinks ~= nil then for k,lnk in pairs(p.customLinks) do table.insert(links, lnk) end end -- setup project dependencies local dependencyLocs = { } if p.projectDependencies ~= nil and #p.projectDependencies ~= 0 then for k,projname in pairs(p.projectDependencies) do local depproj = projects[projname] -- validation that it exists and can be linked to if depproj ~= nil and (depproj.kind == "SharedLib" or depproj.kind == "StaticLib") then if depproj.kind == "SharedLib" then local deplocation = nil if depproj.projectLocation ~= nil then deplocation = depproj.projectLocation .. "/" .. p.name else deplocation = depproj.name .. "/" end table.insert(dependencyLocs, { location = deplocation, name = projname }) else -- static lib -- we are now dependent on everything the static lib is dependent on if depproj.customLinks ~= nil then for k,lnk in pairs(depproj.customLinks) do table.insert(links, lnk) end end -- also include links from dependencies for i,d in pairs(depproj.dependencyTree) do if d.links then for k,v in pairs(d.links) do local propPath = v:gsub("\\", "/") table.insert(links, propPath) end end end end -- finally, depend on the project itself table.insert(links, projname) elseif depproj == nil then print("Warning: Missing external dependency for project: ".. p.name .. ". Be sure you setup project dependencies in a logical order.") else print("Warning: Cannot link " .. p.name .. " to second project " .. projname .. " because the second project is not a library.") end end end -- iterate across all root directories, matching source directories local dirs = createDirTable(p.sourcedir) -- but first, handle any files specifically set in the project, rather than -- its dependencies -- register c and h files in this directory if (p.files ~= nil and #p.files ~= 0) or (p.paths ~= nil and #p.paths ~= 0) then -- handle all lists of files if p.files ~= nil and #p.files ~= 0 then for k,filepat in pairs(p.files) do for k,f in pairs(os.matchfiles(p.sourcedir .. filepat)) do table.insert(proj.files, path.getrelative(baseLoc, f)) end end end -- end props files if -- add all .c/.h files from each path -- handle all related paths if p.paths ~= nil and #p.paths ~= 0 then for j,filepat in ipairs(p.paths) do for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.c")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.h")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end -- mac osx for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.m")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end end end -- end of props paths if end -- end of check for files/paths in main project -- if this project has any configuration flags, add them to the current file if p.config then addConfig(p.config) end -- now, handle files and paths for dependencies for i,props in ipairs(p.dependencyTree) do if props.compat then -- register c and h files in this directory -- handle all lists of files if props.files ~= nil and #props.files ~= 0 then for k,filepat in pairs(props.files) do for k,f in pairs(os.matchfiles(p.sourcedir .. filepat)) do table.insert(proj.files, path.getrelative(baseLoc, f)) end end end -- end props files if -- add all .c/.h files from each path -- handle all related paths if props.paths ~= nil and #props.paths ~= 0 then for j,filepat in ipairs(props.paths) do for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.c")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.h")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end -- mac osx for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.m")) do table.insert(proj.files, path.getrelative(baseLoc, f)) end end end -- end of props paths if -- if this dependency has any special configuration flags, add 'em if props.config then addConfig(props.config) end -- end of props config if check end -- end check for compatibility end -- end of props loop --local debugConfig = configuration("Debug") local debugConfig = {} local releaseConfig = {} debugConfig.defines = { "USING_PREMAKE_CONFIG_H", "_DEBUG" } releaseConfig.defines = { "USING_PREMAKE_CONFIG_H", "NDEBUG" } -- setup per-project defines if p.defines ~= nil then for k,def in pairs(p.defines) do table.insert(debugConfig.defines, def) table.insert(releaseConfig.defines, def) end end debugConfig.buildoptions = { } if SDL_getos() == "windows" then table.insert(debugConfig.buildoptions, "/MDd") end debugConfig.linkoptions = { } releaseConfig.buildoptions = {} releaseConfig.linkoptions = {} local baseBuildDir = "/Build" if os.get() == "windows" then baseBuildDir = "/Win32" end debugConfig.flags = { "Symbols" } debugConfig.targetdir = proj.location .. baseBuildDir .. "/Debug" releaseConfig.flags = { "OptimizeSpeed" } releaseConfig.targetdir = proj.location .. baseBuildDir .. "/Release" -- setup postbuild options local dbgPostbuildcommands = { } local relPostbuildcommands = { } -- handle copying depended shared libraries to correct folders if os.get() == "windows" then for k,deploc in pairs(dependencyLocs) do table.insert(dbgCopyTable, { src = deploc.location .. baseBuildDir .. "/Debug/" .. deploc.name .. ".dll", dst = debugConfig.targetdir .. "/" .. deploc.name .. ".dll" }) table.insert(relCopyTable, { src = deploc.location .. baseBuildDir .. "/Release/" .. deploc.name .. ".dll", dst = releaseConfig.targetdir .. "/" .. deploc.name .. ".dll" }) end end if p.copy ~= nil then for k,file in pairs(p.copy) do -- the following builds relative paths native to the current system for copying, other -- than the copy command itself, this is essentially cross-platform for paths -- all custom copies should be relative to the current working directory table.insert(dbgCopyTable, { src = path.getrelative(baseLoc, p.sourcedir .. "/" .. file), dst = debugConfig.targetdir .. "/" .. file }) table.insert(relCopyTable, { src = path.getrelative(baseLoc, p.sourcedir .. "/" .. file), dst = releaseConfig.targetdir .. "/" .. file }) end end for k,file in pairs(dbgCopyTable) do -- all copies should be relative to project location, based on platform local relLocation = "./" --if os.get() == "windows" then relLocation = proj.location --end local fromPath = "./" .. path.getrelative(relLocation, file.src) local toPath = "./" .. path.getrelative(relLocation, file.dst) local toPathParent = path.getdirectory(toPath) local copyCommand = "cp" local destCheck = "if [ ! -d \\\"" .. toPathParent .. "\\\" ]; then mkdir -p \\\"" .. toPathParent .. "\\\"; fi" if SDL_getos() ~= "windows" and fromPath:find("*") ~= nil then -- to path must be a directory for * copies toPath = path.getdirectory(toPath) end if SDL_getos() == "windows" then fromPath = path.translate(fromPath, "/"):gsub("/", "\\\\") toPath = path.translate(toPath, "/"):gsub("/", "\\\\") toPathParent = path.translate(toPathParent, "/"):gsub("/", "\\\\") copyCommand = "copy" destCheck = "if not exist \\\"" .. toPathParent .. "\\\" ( mkdir \\\"" .. toPathParent .. "\\\" )" else fromPath = path.translate(fromPath, nil):gsub("\\", "/") toPath = path.translate(toPath, nil):gsub("\\", "/") end -- command will check for destination directory to exist and, if it doesn't, -- it will make the directory and then copy over any assets local quotedFromPath = fromPath if SDL_getos() == "windows" or fromPath:find("*") == nil then quotedFromPath = '\\"' .. quotedFromPath .. '\\"' end table.insert(dbgPostbuildcommands, destCheck) table.insert(dbgPostbuildcommands, copyCommand .. " " .. quotedFromPath .. " \\\"" .. toPath .. "\\\"") end for k,file in pairs(relCopyTable) do -- all copies should be relative to project location, based on platform local relLocation = "./" relLocation = proj.location local fromPath = "./" .. path.getrelative(relLocation, file.src) local toPath = "./" .. path.getrelative(relLocation, file.dst) local toPathParent = path.getdirectory(toPath) local copyCommand = "cp" local destCheck = "if [ ! -d \\\"" .. toPathParent .. "\\\" ]; then mkdir -p \\\"" .. toPathParent .. "\\\"; fi" if SDL_getos() ~= "windows" and fromPath:find("*") ~= nil then -- to path must be a directory for * copies toPath = path.getdirectory(toPath) end if SDL_getos() == "windows" then fromPath = path.translate(fromPath, "/"):gsub("/", "\\\\") toPath = path.translate(toPath, "/"):gsub("/", "\\\\") toPathParent = path.translate(toPathParent, "/"):gsub("/", "\\\\") copyCommand = "copy" destCheck = "if not exist \\\"" .. toPathParent .. "\\\" ( mkdir \\\"" .. toPathParent .. "\\\" )" else fromPath = path.translate(fromPath, nil):gsub("\\", "/") toPath = path.translate(toPath, nil):gsub("\\", "/") end -- command will check for destination directory to exist and, if it doesn't, -- it will make the directory and then copy over any assets local quotedFromPath = fromPath if SDL_getos() == "windows" or fromPath:find("*") == nil then quotedFromPath = '\\"' .. quotedFromPath .. '\\"' end table.insert(relPostbuildcommands, destCheck) table.insert(relPostbuildcommands, copyCommand .. " " .. quotedFromPath .. " \\\"" .. toPath .. "\\\"") end debugConfig.postbuildcommands = dbgPostbuildcommands debugConfig.links = links releaseConfig.postbuildcommands = relPostbuildcommands releaseConfig.links = links -- release links? for i,d in pairs(p.dependencyTree) do if d.includes then for k,v in pairs(d.includes) do local propPath = v:gsub("\\", "/") proj.includedirs[propPath] = propPath end end if d.libs then for k,v in pairs(d.libs) do local propPath = v:gsub("\\", "/") proj.libdirs[propPath] = propPath end end if d.links then for k,v in pairs(d.links) do local propPath = v:gsub("\\", "/") debugConfig.links[#debugConfig.links + 1] = propPath end end end if #proj.files > 0 then file:print(1, 'project "' .. p.name .. '"') file:print(2, 'targetname "' .. p.name .. '"') -- note: commented out because I think this hack is unnecessary --if iOSMode and p.kind == "ConsoleApp" then -- hack for iOS where we cannot build "tools"/ConsoleApps in -- Xcode for iOS, so we convert them over to WindowedApps -- p.kind = "WindowedApp" --end file:print(2, 'kind "' .. p.kind .. '"') file:print(2, 'language "' .. p.language .. '"') file:print(2, 'location "' .. proj.location .. '"') file:print(2, 'flags { "NoExceptions" }') -- NoRTTI file:print(2, 'buildoptions { }')--"/GS-" }') file:print(2, implode(proj.includedirs, 'includedirs {', '"', '"', ', ', '}')) file:print(2, implode(proj.libdirs, 'libdirs {', '"', '"', ', ', '}')) file:print(2, implode(proj.files, 'files {', '"', '"', ', ', '}')) -- debug configuration file:print(2, 'configuration "Debug"') file:print(3, 'targetdir "' .. debugConfig.targetdir .. '"') -- debug dir is relative to the solution's location file:print(3, 'debugdir "' .. debugConfig.targetdir .. '"') file:print(3, implode(debugConfig.defines, 'defines {', '"', '"', ', ', '}')) file:print(3, implode(debugConfig.links, "links {", '"', '"', ', ', "}")) if SDL_getos() == "mingw" then -- static runtime file:print(3, 'linkoptions { "-lmingw32 -static-libgcc" }') end if SDL_getos() == "cygwin" then file:print(3, 'linkoptions { "-static-libgcc" }') end file:print(3, implode(debugConfig.flags, "flags {", '"', '"', ', ', "}")) file:print(3, implode(debugConfig.postbuildcommands, "postbuildcommands {", '"', '"', ', ', "}")) -- release configuration file:print(2, 'configuration "Release"') file:print(3, 'targetdir "' .. releaseConfig.targetdir .. '"') -- debug dir is relative to the solution's location file:print(3, 'debugdir "' .. releaseConfig.targetdir .. '"') file:print(3, implode(releaseConfig.defines, 'defines {', '"', '"', ', ', '}')) file:print(3, implode(releaseConfig.links, "links {", '"', '"', ', ', "}")) if SDL_getos() == "mingw" then -- static runtime file:print(3, 'linkoptions { "-lmingw32 -static-libgcc" }') end file:print(3, implode(releaseConfig.flags, "flags {", '"', '"', ', ', "}")) file:print(3, implode(releaseConfig.postbuildcommands, "postbuildcommands {", '"', '"', ', ', "}")) end -- end check for valid project (files to build) end -- end compatibility check for projects end -- end for loop for projects endGeneration() -- finish generating the config header file file:close() -- generation is over, now execute the generated file, setup the premake -- solution, and let premake execute the action and generate the project files dofile(genFile) end -- end check for not being in help mode
gpl-2.0
Wiladams/LJIT2perfmon
perf_event.lua
1
15523
local ffi = require("ffi") local bit = require("bit") local lshift = bit.lshift; local rshift = bit.rshift; local bnot = bit.bnot; local S = require("syscall") local nr = require "syscall.linux.nr" local _IO, _IOW = S.c.IOCTL._IO, S.c.IOCTL._IOW local shared = require("shared") -- The table which will hold anything we want exported -- from this module local exports = {} exports.nr = nr; ffi.cdef[[ /* * attr->type field values */ enum perf_type_id { PERF_TYPE_HARDWARE = 0, PERF_TYPE_SOFTWARE = 1, PERF_TYPE_TRACEPOINT = 2, PERF_TYPE_HW_CACHE = 3, PERF_TYPE_RAW = 4, PERF_TYPE_BREAKPOINT = 5, PERF_TYPE_MAX }; /* * attr->config values for generic HW PMU events * * they get mapped onto actual events by the kernel */ enum perf_hw_id { PERF_COUNT_HW_CPU_CYCLES = 0, PERF_COUNT_HW_INSTRUCTIONS = 1, PERF_COUNT_HW_CACHE_REFERENCES = 2, PERF_COUNT_HW_CACHE_MISSES = 3, PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, PERF_COUNT_HW_BRANCH_MISSES = 5, PERF_COUNT_HW_BUS_CYCLES = 6, PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, PERF_COUNT_HW_REF_CPU_CYCLES = 9, PERF_COUNT_HW_MAX }; /* * attr->config values for generic HW cache events * * they get mapped onto actual events by the kernel */ enum perf_hw_cache_id { PERF_COUNT_HW_CACHE_L1D = 0, PERF_COUNT_HW_CACHE_L1I = 1, PERF_COUNT_HW_CACHE_LL = 2, PERF_COUNT_HW_CACHE_DTLB = 3, PERF_COUNT_HW_CACHE_ITLB = 4, PERF_COUNT_HW_CACHE_BPU = 5, PERF_COUNT_HW_CACHE_NODE = 6, PERF_COUNT_HW_CACHE_MAX }; enum perf_hw_cache_op_id { PERF_COUNT_HW_CACHE_OP_READ = 0, PERF_COUNT_HW_CACHE_OP_WRITE = 1, PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, PERF_COUNT_HW_CACHE_OP_MAX }; enum perf_hw_cache_op_result_id { PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, PERF_COUNT_HW_CACHE_RESULT_MISS = 1, PERF_COUNT_HW_CACHE_RESULT_MAX }; /* * attr->config values for SW events */ enum perf_sw_ids { PERF_COUNT_SW_CPU_CLOCK = 0, PERF_COUNT_SW_TASK_CLOCK = 1, PERF_COUNT_SW_PAGE_FAULTS = 2, PERF_COUNT_SW_CONTEXT_SWITCHES = 3, PERF_COUNT_SW_CPU_MIGRATIONS = 4, PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, PERF_COUNT_SW_EMULATION_FAULTS = 8, PERF_COUNT_SW_MAX }; /* * attr->sample_type values */ enum perf_event_sample_format { PERF_SAMPLE_IP = 1U << 0, PERF_SAMPLE_TID = 1U << 1, PERF_SAMPLE_TIME = 1U << 2, PERF_SAMPLE_ADDR = 1U << 3, PERF_SAMPLE_READ = 1U << 4, PERF_SAMPLE_CALLCHAIN = 1U << 5, PERF_SAMPLE_ID = 1U << 6, PERF_SAMPLE_CPU = 1U << 7, PERF_SAMPLE_PERIOD = 1U << 8, PERF_SAMPLE_STREAM_ID = 1U << 9, PERF_SAMPLE_RAW = 1U << 10, PERF_SAMPLE_BRANCH_STACK = 1U << 11, PERF_SAMPLE_REGS_USER = 1U << 12, PERF_SAMPLE_STACK_USER = 1U << 13, PERF_SAMPLE_WEIGHT = 1U << 14, PERF_SAMPLE_DATA_SRC = 1U << 15, PERF_SAMPLE_MAX = 1U << 16, }; /* * branch_sample_type values */ enum perf_branch_sample_type { PERF_SAMPLE_BRANCH_USER = 1U << 0, PERF_SAMPLE_BRANCH_KERNEL = 1U << 1, PERF_SAMPLE_BRANCH_HV = 1U << 2, PERF_SAMPLE_BRANCH_ANY = 1U << 3, PERF_SAMPLE_BRANCH_ANY_CALL = 1U << 4, PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << 5, PERF_SAMPLE_BRANCH_IND_CALL = 1U << 6, PERF_SAMPLE_BRANCH_MAX = 1U << 7, }; enum perf_sample_regs_abi { PERF_SAMPLE_REGS_ABI_NONE = 0, PERF_SAMPLE_REGS_ABI_32 = 1, PERF_SAMPLE_REGS_ABI_64 = 2, }; /* * attr->read_format values */ enum perf_event_read_format { PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, PERF_FORMAT_ID = 1U << 2, PERF_FORMAT_GROUP = 1U << 3, PERF_FORMAT_MAX = 1U << 4, }; ]] exports.PERF_ATTR_SIZE_VER0 = 64; -- sizeof first published struct exports.PERF_ATTR_SIZE_VER1 = 72; -- add: config2 exports.PERF_ATTR_SIZE_VER2 = 80; -- add: branch_sample_type ffi.cdef[[ /* * perf_event_attr struct passed to perf_event_open() */ typedef struct perf_event_attr { uint32_t type; uint32_t size; uint64_t config; union { uint64_t sample_period; uint64_t sample_freq; } sample; uint64_t sample_type; uint64_t read_format; /* uint64_t disabled : 1; uint64_t inherit : 1; uint64_t pinned : 1; uint64_t exclusive : 1; uint64_t exclude_user : 1; uint64_t exclude_kernel : 1; uint64_t exclude_hv : 1; uint64_t exclude_idle : 1; uint64_t mmap : 1; uint64_t comm : 1; uint64_t freq : 1; uint64_t inherit_stat : 1; uint64_t enable_on_exec : 1; uint64_t task : 1; uint64_t watermark : 1; uint64_t precise_ip : 2; uint64_t mmap_data : 1; uint64_t sample_id_all : 1; uint64_t exclude_host : 1; uint64_t exclude_guest : 1; uint64_t exclude_callchain_kernel : 1; uint64_t exclude_callchain_user : 1; uint64_t __reserved_1 : 41; */ // TODO - need a better way to represent the uint64_t // based bitfields uint64_t bitfield_flag; union { uint32_t wakeup_events; uint32_t wakeup_watermark; } wakeup; uint32_t bp_type; union { uint64_t bp_addr; uint64_t config1; // extend config } bpa; union { uint64_t bp_len; uint64_t config2; // extend config1 } bpb; uint64_t branch_sample_type; uint64_t sample_regs_user; uint32_t sample_stack_user; uint32_t __reserved_2; } perf_event_attr_t; ]] --[[ As of LuaJIT 2.1, 64-bit values can not be used as bitfields in C structures. This is probably according to the C standard the the C parser follows, as the standard only indicates bitfields will work with 'int' fields. So, we construct this metatype with the bitfield ranges, and implement the __newindex, and __index functions so that we can do the bit manipulations ourselves. Of course, if you want to add any other function to the metatype, you'll have to change this code. More than likely, you can simply do it in a convenient table class instead of in here. --]] local perf_event_attr = ffi.typeof("struct perf_event_attr") local perf_event_attr_mt = {} perf_event_attr_mt.bitfield_ranges = { disabled = { 0, 1}; inherit = { 1, 1}; pinned = { 2, 1}; exclusive = { 3, 1}; exclude_user = { 4, 1}; exclude_kernel = { 5, 1}; exclude_hv = { 6, 1}; exclude_idle = { 7, 1}; mmap = { 8, 1}; comm = { 9, 1}; freq = { 10, 1}; inherit_stat = { 11, 1}; enable_on_exec = { 12, 1}; task = { 13, 1}; watermark = { 14, 1}; precise_ip = { 15, 2}; mmap_data = { 17, 1}; sample_id_all = { 18, 1}; exclude_host = { 19, 1}; exclude_guest = { 20, 1}; exclude_callchain_kernel = { 21, 1}; exclude_callchain_user = { 22, 1}; __reserved_1 = { 23, 41}; } perf_event_attr_mt.__index = function(self, key) local keyrange = perf_event_attr_mt.bitfield_ranges[key] if not keyrange then return nil; end return shared.extractbits64(self.bitfield_flag, keyrange[1], keyrange[2]); end perf_event_attr_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_event_attr_mt.bitfield_ranges[key] if not kr then return nil; end self.bitfield_flag = shared.setbits64(self.bitfield_flag, kr[1], kr[2], value); return res; end ffi.metatype(perf_event_attr, perf_event_attr_mt); ffi.cdef[[ struct perf_branch_entry { uint64_t from; uint64_t to; /* uint64_t mispred:1, // target mispredicted predicted:1, // target predicted reserved:62; */ uint64_t bitfield_flag; }; ]] local perf_branch_entry = ffi.typeof("struct perf_branch_entry") local perf_branch_entry_mt = {} perf_branch_entry_mt.bitfield_ranges = { mispred = {0,1}; predicted = {1,1}; reserved = {2,62}; } perf_branch_entry_mt.__index = function(self, key) local kr = perf_branch_entry_mt.bitfield_ranges[key] if not kr then return nil end return shared.extractbits64(self.bitfield_flag, kr[1], kr[2]); end perf_branch_entry_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_branch_entry_mt.bitfield_ranges[key] if not kr then return end self.bitfield_flag = shared.setbits64(self.bitfield_flag, kr[1], kr[2], value); end ffi.metatype(perf_branch_entry, perf_branch_entry_mt); ffi.cdef[[ /* * branch stack layout: * nr: number of taken branches stored in entries[] * * Note that nr can vary from sample to sample * branches (to, from) are stored from most recent * to least recent, i.e., entries[0] contains the most * recent branch. */ struct perf_branch_stack { uint64_t nr; struct perf_branch_entry entries[0]; }; ]] -- perf_events ioctl commands, use with event fd exports.PERF_EVENT_IOC_ENABLE = _IO ('$', 0) exports.PERF_EVENT_IOC_DISABLE = _IO ('$', 1) exports.PERF_EVENT_IOC_REFRESH = _IO ('$', 2) exports.PERF_EVENT_IOC_RESET = _IO ('$', 3) exports.PERF_EVENT_IOC_PERIOD = _IOW('$', 4, "uint64") exports.PERF_EVENT_IOC_SET_OUTPUT = _IO ('$', 5) exports.PERF_EVENT_IOC_SET_FILTER = _IOW('$', 6, "char") ffi.cdef[[ /* * ioctl() 3rd argument */ enum perf_event_ioc_flags { PERF_IOC_FLAG_GROUP = 1U << 0, }; ]] ffi.cdef[[ /* * mmapped sampling buffer layout * occupies a 4kb page */ struct perf_event_mmap_page { uint32_t version; uint32_t compat_version; uint32_t lock; uint32_t index; int64_t offset; uint64_t time_enabled; uint64_t time_running; union { uint64_t capabilities; /* uint64_t cap_usr_time:1, cap_usr_rdpmc:1, cap_____res:62; */ uint64_t bitfield_flag; } rdmap_cap; uint16_t pmc_width; uint16_t time_shift; uint32_t time_mult; uint64_t time_offset; uint64_t __reserved[120]; uint64_t data_head; uint64_t data_tail; }; /* * sampling buffer event header */ struct perf_event_header { uint32_t type; uint16_t misc; uint16_t size; }; ]] -- event header misc field values exports.PERF_EVENT_MISC_CPUMODE_MASK = lshift(3,0) exports.PERF_EVENT_MISC_CPUMODE_UNKNOWN = lshift(0,0) exports.PERF_EVENT_MISC_KERNEL = lshift(1,0) exports.PERF_EVENT_MISC_USER = lshift(2,0) exports.PERF_EVENT_MISC_HYPERVISOR = lshift(3,0) exports.PERF_RECORD_MISC_GUEST_KERNEL = lshift(4,0) exports.PERF_RECORD_MISC_GUEST_USER = lshift(5,0) exports.PERF_RECORD_MISC_EXACT = lshift(1, 14) exports.PERF_RECORD_MISC_EXACT_IP = lshift(1, 14) exports.PERF_RECORD_MISC_EXT_RESERVED = lshift(1, 15) ffi.cdef[[ // header->type values enum perf_event_type { PERF_RECORD_MMAP = 1, PERF_RECORD_LOST = 2, PERF_RECORD_COMM = 3, PERF_RECORD_EXIT = 4, PERF_RECORD_THROTTLE = 5, PERF_RECORD_UNTHROTTLE = 6, PERF_RECORD_FORK = 7, PERF_RECORD_READ = 8, PERF_RECORD_SAMPLE = 9, PERF_RECORD_MMAP2 = 10, PERF_RECORD_MAX }; enum perf_callchain_context { PERF_CONTEXT_HV = (uint64_t)-32, PERF_CONTEXT_KERNEL = (uint64_t)-128, PERF_CONTEXT_USER = (uint64_t)-512, PERF_CONTEXT_GUEST = (uint64_t)-2048, PERF_CONTEXT_GUEST_KERNEL = (uint64_t)-2176, PERF_CONTEXT_GUEST_USER = (uint64_t)-2560, PERF_CONTEXT_MAX = (uint64_t)-4095, }; ]] -- flags for perf_event_open() exports.PERF_FLAG_FD_NO_GROUP = lshift(1, 0) exports.PERF_FLAG_FD_OUTPUT = lshift(1, 1) exports.PERF_FLAG_PID_CGROUP = lshift(1, 2) local __NR_perf_event_open = 0; if ffi.arch == "x64" then __NR_perf_event_open = 298; end if ffi.arch == "x86" then __NR_perf_event_open = 336; end if ffi.arch == "ppc" then __NR_perf_event_open = 319; end if ffi.arch == "arm" then __NR_perf_event_open = 364; end if ffi.arch == "arm64" then __NR_perf_event_open = 241; end if ffi.arch == "mips" then __NR_perf_event_open = 4333; end -- perf_event_open() syscall stub --local function perf_event_open( -- struct perf_event_attr *hw_event_uptr, -- pid_t pid, -- int cpu, -- int group_fd, -- unsigned long flags) local function perf_event_open( hw_event_uptr, pid, cpu, group_fd, flags) --print("perf_event_open: ", S.perf_event_open, hw_event_uptr, pid, cpu, group_fd, flags) local fd = ffi.C.syscall(nr.SYS.perf_event_open, hw_event_uptr, pid, cpu, group_fd, flags); fd = S.t.fd(fd); return fd; end exports.perf_event_open = perf_event_open exports.PR_TASK_PERF_EVENTS_ENABLE = 32 exports.PR_TASK_PERF_EVENTS_DISABLE = 31 ffi.cdef[[ union perf_mem_data_src { uint64_t val; struct { /* uint64_t mem_op:5, // type of opcode mem_lvl:14, // memory hierarchy level mem_snoop:5, // snoop mode mem_lock:2, // lock instr mem_dtlb:7, // tlb access mem_rsvd:31; */ }; }; ]] local perf_mem_data_src = ffi.typeof("union perf_mem_data_src") local perf_mem_data_src_mt = {} perf_mem_data_src_mt.bitfield_ranges = { mem_op = {0,5}; mem_lvl = {5,14}; mem_snoop = {19,5}; mem_lock = {24,2}; mem_dtlb = {26,7}; mem_rsvd = {33,31}; } perf_mem_data_src_mt.__index = function(self, key) local kr = perf_mem_data_src_mt.bitfield_ranges[key] if not kr then return nil; end return shared.extractbits64(self.val, kr[1], kr[2]); end perf_mem_data_src_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_mem_data_src_mt.bitfield_ranges[key] if not kr then return nil; end self.val = shared.setbits64(self.val, kr[1], kr[2], value); end ffi.metatype(perf_mem_data_src, perf_mem_data_src_mt); -- type of opcode (load/store/prefetch,code) exports.PERF_MEM_OP_NA = 0x01 -- not available exports.PERF_MEM_OP_LOAD = 0x02 -- load instruction exports.PERF_MEM_OP_STORE = 0x04 -- store instruction exports.PERF_MEM_OP_PFETCH = 0x08 -- prefetch exports.PERF_MEM_OP_EXEC = 0x10 -- code (execution) exports.PERF_MEM_OP_SHIFT = 0 -- memory hierarchy (memory level, hit or miss) exports.PERF_MEM_LVL_NA = 0x01 -- not available exports.PERF_MEM_LVL_HIT = 0x02 -- hit level exports.PERF_MEM_LVL_MISS = 0x04 -- miss level exports.PERF_MEM_LVL_L1 = 0x08 -- L1 exports.PERF_MEM_LVL_LFB = 0x10 -- Line Fill Buffer exports.PERF_MEM_LVL_L2 = 0x20 -- L2 exports.PERF_MEM_LVL_L3 = 0x40 -- L3 exports.PERF_MEM_LVL_LOC_RAM = 0x80 -- Local DRAM exports.PERF_MEM_LVL_REM_RAM1 = 0x100 -- Remote DRAM (1 hop) exports.PERF_MEM_LVL_REM_RAM2 = 0x200 -- Remote DRAM (2 hops) exports.PERF_MEM_LVL_REM_CCE1 = 0x400 -- Remote Cache (1 hop) exports.PERF_MEM_LVL_REM_CCE2 = 0x800 -- Remote Cache (2 hops) exports.PERF_MEM_LVL_IO = 0x1000 -- I/O memory exports.PERF_MEM_LVL_UNC = 0x2000 -- Uncached memory exports.PERF_MEM_LVL_SHIFT = 5 -- snoop mode exports.PERF_MEM_SNOOP_NA = 0x01 -- not available exports.PERF_MEM_SNOOP_NONE = 0x02 -- no snoop exports.PERF_MEM_SNOOP_HIT = 0x04 -- snoop hit exports.PERF_MEM_SNOOP_MISS = 0x08 -- snoop miss exports.PERF_MEM_SNOOP_HITM = 0x10 -- snoop hit modified exports.PERF_MEM_SNOOP_SHIFT = 19 -- locked instruction exports.PERF_MEM_LOCK_NA = 0x01 -- not available exports.PERF_MEM_LOCK_LOCKED = 0x02 -- locked transaction exports.PERF_MEM_LOCK_SHIFT = 24 -- TLB access exports.PERF_MEM_TLB_NA = 0x01 -- not available exports.PERF_MEM_TLB_HIT = 0x02 -- hit level exports.PERF_MEM_TLB_MISS = 0x04 -- miss level exports.PERF_MEM_TLB_L1 = 0x08 -- L1 exports.PERF_MEM_TLB_L2 = 0x10 -- L2 exports.PERF_MEM_TLB_WK = 0x20 -- Hardware Walker exports.PERF_MEM_TLB_OS = 0x40 -- OS fault handler exports.PERF_MEM_TLB_SHIFT = 26 local function PERF_MEM_S(a, s) --(((u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) local id = string.format("PERF_MEM_%s_%s", a, s) local shift = string.format("PERF_MEM_%s_SHIFT", a) return lshift(exports[id], exports[shift]) end return exports
mit
marshmellow42/proxmark3
client/lualibs/hf_reader.lua
6
5956
--[[ THIS IS WORK IN PROGREESS, very much not finished. This library utilises other libraries under the hood, but can be used as a generic reader for 13.56MHz tags. ]] local reader14443A = require('read14a') local cmds = require('commands') local TIMEOUT = 1000 local function sendToDevice(command, ignoreresponse) core.clearCommandBuffer() local err = core.SendCommand(command:getBytes()) if err then print(err) return nil, err end if ignoreresponse then return nil,nil end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) return response,nil end ------------------------------------------------------- -- This will be moved to a separate 14443B library ------------------------------------------------------- local function read14443B() return nil, "Not implemented" end local reader14443B = { read = read14443B } ------------------------------------------------------- -- This will be moved to a separate 1593 library ------------------------------------------------------- local function errorString15693(number) local errors = {} errors[0x01] = "The command is not supported" errors[0x02] = "The command is not recognised" errors[0x03] = "The option is not supported." errors[0x0f] = "Unknown error." errors[0x10] = "The specified block is not available (doesn’t exist)." errors[0x11] = "The specified block is already -locked and thus cannot be locked again" errors[0x12] = "The specified block is locked and its content cannot be changed." errors[0x13] = "The specified block was not successfully programmed." errors[0x14] = "The specified block was not successfully locked." return errors[number] or "Reserved for Future Use or Custom command error." end ------------------------------------------------------- -- This will be moved to a separate 1593 library ------------------------------------------------------- local function parse15693(data) -- From common/iso15693tools.h : --[[ #define ISO15_CRC_CHECK ((uint16_t)(~0xF0B8 & 0xFFFF)) // use this for checking of a correct crc --]] -- But that is very strange. Basically what is says is: -- define ISO15_CRC_CHECK 0F47 -- So we can just use that directly... -- The following code is based on cmdhf15.c around line 666 (NoTB!) and onwards if core.iso15693_crc(data, string.len(data)) ~= 0xF47 then return nil, "CRC failed" elseif data[1] % 2 == 1 then -- Above is a poor-mans bit check: -- recv[0] & ISO15_RES_ERROR //(0x01) local err = "Tag returned error %i: %s" err = string.format(err, data[1],errorString15693(data[1])) return nil, err end -- Finally, let the parsing begin... -- the UID is just the data in reverse... almost: -- 0FC481FF70000104E001001B0301 -- 8877665544332211 -- UID = E004010070FF81C4 -- 1122334455667788 -- So, cut out the relevant part and reverse it local uid = data:sub(2,9):reverse() local uidStr = bin.unpack("H8", uid) local _,manufacturer_code = bin.unpack("s",uid:sub(2,2)) local _,tag_size = bin.unpack(">I",data:sub(12,13)) local _,micref_modelcode = bin.unpack("s",data:sub(14,14)) return { uid = uidStr, manufacturer_code = manufacturer_code, tag_size = tag_size, micref_modelcode = micref_modelcode, } end ------------------------------------------------------- -- This will be moved to a separate 1593 library ------------------------------------------------------- local function read15693() --[[ We start by trying this command: proxmark3> hf 15 cmd sysinfo -2 u 0F C4 81 FF 70 00 01 04 E0 01 00 1B 03 01 UID = E004010070FF81C4 Philips; IC SL2 ICS20 DSFID supported, set to 01 AFI supported, set to 000 Tag provides info on memory layout (vendor dependent) 4 (or 3) bytes/page x 28 pages IC reference given: 01 This command is not always present in ISO15693 tags (it is an optional standard command) but if it is present usually the tags contain all the "colored" info above. If the above command doesn't give an answer (see example below): proxmark3> hf 15 cmd sysinfo -2 u timeout: no we must send the MANDATORY (present in ALL iso15693 tags) command (the example below is sent to a tag different from the above one): proxmark3> hf 15 cmd inquiry UID=E007C1A257394244 Tag Info: Texas Instrument; Tag-it HF-I Standard; 8x32bit proxmark3> From which we obtain less information than the above one. --]] local command, result, info, err, data local data = "02" local datalen = string.len(data) / 2 local speed = 1 local recv = 1 command = Command:new{cmd = cmds.CMD_ISO_15693_COMMAND, arg1 = datalen,arg2 = speed,arg3 =recv, data=data} -- These are defined in common/iso15693tools.h -- #define ISO15_REQ_SUBCARRIER_SINGLE 0x00 // Tag should respond using one subcarrier (ASK) -- #define ISO15_REQ_DATARATE_HIGH 0x02 // Tag should respond using high data rate -- #define ISO15_REQ_NONINVENTORY 0x00 local result,err = sendToDevice(command) if not result then print(err) return nil, "15693 sysinfo: no answer" end local count,cmd,recvLen,arg1,arg2 = bin.unpack('LLLL',result) data = string.sub(result,recvLen) info, err = parse15693(data) if err then return nil, err end return info end local reader15693 = { read = read15693 } --- -- This method library can be set waits or a 13.56 MHz tag, and when one is found, returns info about -- what tag it is. -- -- @return if successfull: an table containing card info -- @return if unsuccessfull : nil, error local function waitForTag() print("Waiting for card... press any key to quit") local readers = {reader14443A, reader14443B, reader15693} local i = 0; while not core.ukbhit() do i = (i % 3) +1 r = readers[i] print("Reading with ",i) res, err = r.read() if res then return res end print(err) -- err means that there was no response from card end return nil, "Aborted by user" end return { waitForTag = waitForTag, }
gpl-2.0
akh00/kong
kong/api/init.lua
2
3659
local lapis = require "lapis" local utils = require "kong.tools.utils" local tablex = require "pl.tablex" local responses = require "kong.tools.responses" local singletons = require "kong.singletons" local app_helpers = require "lapis.application" local api_helpers = require "kong.api.api_helpers" local find = string.find local app = lapis.Application() local NEEDS_BODY = tablex.readonly({ PUT = 1, POST = 2, PATCH = 3 }) local function parse_params(fn) return app_helpers.json_params(function(self, ...) if NEEDS_BODY[ngx.req.get_method()] then local content_type = self.req.headers["content-type"] if content_type and find(content_type:lower(), "application/json", nil, true) then if not self.json then return responses.send_HTTP_BAD_REQUEST("Cannot parse JSON body") end end end self.params = api_helpers.normalize_nested_params(self.params) return fn(self, ...) end) end local function on_error(self) local err = self.errors[1] if type(err) == "table" then if err.db then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err.message) elseif err.unique then return responses.send_HTTP_CONFLICT(err.tbl) elseif err.foreign then return responses.send_HTTP_NOT_FOUND(err.tbl) else return responses.send_HTTP_BAD_REQUEST(err.tbl or err.message) end end end app.default_route = function(self) local path = self.req.parsed_url.path:match("^(.*)/$") if path and self.app.router:resolve(path, self) then return elseif self.app.router:resolve(self.req.parsed_url.path .. "/", self) then return end return self.app.handle_404(self) end app.handle_404 = function(self) return responses.send_HTTP_NOT_FOUND() end app.handle_error = function(self, err, trace) if err and find(err, "don't know how to respond to", nil, true) then return responses.send_HTTP_METHOD_NOT_ALLOWED() end ngx.log(ngx.ERR, err, "\n", trace) -- We just logged the error so no need to give it to responses and log it -- twice return responses.send_HTTP_INTERNAL_SERVER_ERROR() end app:before_filter(function(self) if NEEDS_BODY[ngx.req.get_method()] and not self.req.headers["content-type"] then return responses.send_HTTP_UNSUPPORTED_MEDIA_TYPE() end end) local handler_helpers = { responses = responses, yield_error = app_helpers.yield_error } local function attach_routes(routes) for route_path, methods in pairs(routes) do methods.on_error = methods.on_error or on_error for method_name, method_handler in pairs(methods) do local wrapped_handler = function(self) return method_handler(self, singletons.dao, handler_helpers) end methods[method_name] = parse_params(wrapped_handler) end app:match(route_path, route_path, app_helpers.respond_to(methods)) end end ngx.log(ngx.DEBUG, "Loading Admin API endpoints") -- Load core routes for _, v in ipairs({"kong", "apis", "consumers", "plugins", "cache", "cluster", "certificates", "snis", "upstreams"}) do local routes = require("kong.api.routes." .. v) attach_routes(routes) end -- Loading plugins routes if singletons.configuration and singletons.configuration.plugins then for k in pairs(singletons.configuration.plugins) do local loaded, mod = utils.load_module_if_exists("kong.plugins." .. k .. ".api") if loaded then ngx.log(ngx.DEBUG, "Loading API endpoints for plugin: ", k) attach_routes(mod) else ngx.log(ngx.DEBUG, "No API endpoints loaded for plugin: ", k) end end end return app
apache-2.0
SatoshiNXSimudrone/sl4a-damon-clone
lua/luasocket/samples/cddb.lua
56
1415
local socket = require("socket") local http = require("socket.http") if not arg or not arg[1] or not arg[2] then print("luasocket cddb.lua <category> <disc-id> [<server>]") os.exit(1) end local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" function parse(body) local lines = string.gfind(body, "(.-)\r\n") local status = lines() local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)")) if tonumber(code) ~= 210 then return nil, code, message end local data = {} for l in lines do local c = string.sub(l, 1, 1) if c ~= '#' and c ~= '.' then local key, value = socket.skip(2, string.find(l, "(.-)=(.*)")) value = string.gsub(value, "\\n", "\n") value = string.gsub(value, "\\\\", "\\") value = string.gsub(value, "\\t", "\t") data[key] = value end end return data, code, message end local host = socket.dns.gethostname() local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" local url = string.format(query, server, arg[1], arg[2], host) local body, headers, code = http.get(url) if code == 200 then local data, code, error = parse(body) if not data then print(error or code) else for i,v in pairs(data) do io.write(i, ': ', v, '\n') end end else print(error) end
apache-2.0
Daniex0r/project-roleplay-rp
resources/system-kamer/s_camera_pd_commands.lua
1
1689
function toggleTrafficCam(thePlayer, commandName) local isLoggedIn = getElementData(thePlayer, "loggedin") or 0 if (isLoggedIn == 1) then local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") -- factiontype == law if (factionType == 2) then local resultColshape local results = 0 -- get current colshape for k, theColshape in ipairs(exports.pool:getPoolElementsByType("colshape")) do local isSpeedcam = getElementData(theColshape, "speedcam") if (isSpeedcam) then if (isElementWithinColShape(thePlayer, theColshape)) then resultColshape = theColshape results = results + 1 end end end if (results == 0) then outputChatBox("The system returns an error: No nearby speedcam found.", thePlayer,255,0,0) elseif (results > 1) then outputChatBox("The system returns an error: Too many speedcams near.", thePlayer, 255,0,0) else local gender = getElementData(thePlayer, "gender") local genderm = "his" if (gender == 1) then genderm = "her" end exports.global:sendLocalText(thePlayer, " *"..getPlayerName(thePlayer):gsub("_", " ") .." taps a few keys on " .. genderm .. " mobile data computer.", 255, 51, 102) local result = toggleTrafficCam(resultColshape) if (result == 0) then outputChatBox("Error SPDCM03, please report at the mantis.", thePlayer, 255,0,0) elseif (result == 1) then outputChatBox("The speedcam has been turned off.", thePlayer, 0,255,0) else outputChatBox("The speedcam has been turned on.", thePlayer, 0,255,0) end end end end end addCommandHandler("togglespeedcam", toggleTrafficCam)
gpl-2.0
mediocregopher/ripple
main.lua
1
7312
pp = require 'inspect' ripple = require 'ripple' -- We only do this once, not on every newGame introFade = 255 -- How many seconds the dude should fade out for on death (times 255) deathFadeScale = 1 * 255 -- The font to use fontPath = 'assets/Roboto-Thin.ttf' -- Color palettes available. One will be chosen at random on every newGame. The -- index of the color will be used as the color of a ripple with that many -- bounces in it. So a ripple with no bounces will use the first color, one -- bounce will use the second color, etc... The final color is also used as the -- color of the dude. colors = { { -- The River {159,180,159}, {78,144,135}, {52,98,100}, {37,66,71}, }, { -- River Dance {162,212,224}, {114,198,219}, {68,169,194}, {50,122,140}, {48,71,77}, }, { -- Rivers of Babylon {196,231,242}, {150,224,235}, {104,216,227}, {6,153,173}, {85,100,105}, }, { -- Dream Magent {0,223,252}, {0,180,204}, {0,140,158}, {0,95,107}, {52,56,56}, }, { -- Deep Sky Blues {16,127,201}, {14,78,173}, {11,16,140}, {12,15,102}, {7,9,61}, }, { -- Devastating Loss {184,208,222}, {159,194,214}, {134,180,207}, {115,162,189}, {103,146,171}, }, } function newGame() c = colors[love.math.random(1,table.getn(colors))] cn = table.getn(c) game = { colors = c, fonts = { ["title"] = { font = love.graphics.newFont(fontPath, 128), color = c[cn-1], }, ["instr"] = { font = love.graphics.newFont(fontPath, 48), color = c[cn-1], }, ["count"] = { font = love.graphics.newFont(fontPath, 56), color = c[cn], }, }, ripples = { }, dude = { pos = {x = w/2, y = h/2}, radius = 10, speed = 150, inAir = false, zBump = 0, zVel = 0, color = c[cn], }, progress = { died = false, diedTS = 0, jumps = 0, outroFade = 255, } } return game end function love.load() love.math.setRandomSeed(love.timer.getTime()) love.window.setMode(1024, 1024, { --fullscreen = true, vsync = true, }) love.mouse.setVisible(false) love.graphics.setBackgroundColor(248, 252, 255) w, h = love.graphics.getDimensions() game = newGame() addRipple(w/2, h/2, w/5, 0) end function setFont(f, alpha) if not alpha then alpha = 255 end font = game.fonts[f] love.graphics.setColor(font.color[1], font.color[2], font.color[3], alpha) love.graphics.setFont(font.font) end function isDown(keys) for _, k in pairs(keys) do if love.keyboard.isDown(k) then return true end end end -- These keys have special properties which require them to be here and not in -- the normal key handling: -- * Space: we don't want the player to be able to continuously jump -- * r: this needs debouncing or else when you press it you'll actually be -- making 4 or 5 new games function love.keypressed(key, isrepeat) -- it's "space" on linux, but " " on mac, bleh if (key == "space" or key == " ") and not game.dude.inAir then game.dude.inAir = true game.dude.zVel = 12 elseif key == "r" then game = newGame() end end function math.clamp(low, n, high) return math.min(math.max(n, low), high) end function addRipple(x, y, speed, bounces) r = ripple.new(x, y, speed, bounces, game.colors) game.ripples[r] = true end function love.update(dt) -- Always want to be able to quit if isDown({"escape"}) then love.event.quit() end if game.progress.died then return end w, h = love.graphics.getDimensions() for r in pairs(game.ripples) do if ripple.canDie(r, w, h) then game.ripples[r] = nil end end minx = game.dude.radius miny = game.dude.radius maxx = w - game.dude.radius maxy = h - game.dude.radius if isDown({"w", "up"}) then game.dude.pos.y = math.clamp(miny, game.dude.pos.y - (dt * game.dude.speed), maxy) end if isDown({"s", "down"}) then game.dude.pos.y = math.clamp(miny, game.dude.pos.y + (dt * game.dude.speed), maxy) end if isDown({"a", "left"}) then game.dude.pos.x = math.clamp(minx, game.dude.pos.x - (dt * game.dude.speed), maxx) end if isDown({"d", "right"}) then game.dude.pos.x = math.clamp(minx, game.dude.pos.x + (dt * game.dude.speed), maxy) end game.dude.zBump = game.dude.zBump + game.dude.zVel if game.dude.zBump > 0 then game.dude.zVel = game.dude.zVel - 1 elseif game.dude.zBump < 0 then game.dude.zBump = 0 game.dude.zVel = 0 game.dude.inAir = false game.progress.jumps = game.progress.jumps + 1 speed = love.math.random(w/20, w/15) if game.progress.jumps > 1 then bounces = love.math.random(0,2) else bounces = love.math.random(1,2) end addRipple(game.dude.pos.x, game.dude.pos.y, speed, bounces) end if not game.dude.inAir then for r in pairs(game.ripples) do if ripple.collided(r, game.dude.pos.x, game.dude.pos.y, game.dude.radius) then game.progress.died = true game.progress.diedTS = love.timer.getTime() return end end end introFade = math.clamp(0, introFade - 5, 255) if game.progress.jumps > 0 then game.progress.outroFade = math.clamp(0, game.progress.outroFade - 5, 255) end end function love.draw() for r in pairs(game.ripples) do ripple.draw(r) end drawDude() drawUI() if introFade > 1 then love.graphics.setColor(255, 255, 255, introFade) love.graphics.rectangle("fill", 0, 0, w, h) end end function drawDude() red = game.dude.color[1] green = game.dude.color[2] blue = game.dude.color[3] alpha = 255 if game.progress.died then alpha = 255 - math.clamp(0, (love.timer.getTime() - game.progress.diedTS) * deathFadeScale, 255) end love.graphics.setColor(red, green, blue, alpha) rad = game.dude.radius + (game.dude.zBump / 8) love.graphics.circle("fill", game.dude.pos.x, game.dude.pos.y - game.dude.zBump, rad, 50) end function drawUI() if game.progress.died then setFont("instr") love.graphics.printf("Restart: r\nQuit: esc", 0, h/2 + 200, w, "center") elseif game.progress.outroFade > 0 then setFont("title", game.progress.outroFade) love.graphics.printf("RIPPLE", 0, h/2 - 300, w, "center") setFont("instr", game.progress.outroFade) love.graphics.printf("Move: arrows/wasd\nJump: space", 0, h/2 + 200, w, "center") end if game.progress.jumps > 0 then setFont("count") love.graphics.printf(game.progress.jumps, w - 80, 10, 60, "right") end end
apache-2.0
aqasaeed/mamad
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
Daniex0r/project-roleplay-rp
resources/prp_grafika/grafika_gui_c.lua
1
7169
GUISP = {} local screenWidth, screenHeight = guiGetScreenSize() local left = (screenWidth/2 - 321/2)+screenWidth/4 local top = (screenHeight/2 - 309/2) GUISP.ShaderPanelWindow = guiCreateWindow(left,top,321,309,"Grafika - Opcje",false) GUISP.fps = guiCreateLabel(13,21,296,20,"00 FPS",false,GUISP.ShaderPanelWindow) guiLabelSetVerticalAlign(GUISP.fps,"center") guiLabelSetHorizontalAlign(GUISP.fps,"center",false) GUISP.label2 = guiCreateLabel(13,43,295,20,"Paleta Kolorow",false,GUISP.ShaderPanelWindow) guiLabelSetVerticalAlign(GUISP.label2,"center") guiLabelSetHorizontalAlign(GUISP.label2,"center",false) GUISP.label3 = guiCreateLabel(13,93,295,20,"Shader Bloom",false,GUISP.ShaderPanelWindow) guiLabelSetVerticalAlign(GUISP.label3,"center") guiLabelSetHorizontalAlign(GUISP.label3,"center",false) GUISP.label4 = guiCreateLabel(13,143,295,20,"Auta Shader",false,GUISP.ShaderPanelWindow) guiLabelSetVerticalAlign(GUISP.label4,"center") guiLabelSetHorizontalAlign(GUISP.label4,"center",false) --GUISP.label5 = guiCreateLabel(13,193,295,20,"Water Shader",false,GUISP.ShaderPanelWindow) --guiLabelSetVerticalAlign(GUISP.label5,"center") guiLabelSetHorizontalAlign(GUISP.label5,"center",false) GUISP.spl_save = guiCreateButton(15,258,139,36,"Zapisz",false,GUISP.ShaderPanelWindow) GUISP.spl_close = guiCreateButton(169,258,139,36,"Zamknij",false,GUISP.ShaderPanelWindow) GUISP.palette_choose = guiCreateComboBox(13,65,295,75,"-Wybierz-",false,GUISP.ShaderPanelWindow) guiComboBoxAddItem ( GUISP.palette_choose, "off" ) guiComboBoxAddItem ( GUISP.palette_choose, "paleta 1" ) guiComboBoxAddItem ( GUISP.palette_choose, "paleta 2" ) GUISP.bloom_choose = guiCreateComboBox(13,115,295,60,"-Wybierz-",false,GUISP.ShaderPanelWindow) guiComboBoxAddItem ( GUISP.bloom_choose, "Wylaczone" ) guiComboBoxAddItem ( GUISP.bloom_choose, "Wlaczone" ) GUISP.carpaint_choose = guiCreateComboBox(13,165,295,75,"-Wybierz-",false,GUISP.ShaderPanelWindow) guiComboBoxAddItem ( GUISP.carpaint_choose, "Wylaczone" ) guiComboBoxAddItem ( GUISP.carpaint_choose, "Klasyczne" ) guiComboBoxAddItem ( GUISP.carpaint_choose, "Refleksyjne" ) --GUISP.water_choose = guiCreateComboBox(13,215,295,60,"-choose-",false,GUISP.ShaderPanelWindow) --guiComboBoxAddItem ( GUISP.water_choose, "off" ) --guiComboBoxAddItem ( GUISP.water_choose, "classic" ) guiSetVisible(GUISP.ShaderPanelWindow, false) function toggleShaDanLite() if getElementData (getLocalPlayer(), "spl_logged")==true then local combo_palette=getElementData ( getLocalPlayer(), "spl_palette" ) guiComboBoxSetSelected(GUISP.palette_choose, combo_palette) local combo_bloom= getElementData ( getLocalPlayer(), "spl_bloom" ) guiComboBoxSetSelected(GUISP.bloom_choose, combo_bloom) local combo_carpaint=getElementData ( getLocalPlayer(), "spl_carpaint" ) guiComboBoxSetSelected(GUISP.carpaint_choose, combo_carpaint) local combo_water= getElementData ( getLocalPlayer(), "spl_water" ) guiComboBoxSetSelected(GUISP.water_choose, combo_water) end if (guiGetVisible(GUISP.ShaderPanelWindow)) then showCursor(false) guiSetVisible(GUISP.ShaderPanelWindow,false) else showCursor(true) guiSetVisible(GUISP.ShaderPanelWindow,true) end end bindKey("F4","down",toggleShaDanLite) addCommandHandler("grafika",toggleShaDanLite) function spl_save_func() local combo_palette = getElementData ( getLocalPlayer(), "spl_palette" ) local combo_bloom = getElementData ( getLocalPlayer(), "spl_bloom" ) local combo_carpaint = getElementData ( getLocalPlayer(), "spl_carpaint" ) local combo_water = getElementData ( getLocalPlayer(), "spl_water" ) triggerServerEvent ( "splSave", getLocalPlayer(),combo_water, combo_carpaint, combo_bloom, combo_palette ) end function spl_choose_settings() local combo_palette=guiComboBoxGetSelected(GUISP.palette_choose) setElementData( getLocalPlayer(), "spl_palette",combo_palette ) local combo_bloom=guiComboBoxGetSelected(GUISP.bloom_choose) setElementData( getLocalPlayer(), "spl_bloom",combo_bloom) local combo_carpaint=guiComboBoxGetSelected(GUISP.carpaint_choose) setElementData( getLocalPlayer(), "spl_carpaint",combo_carpaint ) local combo_water=guiComboBoxGetSelected(GUISP.water_choose) setElementData( getLocalPlayer(), "spl_water",combo_water ) Settings.var.PaletteON = getElementData ( getLocalPlayer(), "spl_palette" ) Settings.var.BloomON = getElementData ( getLocalPlayer(), "spl_bloom" ) Settings.var.CarPaintVers = getElementData ( getLocalPlayer(), "spl_carpaint" ) Settings.var.WaterVers = getElementData ( getLocalPlayer(), "spl_water" ) if (Settings.var.PaletteON)>0 then palette = dxCreateTexture ( "images/enbpalette"..Settings.var.PaletteON..".png" ) dxSetShaderValue( paletteShader, "TEX1", palette ) end if Settings.var.CarPaintVers ==0 then carpaint_stopCla() carpaint_stopRef() end if Settings.var.CarPaintVers ==2 then carpaint_stopCla() carpaint_stopRef() carpaint_staRef() end if Settings.var.CarPaintVers ==1 then carpaint_stopCla() carpaint_stopRef() carpaint_staCla() end if Settings.var.WaterVers == 1 then water_stopCla() water_startCla() end if Settings.var.WaterVers == 0 then water_stopCla() end end function spl_close_func() guiSetVisible(GUISP.ShaderPanelWindow, false) showCursor(false) end local frames,lastsec = 0,0 function fpscheck() if (guiGetVisible(GUISP.ShaderPanelWindow)) then local frameticks=getTickCount() frames=frames+1 if frameticks-1000>lastsec then local prog=(frameticks-lastsec) lastsec=frameticks fps=frames/(prog/1000) frames=fps*((prog-1000)/1000) local fps_out=math.floor(fps) local frame_string=tostring(fps_out) frame_string='FPS: '..frame_string..' ' guiSetText ( GUISP.fps,frame_string) end end end addEvent ( "onClientPlayerLogin", true ) addEventHandler ( "onClientPlayerLogin", root, function() if getElementData (getLocalPlayer(), "spl_logged")==true then outputChatBox('Grafika: Ustawiania zostaly przywrocone!') Settings.var.PaletteON = getElementData ( getLocalPlayer(), "spl_palette" ) Settings.var.BloomON = getElementData ( getLocalPlayer(), "spl_bloom" ) Settings.var.CarPaintVers = getElementData ( getLocalPlayer(), "spl_carpaint" ) Settings.var.WaterVers = getElementData ( getLocalPlayer(), "spl_water" ) if (Settings.var.PaletteON)>0 then palette = dxCreateTexture ( "images/enbpalette"..Settings.var.PaletteON..".png" ) dxSetShaderValue( paletteShader, "TEX1", palette ) end if Settings.var.CarPaintVers <=0 then carpaint_stopCla() carpaint_stopRef() end if Settings.var.CarPaintVers ==2 then carpaint_stopCla() carpaint_stopRef() carpaint_staRef() end if Settings.var.CarPaintVers ==1 then carpaint_stopCla() carpaint_stopRef() carpaint_staCla() end if Settings.var.WaterVers == 1 then water_stopCla() water_startCla() end if Settings.var.WaterVers <= 0 then water_stopCla() end end end ) addEventHandler ( "onClientRender", root, fpscheck) addEventHandler("onClientGUIComboBoxAccepted", GUISP.ShaderPanelWindow, spl_choose_settings) addEventHandler("onClientGUIClick", GUISP.spl_save, spl_save_func) addEventHandler("onClientGUIClick", GUISP.spl_close, spl_close_func)
gpl-2.0
DevMoataz/Maestro
plugins/kickme-ar.lua
1
1956
--[[ _ _ _ _____ _____ ____ ____ / \ / \ / \ | ____|___|_ _| /_\ \ / __ \ Đєⱴ 💀: @MaEsTrO_0 / / \/ / \ / _ \ | _| / __| | | | |_\_/| | | | Đєⱴ 💀: @devmaestr0 / / \ \/ \ \ / ___ \| |___\__ \ | | | | \ \| |__| | Đєⱴ ฿๏ͳ💀: @iqMaestroBot /_/ \/ \_/_/ \_|_____|___/ |_| |_| \_\\____/ Đєⱴ ฿๏ͳ💀: @maestr0bot Đєⱴ Ϲḫ₳ͷͷєℓ💀: @DevMaestro —]] local function run(msg, matches) if matches[1] == 'اطردني' then local hash = 'kick:'..msg.to.id..':'..msg.from.id redis:set(hash, "waite") return '▫️ كبد عمري \n▫️ المعرف | @'..msg.from.username..'\n▫️ هل انت متاكد من رغبتك في المغادره😢\n▫️ ارسل ﴿ نعم ﴾ للتاكيد \n▫️ ارسل﴿ لا ﴾ لالغاء المغادره \n▫️ خليك ويانه ليش تغادر 😕😒' end if msg.text then local hash = 'kick:'..msg.to.id..':'..msg.from.id if msg.text:match("^نعم$") and redis:get(hash) == "waite" then redis:set(hash, "ok") elseif msg.text:match("^لا$") and redis:get(hash) == "waite" then send_large_msg(get_receiver(msg), "زين سويت خليك ويانه ليش ماتدخل للقناة اسويك مطور @DevMaestro 🌚🙊") redis:del(hash, true) end end local hash = 'kick:'..msg.to.id..':'..msg.from.id if redis:get(hash) then if redis:get(hash) == "ok" then channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) return 'تم طردك من المجموعه وبعد لا ترجع 😒👍🏿 ('..msg.to.title..')' end end end return { patterns = { '^(اطردني)$', '^(نعم)$', '^(لا)$' , '^[#!/](اطردني)$', '^[#!/](نعم)$', '^[#!/](لا)$' }, run = run, }
gpl-2.0
soheil22222222/ub
plugins/instagram.lua
4
3894
local access_token = "3084249803.280d5d7.999310365c8248f8948ee0f6929c2f02" -- your api key local function instagramUser(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/users/search?q="..URL.escape(query).."&access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if #jdat.data == 0 then send_msg(receiver,"#Error\nUsername not found",ok_cb,false) end if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_message,ok_cb,false) end local id = jdat.data[1].id local gurl = "https://api.instagram.com/v1/users/"..id.."/?access_token="..access_token local ress = https.request(gurl) local user = json:decode(ress) if user.meta.error_message then send_msg(receiver,"#Error\n"..user.meta.error_message,ok_cb,false) end local text = '' if user.data.bio ~= '' then text = text.."Username: "..user.data.username:upper().."\n\n" else text = text.."Username: "..user.data.username:upper().."\n" end if user.data.bio ~= '' then text = text..user.data.bio.."\n\n" end if user.data.full_name ~= '' then text = text.."Name: "..user.data.full_name.."\n" end text = text.."Media Count: "..user.data.counts.media.."\n" text = text.."Following: "..user.data.counts.follows.."\n" text = text.."Followers: "..user.data.counts.followed_by.."\n" if user.data.website ~= '' then text = text.."Website: "..user.data.website.."\n" end text = text.."\n@GPMod" local file_path = download_to_file(user.data.profile_picture,"insta.png") -- disable this line if you want to send profile photo as sticker --local file_path = download_to_file(user.data.profile_picture,"insta.webp") -- enable this line if you want to send profile photo as sticker local cb_extra = {file_path=file_path} local mime_type = mimetype.get_content_type_no_sub(ext) send_photo(receiver, file_path, rmtmp_cb, cb_extra) -- disable this line if you want to send profile photo as sticker --send_document(receiver, file_path, rmtmp_cb, cb_extra) -- enable this line if you want to send profile photo as sticker send_msg(receiver,text,ok_cb,false) end local function instagramMedia(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/media/shortcode/"..URL.escape(query).."?access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_type.."\n"..jdat.meta.error_message,ok_cb,false) end local text = '' local data = '' if jdat.data.caption then data = jdat.data.caption text = text.."Username: "..data.from.username:upper().."\n\n" text = text..data.from.full_name.."\n\n" text = text..data.text.."\n\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" else text = text.."Username: "..jdat.data.user.username:upper().."\n" text = text.."Name: "..jdat.data.user.full_name.."\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" end text = text.."\n@GPMod" send_msg(receiver,text,ok_cb,false) end local function run(msg, matches) if matches[1] == "insta" and not matches[3] then return instagramUser(msg,matches[2]) end if matches[1] == "insta" and matches[3] then local media = matches[3] if string.match(media , '/') then media = media:gsub("/", "") end return instagramMedia(msg,media) end end return { patterns = { "^[#/!]([Ii]nsta) ([Hh]ttps://www.instagram.com/p/)([^%s]+)$", "^[#/!]([Ii]nsta) ([Hh]ttps://instagram.com/p/)([^%s]+)$", "^[#/!]([Ii]nsta) ([Hh]ttp://www.instagram.com/p/)([^%s]+)$", "^[#/!]([Ii]nsta) ([Hh]ttp://instagram.com/p/)([^%s]+)$", "^[#/!]([Ii]nsta) ([^%s]+)$", }, run = run }
gpl-2.0
LucentW/s-uzzbot
plugins/gnuplot.lua
2
1986
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) if string.match(fun, "\"") or string.match(fun, "'") or string.match(fun, "`") then return "Invalid input" end -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot lacks a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
dddaaaddd/hunter_bot
plugins/Plugins.lua
1
6389
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local tmp = '\n\n@MAX_TM' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end local text = text..'\n\n'..nsum..' plugins installed\n\n'..nact..' plugins enabled\n\n'..nsum-nact..' plugins disabled'..tmp return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end local text = text..'\nPlugins Reloaded !\n\n'..nact..' plugins enabled\n'..nsum..' plugins installed\n\n@MAX_TM' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return ''..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return ''..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return ' '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return ' '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return ' '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return ' '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'chat' then if is_momod(msg) then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo if is_momod(msg) then local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'chat' then if is_momod(msg) then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins + [plugin] : enable plugin.", "!plugins - [plugin] : disable plugin.", "!plugins * : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (+) ([%w_%.%-]+)$", "^!plugins? (-) ([%w_%.%-]+)$", "^!plugins? (+) ([%w_%.%-]+) (chat)", "^!plugins? (-) ([%w_%.%-]+) (chat)", "^!plugins? (*)$", "^[!/](reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
akh00/kong
kong/cmd/migrations.lua
1
1817
local conf_loader = require "kong.conf_loader" local DAOFactory = require "kong.dao.factory" local log = require "kong.cmd.utils.log" local concat = table.concat local ANSWERS = { y = true, Y = true, yes = true, YES = true, n = false, N = false, no = false, NO = false } local function confirm(q) local max = 3 while max > 0 do io.write("> " .. q .. " [Y/n] ") local a = io.read("*l") if ANSWERS[a] ~= nil then return ANSWERS[a] end max = max - 1 end end local function execute(args) local conf = assert(conf_loader(args.conf)) local dao = assert(DAOFactory.new(conf)) if args.command == "up" then assert(dao:run_migrations()) elseif args.command == "list" then local migrations = assert(dao:current_migrations()) local db_infos = dao:infos() if next(migrations) then log("Executed migrations for %s '%s':", db_infos.desc, db_infos.name) for id, row in pairs(migrations) do log("%s: %s", id, concat(row, ", ")) end else log("No migrations have been run yet for %s '%s'", db_infos.desc, db_infos.name) end elseif args.command == "reset" then if confirm("Are you sure? This operation is irreversible.") then dao:drop_schema() log("Schema successfully reset") else log("Canceled") end end end local lapp = [[ Usage: kong migrations COMMAND [OPTIONS] Manage Kong's database migrations. The available commands are: list List migrations currently executed. up Execute all missing migrations up to the latest available. reset Reset the configured database (irreversible). Options: -c,--conf (optional string) configuration file ]] return { lapp = lapp, execute = execute, sub_commands = {up = true, list = true, reset = true} }
apache-2.0
emadni/Telelord-
plugins/stats.lua
236
3989
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
larber/domoticz
scripts/dzVents/runtime/Utils.lua
5
1304
local self = { LOG_ERROR = 1, LOG_FORCE = 0.5, LOG_MODULE_EXEC_INFO = 2, LOG_INFO = 3, LOG_DEBUG = 4, } function self.fileExists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end function self.osExecute(cmd) if (_G.TESTMODE) then return end os.execute(cmd) end function self.print(msg) if (_G.TESTMODE) then return end print(msg) end function self.urlEncode(str) if (str) then str = string.gsub(str, "\n", "\r\n") str = string.gsub(str, "([^%w %-%_%.%~])", function(c) return string.format("%%%02X", string.byte(c)) end) str = string.gsub(str, " ", "+") end return str end function self.log(msg, level) if (level == nil) then level = self.LOG_INFO end local lLevel = _G.logLevel == nil and 1 or _G.logLevel local marker = '' if (level == self.LOG_ERROR) then marker = marker .. 'Error: ' elseif (level == self.LOG_DEBUG) then marker = marker .. 'Debug: ' elseif (level == self.LOG_INFO or level == self.LOG_MODULE_EXEC_INFO) then marker = marker .. 'Info: ' elseif (level == self.LOG_FORCE) then marker = marker .. '!Info: ' end if (_G.logMarker ~= nil) then marker = marker .. _G.logMarker .. ': ' end if (level <= lLevel) then self.print(tostring(marker) .. msg) end end return self
gpl-3.0
stephank/luci
libs/nixio/docsrc/nixio.bit.lua
171
2044
--- Bitfield operators and mainpulation functions. -- Can be used as a drop-in replacement for bitlib. module "nixio.bit" --- Bitwise OR several numbers. -- @class function -- @name bor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Invert given number. -- @class function -- @name bnot -- @param oper Operand -- @return number --- Bitwise AND several numbers. -- @class function -- @name band -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Bitwise XOR several numbers. -- @class function -- @name bxor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Left shift a number. -- @class function -- @name lshift -- @param oper number -- @param shift bits to shift -- @return number --- Right shift a number. -- @class function -- @name rshift -- @param oper number -- @param shift bits to shift -- @return number --- Arithmetically right shift a number. -- @class function -- @name arshift -- @param oper number -- @param shift bits to shift -- @return number --- Integer division of 2 or more numbers. -- @class function -- @name div -- @param oper1 Operand 1 -- @param oper2 Operand 2 -- @param ... More Operands -- @return number --- Cast a number to the bit-operating range. -- @class function -- @name cast -- @param oper number -- @return number --- Sets one or more flags of a bitfield. -- @class function -- @name set -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Unsets one or more flags of a bitfield. -- @class function -- @name unset -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Checks whether given flags are set in a bitfield. -- @class function -- @name check -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return true when all flags are set, otherwise false
apache-2.0
ld-test/tapered
src/tapered.lua
1
4354
-- Helper variables and functions local get_info = debug.getinfo local pcall = pcall local slice = string.sub local sprintf = string.format local str_find = string.find local tonumber = tonumber -- Lua 5.3 moved unpack to table.unpack local unpack = unpack or table.unpack local write = io.write local rawget = rawget local getmetatable = getmetatable local exit = os.exit ---- Helper methods --- C-like printf method local printf = function(fmt, ...) write(sprintf(fmt, ...)) end --- Compare potentially complex tables or objects -- -- Ideas here are taken from [Penlight][p], [Underscore][u], [cwtest][cw], and -- [luassert][l]. -- [p]: https://github.com/stevedonovan/Penlight -- [u]: https://github.com/mirven/underscore.lua -- [cw]: https://github.com/catwell/cwtest -- [l]: https://github.com/Olivine-Labs/luassert -- -- Predeclare both function names local keyvaluesame local deepsame -- --- keyvaluesame(table, table) => true or false -- Helper method to compare all the keys and values of a table keyvaluesame = function (t1, t2) for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not deepsame(v1, v2) then return false end end -- Check for any keys present in t2 but not t1 for k2, _ in pairs(t2) do if t1[k2] == nil then return false end end return true end -- --- deepsame(item, item) => true or false -- Compare two items of any type for identity deepsame = function (t1, t2) local ty1, ty2 = type(t1), type(t2) if ty1 ~= ty2 then return false end if ty1 ~= 'table' then return t1 == t2 end -- If ._eq is found, use == and end quickly. -- As of Lua 5.3 == only cares if **one** of the two items has a __eq -- metamethod. Penlight, underscore and cwtest take the same approach, -- so I will as well. local eq = rawget(getmetatable(t1) or {}, '__eq') if (type(eq) == 'function') then return not not eq(t1, t2) else return keyvaluesame(t1, t2) end end ---- tapered test suite local exit_status = 0 local test_count = 0 local debug_level = 3 local setup_call = function () if _G["setup"] then return _G["setup"]() end end local teardown_call = function () if _G["teardown"] then return _G["teardown"]() end end -- All other tests are defined in terms of this primitive, which is -- kept private. local _test = function (exp, msg) test_count = test_count + 1 if msg then msg = sprintf(" - %s", msg) else msg = '' end setup_call() if exp then printf("ok %s%s\n", test_count, msg) else exit_status = 1 + exit_status printf("not ok %s%s\n", test_count, msg) local info = get_info(debug_level) printf("# Trouble in %s around line %s\n", slice(info.source, 2), info.currentline) end teardown_call() end local ok = function (expression, msg) _test(expression, msg) end local nok = function (expression, msg) _test(not expression, msg) end local is = function (actual, expected, msg) _test(actual == expected, msg) end local isnt = function (actual, expected, msg) _test(actual ~= expected, msg) end local same = function (actual, expected, msg) _test(deepsame(actual, expected), msg) end local like = function (str, pattern, msg) _test(str_find(str, pattern), msg) end local unlike = function (str, pattern, msg) _test(not str_find(str, pattern), msg) end local pass = function (msg) _test(true, msg) end local fail = function (msg) _test(false, msg) end local boom = function (func, args, msg) local err, errmsg err, errmsg = pcall(func, unpack(args)) _test(not err, msg) if not err and type(errmsg) == 'string' then printf('# Got this error: "%s"\n', errmsg) end end local done = function (n) local expected = tonumber(n) if not expected or test_count == expected then printf('1..%d\n', test_count) elseif expected ~= test_count then exit_status = 1 + exit_status local s if expected == 1 then s = '' else s = 's' end printf("# Bad plan. You planned %d test%s but ran %d\n", expected, s, test_count) end exit(exit_status) end return { ok = ok, nok = nok, is = is, isnt = isnt, same = same, like = like, unlike = unlike, pass = pass, fail = fail, boom = boom, done = done, _VERSION = '1.1-0', _AUTHOR = 'Peter Aronoff', _URL = 'https://bitbucket.org/telemachus/tapered', _LICENSE = 'BSD 3-Clause' }
bsd-3-clause
UnluckyNinja/PathOfBuilding
Classes/Control.lua
1
3412
-- Path of Building -- -- Class: Control -- UI control base class -- local launch, main = ... local t_insert = table.insert local m_floor = math.floor local anchorPos = { ["TOPLEFT"] = { 0 , 0 }, ["TOP"] = { 0.5, 0 }, ["TOPRIGHT"] = { 1 , 0 }, ["RIGHT"] = { 1 , 0.5 }, ["BOTTOMRIGHT"] = { 1 , 1 }, ["BOTTOM"] = { 0.5, 1 }, ["BOTTOMLEFT"] = { 0 , 1 }, ["LEFT"] = { 0 , 0.5 }, ["CENTER"] = { 0.5, 0.5 }, } local ControlClass = common.NewClass("Control", function(self, anchor, x, y, width, height) self.x = x or 0 self.y = y or 0 self.width = width or 0 self.height = height or 0 self.shown = true self.enabled = true self.anchor = { } if anchor then self:SetAnchor(anchor[1], anchor[2], anchor[3]) end end) function ControlClass:GetProperty(name) if type(self[name]) == "function" then return self[name](self) else return self[name] end end function ControlClass:SetAnchor(point, other, otherPoint, x, y) self.anchor.point = point self.anchor.other = other self.anchor.otherPoint = otherPoint if x and y then self.x = x self.y = y end end function ControlClass:GetPos() local x = self:GetProperty("x") local y = self:GetProperty("y") if self.anchor.other then local otherX, otherY = self.anchor.other:GetPos() local otherW, otherH = 0, 0 local width, height = 0, 0 local otherPos = anchorPos[self.anchor.otherPoint] assert(otherPos, "invalid anchor position '"..tostring(self.anchor.otherPoint).."'") if self.anchor.otherPoint ~= "TOPLEFT" then otherW, otherH = self.anchor.other:GetSize() end local pos = anchorPos[self.anchor.point] assert(pos, "invalid anchor position '"..tostring(self.anchor.point).."'") if self.anchor.point ~= "TOPLEFT" then width, height = self:GetSize() end x = m_floor(otherX + otherW * otherPos[1] + x - width * pos[1]) y = m_floor(otherY + otherH * otherPos[2] + y - height * pos[2]) end return x, y end function ControlClass:GetSize() return self:GetProperty("width"), self:GetProperty("height") end function ControlClass:IsShown() return (not self.anchor.other or self.anchor.other:IsShown()) and self:GetProperty("shown") end function ControlClass:IsEnabled() return self:GetProperty("enabled") end function ControlClass:IsMouseInBounds() local x, y = self:GetPos() local width, height = self:GetSize() local cursorX, cursorY = GetCursorPos() return cursorX >= x and cursorY >= y and cursorX < x + width and cursorY < y + height end function ControlClass:SetFocus(focus) if focus ~= self.hasFocus then if focus and self.OnFocusGained then self:OnFocusGained() elseif not focus and self.OnFocusLost then self:OnFocusLost() end self.hasFocus = focus end end function ControlClass:AddToTabGroup(master) if master.tabOrder then t_insert(master.tabOrder, self) else master.tabOrder = { master, self } end self.tabOrder = master.tabOrder end function ControlClass:TabAdvance(step) if self.tabOrder then local index = isValueInArray(self.tabOrder, self) if index then while true do index = index + step if index > #self.tabOrder then index = 1 elseif index < 1 then index = #self.tabOrder end if self.tabOrder[index] == self or (self.tabOrder[index].OnKeyDown and self.tabOrder[index]:IsShown()) then return self.tabOrder[index] end end end end return self end
mit
RicoP/vlcfork
share/lua/playlist/anevia_streams.lua
112
3664
--[[ $Id$ Parse list of available streams on Anevia Toucan servers. The URI http://ipaddress:554/list_streams.idp describes a list of available streams on the server. Copyright © 2009 M2X BV Authors: Jean-Paul Saman <jpsaman@videolan.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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "list_streams.idp" ) end -- Parse function. function parse() p = {} _,_,server = string.find( vlc.path, "(.*)/list_streams.idp" ) while true do line = vlc.readline() if not line then break end if string.match( line, "<streams[-]list> </stream[-]list>" ) then break elseif string.match( line, "<streams[-]list xmlns=\"(.*)\">" ) then while true do line = vlc.readline() if not line then break end if string.match( line, "<streamer name=\"(.*)\"> </streamer>" ) then break; elseif string.match( line, "<streamer name=\"(.*)\">" ) then _,_,streamer = string.find( line, "name=\"(.*)\"" ) while true do line = vlc.readline() if not line then break end -- ignore <host name=".." /> tags -- ignore <port number=".." /> tags if string.match( line, "<input name=\"(.*)\">" ) then _,_,path = string.find( line, "name=\"(.*)\"" ) while true do line = vlc.readline() if not line then break end if string.match( line, "<stream id=\"(.*)\" />" ) then _,_,media = string.find( line, "id=\"(.*)\"" ) video = "rtsp://" .. tostring(server) .. "/" .. tostring(path) .. "/" .. tostring(media) vlc.msg.dbg( "adding to playlist " .. tostring(video) ) table.insert( p, { path = video; name = media, url = video } ) end -- end of input tag found if string.match( line, "</input>" ) then break end end end end if not line then break end -- end of streamer tag found if string.match( line, "</streamer>" ) then break end end if not line then break end -- end of streams-list tag found if string.match( line, "</streams-list>" ) then break end end end end return p end
gpl-2.0
moltafet35/ssssis
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
theonlywild/erfaan
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
artynet/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua
18
3606
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("RRDTool Plugin Configuration"), translate( "The rrdtool plugin stores the collected data in rrd database " .. "files, the foundation of the diagrams.<br /><br />" .. "<strong>Warning: Setting the wrong values will result in a very " .. "high memory consumption in the temporary directory. " .. "This can render the device unusable!</strong>" )) -- collectd_rrdtool config section s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" ) -- collectd_rrdtool.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 1 -- collectd_rrdtool.datadir (DataDir) datadir = s:option( Value, "DataDir", translate("Storage directory"), translate("Note: as pages are rendered by user 'nobody', the *.rrd files, " .. "the storage directory and all its parent directories need " .. "to be world readable." )) datadir.default = "/tmp" datadir.rmempty = true datadir.optional = true datadir:depends( "enable", 1 ) -- collectd_rrdtool.stepsize (StepSize) stepsize = s:option( Value, "StepSize", translate("RRD step interval"), translate("Seconds") ) stepsize.default = 30 stepsize.isinteger = true stepsize.rmempty = true stepsize.optional = true stepsize:depends( "enable", 1 ) -- collectd_rrdtool.heartbeat (HeartBeat) heartbeat = s:option( Value, "HeartBeat", translate("RRD heart beat interval"), translate("Seconds") ) heartbeat.default = 60 heartbeat.isinteger = true heartbeat.rmempty = true heartbeat.optional = true heartbeat:depends( "enable", 1 ) -- collectd_rrdtool.rrasingle (RRASingle) rrasingle = s:option( Flag, "RRASingle", translate("Only create average RRAs"), translate("reduces rrd size") ) rrasingle.default = true rrasingle:depends( "enable", 1 ) -- collectd_rrdtool.rramax (RRAMax) rramax = s:option( Flag, "RRAMax", translate("Show max values instead of averages"), translate("Max values for a period can be used instead of averages when not using 'only average RRAs'") ) rramax.default = false rramax.rmempty = true rramax:depends( "RRASingle", 0 ) -- collectd_rrdtool.rratimespans (RRATimespan) rratimespans = s:option( Value, "RRATimespans", translate("Stored timespans"), translate("seconds; multiple separated by space") ) rratimespans.default = "600 86400 604800 2678400 31622400" rratimespans.rmempty = true rratimespans.optional = true rratimespans:depends( "enable", 1 ) -- collectd_rrdtool.rrarows (RRARows) rrarows = s:option( Value, "RRARows", translate("Rows per RRA") ) rrarows.isinteger = true rrarows.default = 100 rrarows.rmempty = true rrarows.optional = true rrarows:depends( "enable", 1 ) -- collectd_rrdtool.xff (XFF) xff = s:option( Value, "XFF", translate("RRD XFiles Factor") ) xff.default = 0.1 xff.isnumber = true xff.rmempty = true xff.optional = true xff:depends( "enable", 1 ) -- collectd_rrdtool.cachetimeout (CacheTimeout) cachetimeout = s:option( Value, "CacheTimeout", translate("Cache collected data for"), translate("Seconds") ) cachetimeout.isinteger = true cachetimeout.default = 100 cachetimeout.rmempty = true cachetimeout.optional = true cachetimeout:depends( "enable", 1 ) -- collectd_rrdtool.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Flush cache after"), translate("Seconds") ) cacheflush.isinteger = true cacheflush.default = 100 cacheflush.rmempty = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
pchote/OpenRA
mods/ra/maps/sarin-gas-1-crackdown/crackdown-AI.lua
2
2806
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] IdlingUnits = { } AttackGroup = { } AttackGroupSize = 10 BGAttackGroup = { } BGAttackGroupSize = 8 SovietInfantry = { "e1", "e2", "e4" } SovietVehicles = { "ttnk", "3tnk", "3tnk", "v2rl" } ProductionInterval = { easy = DateTime.Seconds(25), normal = DateTime.Seconds(15), hard = DateTime.Seconds(5) } GroundAttackUnits = { { "ttnk", "ttnk", "e2", "e2", "e2" }, { "3tnk", "v2rl", "e4", "e4", "e4" } } GroundAttackPaths = { { EscapeSouth5.Location, Patrol1.Location }, { EscapeNorth10.Location, EscapeNorth7.Location } } GroundWavesDelays = { easy = 4, normal = 3, hard = 2 } SendBGAttackGroup = function() if #BGAttackGroup < BGAttackGroupSize then return end Utils.Do(BGAttackGroup, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end) BGAttackGroup = { } end ProduceBadGuyInfantry = function() if BadGuyRax.IsDead or BadGuyRax.Owner ~= badguy then return end badguy.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(BGAttackGroup, units[1]) SendBGAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceBadGuyInfantry) end) end SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end Utils.Do(AttackGroup, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceUSSRInfantry = function() if USSRRax.IsDead or USSRRax.Owner ~= ussr then return end ussr.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceUSSRInfantry) end) end ProduceVehicles = function() if USSRWarFactory.IsDead or USSRWarFactory.Owner ~= ussr then return end ussr.Build({ Utils.Random(SovietVehicles) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end GroundWaves = function() Reinforcements.Reinforce(ussr, Utils.Random(GroundAttackUnits), Utils.Random(GroundAttackPaths), 0, function(unit) unit.Hunt() end) Trigger.AfterDelay(DateTime.Minutes(GroundWavesDelays), GroundWaves) end ActivateAI = function() GroundWavesDelays = GroundWavesDelays[Difficulty] ProduceBadGuyInfantry() ProduceUSSRInfantry() Trigger.AfterDelay(DateTime.Minutes(1), ProduceVehicles) Trigger.AfterDelay(DateTime.Minutes(4), GroundWaves) end
gpl-3.0
noctux/philote
src/opkg.lua
1
4474
#!/usr/bin/lua local Ansible = require("ansible") function update_package_db(module, opkg_path) local rc, out, err = module:run_command(string.format("%s update", opkg_path)) if rc ~= 0 then module:fail_json({msg = "could not update package db", opkg={rc=rc, out=out, err=err}}) end end function query_package(module, opkg_path, name) local rc, out, err = module:run_command(string.format("%s list-installed", opkg_path)) if rc ~= 0 then module:fail_json({msg = "failed to list installed packages", opkg={rc=rc, out=out, err=err}}) end for line in string.gmatch(out, "[^\n]+") do if name == string.match(line, "^(%S+)%s") then return true end end return false end function get_force(force) if force and string.len(force) > 0 then return "--force-" .. force else return "" end end function remove_packages(module, opkg_path, packages) local p = module:get_params() local force = get_force(p["force"]) local remove_c = 0 for _,package in ipairs(packages) do -- Query the package first, to see if we even need to remove if query_package(module, opkg_path, package) then if not module:check_mode() then local rc, out, err = module:run_command(string.format("%s remove %s %q", opkg_path, force, package)) if rc ~= 0 or query_package(module, opkg_path, package) then module:fail_json({msg="failed to remove " .. package, opkg={rc=rc, out=out, err=err}}) end end remove_c = remove_c + 1; end end if remove_c > 0 then module:exit_json({changed=true, msg=string.format("removed %d package(s)", remove_c)}) else module:exit_json({changed=false, msg="package(s) already absent"}) end end function install_packages(module, opkg_path, packages) local p = module:get_params() local force = get_force(p["force"]) local install_c = 0 for _,package in ipairs(packages) do -- Query the package first, to see if we even need to remove if not query_package(module, opkg_path, package) then if not module:check_mode() then local rc, out, err = module:run_command(string.format("%s install %s %s", opkg_path, force, package)) if rc ~= 0 or not query_package(module, opkg_path, package) then module:fail_json({msg=string.format("failed to install %s", package), opkg={rc=rc, out=out, err=err}}) end end install_c = install_c + 1; end end if install_c > 0 then module:exit_json({changed=true, msg=string.format("installed %s packages(s)", install_c)}) else module:exit_json({changed=false, msg="package(s) already present"}) end end function last_cache_update_timestamp(module) local rc, stdout, stderr = module:run_command("date +%s -r /tmp/opkg-lists") if rc ~= 0 then return nil else return tonumber(stdout) end end function current_timestamp(module) local rc, stdout, stderr = module:run_command("date +%s") return tonumber(stdout) end function cache_age(module) local last_update = last_cache_update_timestamp(module) if last_update == nil then return nil else return current_timestamp(module) - last_update end end function should_update_cache(module) if module.params.update_cache then return true end if module.params.cache_valid_time ~= nil then local age = cache_age(module) if age == nil then return true end if age > module.params.cache_valid_time then return true end end return false end function update_cache_if_needed(module, opkg_path) if should_update_cache(module) and not module:check_mode() then update_package_db(module, opkg_path) end end function main(arg) local module = Ansible.new({ name = { aliases = {"pkg"}, required=true , type='list'}, state = { default = "present", choices={"present", "installed", "absent", "removed"} }, force = { default = "", choices={"", "depends", "maintainer", "reinstall", "overwrite", "downgrade", "space", "postinstall", "remove", "checksum", "removal-of-dependent-packages"} } , update_cache = { default = "no", aliases={ "update-cache" }, type='bool' }, cache_valid_time = { type='int' } }) local opkg_path = module:get_bin_path('opkg', true, {'/bin'}) module:parse(arg[1]) local p = module:get_params() update_cache_if_needed(module, opkg_path) local state = p["state"] local packages = p["name"] if "present" == state or "installed" == state then install_packages(module, opkg_path, packages) elseif "absent" == state or "removed" == state then remove_packages(module, opkg_path, packages) end end main(arg)
agpl-3.0
stephank/luci
libs/httpclient/luasrc/httpclient.lua
41
9111
--[[ LuCI - Lua Development Framework Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require "nixio.util" local nixio = require "nixio" local ltn12 = require "luci.ltn12" local util = require "luci.util" local table = require "table" local http = require "luci.http.protocol" local date = require "luci.http.protocol.date" local type, pairs, ipairs, tonumber = type, pairs, ipairs, tonumber local unpack = unpack module "luci.httpclient" function chunksource(sock, buffer) buffer = buffer or "" return function() local output local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") while not count and #buffer <= 1024 do local newblock, code = sock:recv(1024 - #buffer) if not newblock then return nil, code end buffer = buffer .. newblock _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") end count = tonumber(count, 16) if not count then return nil, -1, "invalid encoding" elseif count == 0 then return nil elseif count + 2 <= #buffer - endp then output = buffer:sub(endp+1, endp+count) buffer = buffer:sub(endp+count+3) return output else output = buffer:sub(endp+1, endp+count) buffer = "" if count - #output > 0 then local remain, code = sock:recvall(count-#output) if not remain then return nil, code end output = output .. remain count, code = sock:recvall(2) else count, code = sock:recvall(count+2-#buffer+endp) end if not count then return nil, code end return output end end end function request_to_buffer(uri, options) local source, code, msg = request_to_source(uri, options) local output = {} if not source then return nil, code, msg end source, code = ltn12.pump.all(source, (ltn12.sink.table(output))) if not source then return nil, code end return table.concat(output) end function request_to_source(uri, options) local status, response, buffer, sock = request_raw(uri, options) if not status then return status, response, buffer elseif status ~= 200 and status ~= 206 then return nil, status, buffer end if response.headers["Transfer-Encoding"] == "chunked" then return chunksource(sock, buffer) else return ltn12.source.cat(ltn12.source.string(buffer), sock:blocksource()) end end -- -- GET HTTP-resource -- function request_raw(uri, options) options = options or {} local pr, auth, host, port, path if uri:find("@") then pr, auth, host, port, path = uri:match("(%w+)://(.+)@([%w-.]+):?([0-9]*)(.*)") else pr, host, port, path = uri:match("(%w+)://([%w-.]+):?([0-9]*)(.*)") end if not host then return nil, -1, "unable to parse URI" end if pr ~= "http" and pr ~= "https" then return nil, -2, "protocol not supported" end port = #port > 0 and port or (pr == "https" and 443 or 80) path = #path > 0 and path or "/" options.depth = options.depth or 10 local headers = options.headers or {} local protocol = options.protocol or "HTTP/1.1" headers["User-Agent"] = headers["User-Agent"] or "LuCI httpclient 0.1" if headers.Connection == nil then headers.Connection = "close" end if auth and not headers.Authorization then headers.Authorization = "Basic " .. nixio.bin.b64encode(auth) end local sock, code, msg = nixio.connect(host, port) if not sock then return nil, code, msg end sock:setsockopt("socket", "sndtimeo", options.sndtimeo or 15) sock:setsockopt("socket", "rcvtimeo", options.rcvtimeo or 15) if pr == "https" then local tls = options.tls_context or nixio.tls() sock = tls:create(sock) local stat, code, error = sock:connect() if not stat then return stat, code, error end end -- Pre assemble fixes if protocol == "HTTP/1.1" then headers.Host = headers.Host or host end if type(options.body) == "table" then options.body = http.urlencode_params(options.body) end if type(options.body) == "string" then headers["Content-Length"] = headers["Content-Length"] or #options.body headers["Content-Type"] = headers["Content-Type"] or "application/x-www-form-urlencoded" options.method = options.method or "POST" end if type(options.body) == "function" then options.method = options.method or "POST" end -- Assemble message local message = {(options.method or "GET") .. " " .. path .. " " .. protocol} for k, v in pairs(headers) do if type(v) == "string" or type(v) == "number" then message[#message+1] = k .. ": " .. v elseif type(v) == "table" then for i, j in ipairs(v) do message[#message+1] = k .. ": " .. j end end end if options.cookies then for _, c in ipairs(options.cookies) do local cdo = c.flags.domain local cpa = c.flags.path if (cdo == host or cdo == "."..host or host:sub(-#cdo) == cdo) and (cpa == path or cpa == "/" or cpa .. "/" == path:sub(#cpa+1)) and (not c.flags.secure or pr == "https") then message[#message+1] = "Cookie: " .. c.key .. "=" .. c.value end end end message[#message+1] = "" message[#message+1] = "" -- Send request sock:sendall(table.concat(message, "\r\n")) if type(options.body) == "string" then sock:sendall(options.body) elseif type(options.body) == "function" then local res = {options.body(sock)} if not res[1] then sock:close() return unpack(res) end end -- Create source and fetch response local linesrc = sock:linesource() local line, code, error = linesrc() if not line then sock:close() return nil, code, error end local protocol, status, msg = line:match("^([%w./]+) ([0-9]+) (.*)") if not protocol then sock:close() return nil, -3, "invalid response magic: " .. line end local response = { status = line, headers = {}, code = 0, cookies = {}, uri = uri } line = linesrc() while line and line ~= "" do local key, val = line:match("^([%w-]+)%s?:%s?(.*)") if key and key ~= "Status" then if type(response.headers[key]) == "string" then response.headers[key] = {response.headers[key], val} elseif type(response.headers[key]) == "table" then response.headers[key][#response.headers[key]+1] = val else response.headers[key] = val end end line = linesrc() end if not line then sock:close() return nil, -4, "protocol error" end -- Parse cookies if response.headers["Set-Cookie"] then local cookies = response.headers["Set-Cookie"] for _, c in ipairs(type(cookies) == "table" and cookies or {cookies}) do local cobj = cookie_parse(c) cobj.flags.path = cobj.flags.path or path:match("(/.*)/?[^/]*") if not cobj.flags.domain or cobj.flags.domain == "" then cobj.flags.domain = host response.cookies[#response.cookies+1] = cobj else local hprt, cprt = {}, {} -- Split hostnames and save them in reverse order for part in host:gmatch("[^.]*") do table.insert(hprt, 1, part) end for part in cobj.flags.domain:gmatch("[^.]*") do table.insert(cprt, 1, part) end local valid = true for i, part in ipairs(cprt) do -- If parts are different and no wildcard if hprt[i] ~= part and #part ~= 0 then valid = false break -- Wildcard on invalid position elseif hprt[i] ~= part and #part == 0 then if i ~= #cprt or (#hprt ~= i and #hprt+1 ~= i) then valid = false break end end end -- No TLD cookies if valid and #cprt > 1 and #cprt[2] > 0 then response.cookies[#response.cookies+1] = cobj end end end end -- Follow response.code = tonumber(status) if response.code and options.depth > 0 then if response.code == 301 or response.code == 302 or response.code == 307 and response.headers.Location then local nuri = response.headers.Location or response.headers.location if not nuri then return nil, -5, "invalid reference" end if not nuri:find("https?://") then nuri = pr .. "://" .. host .. ":" .. port .. nuri end options.depth = options.depth - 1 if options.headers then options.headers.Host = nil end sock:close() return request_raw(nuri, options) end end return response.code, response, linesrc(true), sock end function cookie_parse(cookiestr) local key, val, flags = cookiestr:match("%s?([^=;]+)=?([^;]*)(.*)") if not key then return nil end local cookie = {key = key, value = val, flags = {}} for fkey, fval in flags:gmatch(";%s?([^=;]+)=?([^;]*)") do fkey = fkey:lower() if fkey == "expires" then fval = date.to_unix(fval:gsub("%-", " ")) end cookie.flags[fkey] = fval end return cookie end function cookie_create(cookie) local cookiedata = {cookie.key .. "=" .. cookie.value} for k, v in pairs(cookie.flags) do if k == "expires" then v = date.to_http(v):gsub(", (%w+) (%w+) (%w+) ", ", %1-%2-%3 ") end cookiedata[#cookiedata+1] = k .. ((#v > 0) and ("=" .. v) or "") end return table.concat(cookiedata, "; ") end
apache-2.0
stephank/luci
applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
90
2019
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface if fs.access(dbdir) then for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface end end end for _, iface in ipairs(sys.net.devices()) do ifaces[iface] = iface end local s = m:section(TypedSection, "vnstat") s.anonymous = true s.addremove = false mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces")) mon_ifaces.template = "cbi/network_ifacelist" mon_ifaces.widget = "checkbox" mon_ifaces.cast = "table" mon_ifaces.noinactive = true mon_ifaces.nocreate = true function mon_ifaces.write(self, section, val) local i local s = { } if val then for _, i in ipairs(type(val) == "table" and val or { val }) do s[i] = true end end for i, _ in pairs(ifaces) do if not s[i] then fs.unlink(dbdir .. "/" .. i) fs.unlink(dbdir .. "/." .. i) end end if next(s) then m.uci:set_list("vnstat", section, "interface", utl.keys(s)) else m.uci:delete("vnstat", section, "interface") end end mon_ifaces.remove = mon_ifaces.write return m
apache-2.0
pins-ocs/OCP-tests
test-CNOC/data/CNOC_Data.lua
1
13507
--[[ /*-----------------------------------------------------------------------*\ | file: CNOC_Data.lua | | | | version: 1.0 date 28/3/2020 | | | | Copyright (C) 2020 | | | | Enrico Bertolazzi, Francesco Biral and Paolo Bosetti | | Dipartimento di Ingegneria Industriale | | Universita` degli Studi di Trento | | Via Sommarive 9, I-38123, Trento, Italy | | email: enrico.bertolazzi@unitn.it | | francesco.biral@unitn.it | | paolo.bosetti@unitn.it | \*-----------------------------------------------------------------------*/ --]] -- Auxiliary values js_min = -50 js_max = 30 jn_max = 65 path_following_tolerance = 1.0e-05 pf_error = path_following_tolerance mesh_segments = 100 v_nom = 0.173 deltaFeed = v_nom content = { -- Level of message InfoLevel = 4, -- maximum number of threads used for linear algebra and various solvers N_threads = 4, U_threaded = true, F_threaded = true, JF_threaded = true, LU_threaded = true, -- Enable doctor Doctor = false, -- Enable check jacobian JacobianCheck = false, JacobianCheckFull = false, JacobianCheck_epsilon = 1e-4, FiniteDifferenceJacobian = false, -- Redirect output to GenericContainer["stream_output"] RedirectStreamToString = false, -- Dump Function and Jacobian if uncommented -- DumpFile = "CNOC_dump", -- spline output (all values as function of "s") -- OutputSplines = [0], -- Redirect output to GenericContainer["stream_output"] RedirectStreamToString = false, ControlSolver = { -- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY", "MINIMIZATION" factorization = "LU", MaxIter = 50, Tolerance = 1e-9, Iterative = false, InfoLevel = -1 -- suppress all messages }, -- setup solver Solver = { -- Linear algebra factorization selection: -- "LU", "QR", "QRP", "SUPERLU" factorization = "LU", -- Last Block selection: -- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY" last_factorization = "LU", -- choose solves: Hyness, NewtonDumped solver = "Hyness", -- solver parameters max_iter = 300, max_step_iter = 40, max_accumulated_iter = 800, tolerance = 9.999999999999999e-10, -- continuation parameters ns_continuation_begin = 0, ns_continuation_end = 0, continuation = { initial_step = 0.2, -- initial step for continuation min_step = 0.001, -- minimum accepted step for continuation reduce_factor = 0.5, -- if continuation step fails, reduce step by this factor augment_factor = 1.5, -- if step successful in less than few_iteration augment step by this factor few_iterations = 8 } }, -- Boundary Conditions (SET/FREE) BoundaryConditions = { initial_n = SET, initial_vs = SET, initial_vn = SET, initial_as = SET, initial_an = SET, final_n = SET, final_vs = SET, final_vn = SET, final_as = SET, final_an = SET, initial_s = SET, final_s = SET, }, -- Guess Guess = { -- possible value: zero, default, none, warm initialize = "zero", -- possible value: default, none, warm, spline, table guess_type = "default" }, Parameters = { -- Model Parameters an_max = 1.2, as_max = 2.1, ax_max = 2.1, ay_max = 2.1, jn_max = jn_max, js_max = js_max, js_min = js_min, deltaFeed = deltaFeed, path_following_tolerance = path_following_tolerance, -- Guess Parameters -- Boundary Conditions an_f = 0, an_i = 0, as_f = 0, as_i = 0, n_f = 0, n_i = 0, vn_f = 0, vn_i = 0, vs_f = 0, vs_i = 0, -- Post Processing Parameters pf_error = pf_error, -- User Function Parameters -- Continuation Parameters -- Constraints Parameters }, -- functions mapped objects MappedObjects = { }, -- Controls -- Penalty type controls: 'QUADRATIC', 'QUADRATIC2', 'PARABOLA', 'CUBIC' -- Barrier type controls: 'LOGARITHMIC', 'COS_LOGARITHMIC', 'TAN2', HYPERBOLIC' Controls = { jsControl = { type = 'LOGARITHMIC', epsilon = 0.01, tolerance = 0.01, }, jnControl = { type = 'LOGARITHMIC', epsilon = 0.01, tolerance = 0.01, }, }, Constraints = { -- Constraint1D -- Penalty subtype: "PENALTY_REGULAR", "PENALTY_SMOOTH", "PENALTY_PIECEWISE" -- Barrier subtype: "BARRIER_LOG", "BARRIER_LOG_EXP", "BARRIER_LOG0" -- PenaltyBarrier1DGreaterThan timePositivesubType = "BARRIER_LOG", timePositiveepsilon = 0.01, timePositivetolerance = 0.01, timePositiveactive = true -- PenaltyBarrier1DGreaterThan vLimitsubType = "PENALTY_PIECEWISE", vLimitepsilon = 0.01, vLimittolerance = 0.01, vLimitactive = true -- PenaltyBarrier1DInterval PathFollowingTolerancesubType = "PENALTY_REGULAR", PathFollowingToleranceepsilon = 0.01, PathFollowingTolerancetolerance = 0.1, PathFollowingTolerancemin = -1, PathFollowingTolerancemax = 1, PathFollowingToleranceactive = true -- PenaltyBarrier1DInterval as_limitsubType = "PENALTY_REGULAR", as_limitepsilon = 0.01, as_limittolerance = 0.01, as_limitmin = -1, as_limitmax = 1, as_limitactive = true -- PenaltyBarrier1DInterval an_limitsubType = "PENALTY_REGULAR", an_limitepsilon = 0.01, an_limittolerance = 0.01, an_limitmin = -1, an_limitmax = 1, an_limitactive = true -- PenaltyBarrier1DInterval ax_limitsubType = "PENALTY_REGULAR", ax_limitepsilon = 0.01, ax_limittolerance = 0.01, ax_limitmin = -1, ax_limitmax = 1, ax_limitactive = true -- PenaltyBarrier1DInterval ay_limitsubType = "PENALTY_REGULAR", ay_limitepsilon = 0.01, ay_limittolerance = 0.01, ay_limitmin = -1, ay_limitmax = 1, ay_limitactive = true -- Constraint2D: none defined }, -- User defined classes initialization -- User defined classes: T O O L P A T H 2 D ToolPath2D = { segments = { { x0 = -0.01, y0 = 0, x1 = 0.02, y1 = 0.002, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.002, x1 = 0.05, y1 = 0, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.05, y0 = 0, x1 = 0.05, y1 = 0.01, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, angle0 = 0, angle1 = 3.1415, }, { x0 = 0.05, y0 = 0.01, x1 = 0.02, y1 = 0.012, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.012, x1 = -0.01, y1 = 0.01, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.01, x1 = -0.01, y1 = 0.02, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.02, x1 = 0.02, y1 = 0.022, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.022, x1 = 0.05, y1 = 0.02, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.05, y0 = 0.02, x1 = 0.05, y1 = 0.03, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, angle0 = 0, angle1 = 3.1415, }, { x0 = 0.05, y0 = 0.03, x1 = 0.02, y1 = 0.032, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.032, x1 = -0.01, y1 = 0.03, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.03, x1 = -0.01, y1 = 0.04, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.04, x1 = 0.02, y1 = 0.042, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.042, x1 = 0.05, y1 = 0.04, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.05, y0 = 0.04, x1 = 0.05, y1 = 0.05, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, angle0 = 0, angle1 = 3.1415, }, { x0 = 0.05, y0 = 0.05, x1 = 0.02, y1 = 0.052, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.052, x1 = -0.01, y1 = 0.05, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.05, x1 = -0.01, y1 = 0.06, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = -0.01, y0 = 0.06, x1 = 0.02, y1 = 0.062, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, { x0 = 0.02, y0 = 0.062, x1 = 0.05, y1 = 0.06, feedRate = v_nom, spindleRate = 3000, crossSection = 1, tolerance = path_following_tolerance, n = mesh_segments, }, }, }, } -- EOF
gpl-2.0
redstormbot/xyiliya
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Daniex0r/project-roleplay-rp
resources/system-policji/s_policedeagle.lua
1
1476
function tazerFired(x, y, z, target) local px, py, pz = getElementPosition(source) local distance = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (distance<20) then if (isElement(target) and getElementType(target)=="player") then for key, value in ipairs(exports.global:getNearbyElements(target, "player", 20)) do if (value~=source) then triggerClientEvent(value, "showTazerEffect", value, x, y, z) -- show the sparks end end exports['antyczit']:changeProtectedElementDataEx(target, "tazed", 1, false) toggleAllControls(target, false, true, false) triggerClientEvent(target, "onClientPlayerWeaponCheck", target) exports.global:applyAnimation(target, "ped", "FLOOR_hit_f", -1, false, false, true) setTimer(removeAnimation, 10005, 1, target) end end end addEvent("tazerFired", true ) addEventHandler("tazerFired", getRootElement(), tazerFired) function removeAnimation(thePlayer) if (isElement(thePlayer) and getElementType(thePlayer)=="player") then exports.global:removeAnimation(thePlayer) toggleAllControls(thePlayer, true, true, true) triggerClientEvent(thePlayer, "onClientPlayerWeaponCheck", thePlayer) end end function updateDeagleMode(mode) if ( tonumber(mode) and (tonumber(mode) >= 0 and tonumber(mode) <= 2) ) then exports['antyczit']:changeProtectedElementDataEx(client, "deaglemode", mode, true) end end addEvent("deaglemode", true) addEventHandler("deaglemode", getRootElement(), updateDeagleMode)
gpl-2.0