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
Sonicrich05/FFXI-Server
scripts/zones/Port_Bastok/npcs/Kurando.lua
38
2161
----------------------------------- -- Area: Port Bastok -- NPC: Kurando -- Type: Quest Giver -- @zone: 236 -- @pos -23.887 3.898 0.870 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,FEAR_OF_FLYING) == QUEST_ACCEPTED) then if (trade:hasItemQty(4526,1) and trade:getItemCount() == 1) then player:startEvent(0x00AB); -- Quest Completion Dialogue end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local FearofFlying = player:getQuestStatus(BASTOK,FEAR_OF_FLYING); -- csid 0x00Ad ? if (FearofFlying == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >=3) then player:startEvent(0x00AA); -- Quest Start Dialogue elseif (FearofFlying == QUEST_COMPLETED) then player:startEvent(0x00AC); -- Dialogue after Completion else player:startEvent(0x001c); -- Default Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00AA) then player:addQuest(BASTOK,FEAR_OF_FLYING); elseif (csid == 0x00AB) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13113); else player:tradeComplete(); player:addItem(13113,1); player:messageSpecial(ITEM_OBTAINED,13113); player:setTitle(AIRSHIP_DENOUNCER); player:completeQuest(BASTOK,FEAR_OF_FLYING); player:addFame(BASTOK,BAS_FAME*30); end end end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Buburimu_Peninsula/npcs/Craigine_RK.lua
4
2909
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Craigine, R.K. -- Border Conquest Guards -- @pos -599.903 -41.441 165.776 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Buburimu_Peninsula/TextIDs"); guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border region = KOLSHUSHU; csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Sea_Serpent_Grotto/npcs/Treasure_Chest.lua
19
3486
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Treasure Chest -- @zone 176 ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1055,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1055,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: L'Ephemere & Map ----------- if (player:hasKeyItem(MAP_OF_THE_SEA_SERPENT_GROTTO) == false) then questItemNeeded = 1; elseif (player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(LEPHEMERE) == false) then questItemNeeded = 2; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(MAP_OF_THE_SEA_SERPENT_GROTTO); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_SEA_SERPENT_GROTTO); -- Map of Sea Serpent Grotto elseif (questItemNeeded == 2) then player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1); player:addKeyItem(LEPHEMERE); player:messageSpecial(KEYITEM_OBTAINED,LEPHEMERE); -- L'Ephemere for A Test Of True Love quest else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1055); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Windurst_Waters/npcs/Kopopo.lua
33
1196
----------------------------------- -- Area: Windurst Waters -- NPC: Kopopo -- Guild Merchant NPC: Cooking Guild -- @pos -103.935 -2.875 74.304 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(530,5,20,7)) then player:showText(npc,KOPOPO_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Northern_San_dOria/npcs/Chasalvige.lua
19
1712
----------------------------------- -- Area: Northern San d'Oria -- NPC: Chasalvige -- Type: Standard Info NPC -- Involved in Mission: The Road Forks -- Involved in Mission: Promathia Mission 5 - Three Paths -- @zone: 231 -- @pos 96.432 -0.520 134.046 -- ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 3) then player:startEvent(0x0026); --COP event elseif (player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("COP_optional_CS_chasalvigne") == 0) then player:startEvent(0x02F9); elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 2) then player:startEvent(0x02FA); else player:startEvent(0x0006); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0026) then player:setVar("EMERALD_WATERS_Status",4); elseif (csid == 0x02F9) then player:setVar("COP_optional_CS_chasalvigne",1); elseif (csid == 0x02FA) then player:setVar("COP_Ulmia_s_Path",3); end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Metalworks/npcs/Fariel.lua
34
2197
----------------------------------- -- Area: Metalworks -- NPC: Fariel -- Type: Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/pathfind"); local path = { 53.551208, -14.000000, -7.162227, 54.111534, -14.000000, -6.227105, 54.075279, -14.000000, -5.139729, 53.565350, -14.000000, 6.000605, 52.636345, -14.000000, 6.521872, 51.561535, -14.000000, 6.710593, 50.436523, -14.000000, 6.835652, 41.754219, -14.000000, 7.686310, 41.409531, -14.000000, 6.635177, 41.351002, -14.000000, 5.549131, 41.341057, -14.000000, 4.461191, 41.338020, -14.000000, -9.138797, 42.356136, -14.000000, -9.449953, 43.442558, -14.000000, -9.409095, 44.524868, -14.000000, -9.298069, 53.718494, -14.000000, -8.260445, 54.082706, -14.000000, -7.257769, 54.110283, -14.000000, -6.170790, 54.073116, -14.000000, -5.083439, 53.556625, -14.000000, 6.192736, 52.545383, -14.000000, 6.570893, 51.441212, -14.000000, 6.730487, 50.430820, -14.000000, 6.836911, 41.680725, -14.000000, 7.693455, 41.396103, -14.000000, 6.599321, 41.349224, -14.000000, 5.512603, 41.340771, -14.000000, 4.424644 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02C2); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
cwarden/mysql-proxy
tests/suite/testenv/fileutils.lua
1
1970
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] require("lfs") module("testenv.fileutils", package.seeall) --- -- check if the file exists and is readable function file_exists(f) local r = lfs.attributes(f) return (r ~= nil) end --- -- check if a path is absolute -- -- FIXME: right now it is Unix only function path_is_absolute(f) return f:byte() == "/" end --- -- get the directory-name of a path -- -- @param filename path to create the directory name from function dirname(filename) local dirname = filename attr = assert(lfs.attributes(dirname)) if attr.mode == "directory" then return dirname end dirname = filename:gsub("/[^/]+$", "") attr = assert(lfs.attributes(dirname)) assert(attr.mode == "directory", "dirname("..filename..") failed: is ".. attr.mode) return dirname end --- -- get the file-name of a path -- -- @param filename path to create the directory name from function basename(filename) name = filename:gsub(".*/", "") return name end --- -- create a empty file -- -- if the file exists, it will be truncated to 0 -- -- @param dst filename to create and truncate function create_empty_file(dst) -- print_verbose("emptying " .. dst) local dst_fd = assert(io.open(dst, "wb+")) dst_fd:close(); end
gpl-2.0
parsaghx/t
plugins/stickermarker.lua
28
2159
local function run(msg, matches) local text = URL.escape(matches[1]) local color = 'blue' if matches[2] == 'red' then color = 'red' elseif matches[2] == 'black' then color = 'black' elseif matches[2] == 'blue' then color = 'blue' elseif matches[2] == 'green' then color = 'green' elseif matches[2] == 'yellow' then color = 'yellow' elseif matches[2] == 'pink' then color = 'magenta' elseif matches[2] == 'orange' then color = 'Orange' elseif matches[2] == 'brown' then color = 'DarkOrange' end local font = 'mathrm' if matches[3] == 'bold' then font = 'mathbf' elseif matches[3] == 'italic' then font = 'mathit' elseif matches[3] == 'fun' then font = 'mathfrak' elseif matches[1] == 'arial' then font = 'mathrm' end local size = '700' if matches[4] == 'small' then size = '300' elseif matches[4] == 'larg' then size = '700' end local url = 'http://latex.codecogs.com/png.latex?'..'\\dpi{'..size..'}%20\\huge%20\\'..font..'{{\\color{'..color..'}'..text..'}}' local file = download_to_file(url,'file.webp') if msg.to.type == 'channel' then send_document('channel#id'..msg.to.id,file,ok_cb,false) else send_document('chat#id'..msg.to.id,file,ok_cb,false) end end return { patterns = { "^[/!#]sticker (.*) ([^%s]+) (.*) (small)$", "^[/!#]sticker (.*) ([^%s]+) (.*) (larg)$", "^[/!#]sticker (.*) ([^%s]+) (bold)$", "^[/!#]sticker (.*) (bold)$", "^[/!#]sticker (.*) ([^%s]+) (italic)$", "^[/!#]sticker (.*) ([^%s]+) (fun)$", "^[/!#]sticker (.*) ([^%s]+) (arial)$", "^[/!#]sticker (.*) (red)$", "[/!#]sticker (.*) (black)$", "^[/!#]sticker (.*) (blue)$", "^[/!#]sticker (.*) (green)$", "^[/!#]sticker (.*) (yellow)$", "^[/!#]sticker (.*) (pink)$", "^[/!#]sticker (.*) (orange)$", "^[/!#]sticker (.*) (brown)$", "^[/!#]sticker +(.*)$", }, run = run }
gpl-2.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/mushroom_salad.lua
2
1292
----------------------------------------- -- ID: 5678 -- Item: mushroom_salad -- Food Effect: 180Min, All Races ----------------------------------------- -- MP 85 -- Agility 6 -- Mind 6 -- Strength -5 -- Vitality -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5678); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 85); target:addMod(MOD_AGI, 6); target:addMod(MOD_MND, 6); target:addMod(MOD_STR, -5); target:addMod(MOD_VIT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 85); target:delMod(MOD_AGI, 6); target:delMod(MOD_MND, 6); target:delMod(MOD_STR, -5); target:delMod(MOD_VIT, -5); end;
gpl-3.0
fruitwasp/DarkRP
entities/entities/spawned_shipment/commands.lua
1
3065
--[[--------------------------------------------------------------------------- Create a shipment from a spawned_weapon ---------------------------------------------------------------------------]] local function createShipment(ply, args) local id = tonumber(args) or -1 local ent = Entity(id) ent = IsValid(ent) and ent or ply:GetEyeTrace().Entity if not IsValid(ent) or not ent.IsSpawnedWeapon or ent.PlayerUse == false then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", "")) return end local pos = ent:GetPos() if pos:DistToSqr(ply:GetShootPos()) > 16900 or not pos:isInSight({ent, ply} , ply) then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("distance_too_big")) return end ent.PlayerUse = false local shipID for k, v in pairs(CustomShipments) do if v.entity == ent:GetWeaponClass() then shipID = k break end end if not shipID or ent.USED then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("unable", "/makeshipment", "")) return end local crate = ents.Create(CustomShipments[shipID].shipmentClass or "spawned_shipment") crate.SID = ply.SID crate:SetPos(ent:GetPos()) crate.nodupe = true crate:SetContents(shipID, ent.dt.amount) crate:Spawn() crate:SetPlayer(ply) crate.clip1 = ent.clip1 crate.clip2 = ent.clip2 crate.ammoadd = ent.ammoadd or 0 SafeRemoveEntity(ent) local phys = crate:GetPhysicsObject() phys:Wake() end DarkRP.defineChatCommand("makeshipment", createShipment, 0.3) --[[--------------------------------------------------------------------------- Split a shipment in two ---------------------------------------------------------------------------]] local function splitShipment(ply, args) local id = tonumber(args) or -1 local ent = Entity(id) ent = IsValid(ent) and ent or ply:GetEyeTrace().Entity if not IsValid(ent) or not ent.IsSpawnedShipment then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", "")) return end if ent:Getcount() < 2 or ent.locked or ent.USED then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("shipment_cannot_split")) return end local pos = ent:GetPos() if pos:DistToSqr(ply:GetShootPos()) > 16900 or not pos:isInSight({ent, ply} , ply) then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("distance_too_big")) return end local count = math.floor(ent:Getcount() / 2) ent:Setcount(ent:Getcount() - count) ent:StartSpawning() local crate = ents.Create("spawned_shipment") crate.locked = true crate.SID = ply.SID crate:SetPos(ent:GetPos()) crate.nodupe = true crate:SetContents(ent:Getcontents(), count) crate:SetPlayer(ply) crate.clip1 = ent.clip1 crate.clip2 = ent.clip2 crate.ammoadd = ent.ammoadd crate:Spawn() local phys = crate:GetPhysicsObject() phys:Wake() end DarkRP.defineChatCommand("splitshipment", splitShipment, 0.3)
mit
Sonicrich05/FFXI-Server
scripts/zones/North_Gustaberg/npcs/Shigezane_IM.lua
28
3150
----------------------------------- -- Area: North Gustaberg -- NPC: Shigezane, I.M. -- Type: Outpost Conquest Guards -- @pos -584.687 39.107 54.281 106 ------------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/North_Gustaberg/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = GUSTABERG; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/globals/items/mercanbaligi.lua
18
1262
----------------------------------------- -- ID: 5454 -- Item: Mercanbaligi -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5454); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -6); end;
gpl-3.0
Servius/tfa-sw-weapons-repository
In Development/servius_development/low_rez_kotor_assets/lua/weapons/holdoutblaster2/shared.lua
1
18059
SWEP.Author = "Velian" SWEP.Contact = "velianhailfrost@gmail.com" --SWEP.Purpose = "What your SWep does." --SWEP.Instructions = "How to operate your SWep" SWEP.PrintName = "Holdout2" SWEP.Spawnable = true -- Whether regular players can see it SWEP.AdminSpawnable = true -- Whether Admins/Super Admins can see it SWEP.Category = "EOTOR Weapons" -- For our use in the game. ;) --This determins how big each clip/magazine for the gun is. You can --set it to -1 to disable the ammo system, meaning primary ammo will --not be displayed and will not be affected. SWEP.Primary.ClipSize = -1 --This sets the number of rounds in the clip when you first get the gun. Again it can be set to -1. SWEP.Primary.DefaultClip = -1 --Obvious. Determines whether the primary fire is automatic. This should be true/false SWEP.Primary.Automatic = false --Sets the ammunition type the gun uses, see below for a list of types. SWEP.Primary.Ammo = "none" SWEP.Base = "weapon_swsft_base" SWEP.Primary.Tracer = "effect_sw_laser_blue" SWEP.Primary.Recoil = 0.5 SWEP.Primary.Damage = 20 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.02 --0.0125 SWEP.Primary.ClipSize = -1 SWEP.Primary.Delay = 0.5 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "pistol" local FireSound = Sound ("combat/sounds.bif_00815.wav"); --local ReloadSound = Sound ("weapons/DC17_reload.wav"); if SERVER then --This makes sure clients download the file AddCSLuaFile ("shared.lua") --How heavy the SWep is SWEP.Weight = 3 --Allow automatic switching to/from this weapon when weapons are picked up SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false elseif CLIENT then SWEP.HoldType = "pistol" SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.UseHands = false SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = "models/weapons/w_pistol.mdl" SWEP.ShowViewModel = true SWEP.ShowWorldModel = true SWEP.ViewModelBoneMods = { ["ValveBiped.square"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }, ["ValveBiped.clip"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }, ["ValveBiped.base"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }, ["ValveBiped.muzzle"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }, ["ValveBiped.hammer"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) } } end function SWEP:Initialize() if CLIENT then self.VElements = { ["blaster"] = { type = "Model", model = "models/weapons/bph_2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(2.596, 1.557, -0.519), angle = Angle(180, 0, 0), size = Vector(0.82, 0.82, 0.82), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } self.WElements = { ["blaster"] = { type = "Model", model = "models/weapons/bph_2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(2.596, 2, -0.519), angle = Angle(176.494, 0, 0), size = Vector(0.82, 0.82, 0.82), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } -- Create a new table for every weapon instance self.VElements = table.FullCopy( self.VElements ) self.WElements = table.FullCopy( self.WElements ) self.ViewModelBoneMods = table.FullCopy( self.ViewModelBoneMods ) self:CreateModels(self.VElements) -- create viewmodels self:CreateModels(self.WElements) -- create worldmodels -- init view model bone build function if IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:ResetBonePositions(vm) -- Init viewmodel visibility if (self.ShowViewModel == nil or self.ShowViewModel) then vm:SetColor(Color(255,255,255,255)) else -- we set the alpha to 1 instead of 0 because else ViewModelDrawn stops being called vm:SetColor(Color(255,255,255,1)) -- ^ stopped working in GMod 13 because you have to do Entity:SetRenderMode(1) for translucency to kick in -- however for some reason the view model resets to render mode 0 every frame so we just apply a debug material to prevent it from drawing vm:SetMaterial("Debug/hsv") end end end end end function SWEP:Holster() if CLIENT and IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:ResetBonePositions(vm) end end return true end function SWEP:PrimaryAttack() -- if self:Clip1() <= 0 then self:NpcReload() -- return end self.Weapon:SetNextSecondaryFire( CurTime() + self.Primary.Delay ) self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay ) --if ( !self:CanPrimaryAttack() ) then return end -- Play shoot sound self.Weapon:EmitSound( FireSound ) -- Shoot the bullet self:CSShootBullet( self.Primary.Damage, self.Primary.Recoil, self.Primary.NumShots, self.Primary.Cone ) -- Remove 1 bullet from our clip --self:TakePrimaryAmmo( 1 ) -- Punch the player's view self.Owner:ViewPunch( Angle( math.Rand(-0.2,-0.1) * self.Primary.Recoil, math.Rand(-0.1,0.1) *self.Primary.Recoil, 0 ) ) -- In singleplayer this function doesn't get called on the client, so we use a networked float -- to send the last shoot time. In multiplayer this is predicted clientside so we don't need to -- send the float. if ( (game.SinglePlayer() && SERVER) || CLIENT ) then self.Weapon:SetNetworkedFloat( "LastShootTime", CurTime() ) end end function SWEP:CSShootBullet( dmg, recoil, numbul, cone ) numbul = numbul or 1 cone = cone or 0.01 local bullet = {} bullet.Num = numbul bullet.Src = self.Owner:GetShootPos() // Source bullet.Dir = self.Owner:GetAimVector() // Dir of bullet bullet.Spread = Vector( cone, cone, 0 ) // Aim Cone bullet.Tracer = 1 // Show a tracer on every x bullets bullet.TracerName = self.Primary.Tracer bullet.Force = 5 // Amount of force to give to phys objects bullet.Damage = dmg self.Owner:FireBullets( bullet ) self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) // View model animation self.Owner:MuzzleFlash() // Crappy muzzle light self.Owner:SetAnimation( PLAYER_ATTACK1 ) // 3rd Person Animation if ( self.Owner:IsNPC() ) then return end // CUSTOM RECOIL ! if ( (game.SinglePlayer() && SERVER) || ( !game.SinglePlayer() && CLIENT && IsFirstTimePredicted() ) ) then local eyeang = self.Owner:EyeAngles() eyeang.pitch = eyeang.pitch - recoil self.Owner:SetEyeAngles( eyeang ) end end -- function SWEP:Deploy() -- self.Owner:DrawViewModel(false) -- end function SWEP:CanPrimaryAttack() return true end function SWEP:SecondaryAttack() end if CLIENT then SWEP.vRenderOrder = nil function SWEP:ViewModelDrawn() local vm = self.Owner:GetViewModel() if !IsValid(vm) then return end if (!self.VElements) then return end self:UpdateBonePositions(vm) if (!self.vRenderOrder) then -- we build a render order because sprites need to be drawn after models self.vRenderOrder = {} for k, v in pairs( self.VElements ) do if (v.type == "Model") then table.insert(self.vRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.vRenderOrder, k) end end end for k, name in ipairs( self.vRenderOrder ) do local v = self.VElements[name] if (!v) then self.vRenderOrder = nil break end if (v.hide) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (!v.bone) then continue end local pos, ang = self:GetBoneOrientation( self.VElements, v, vm ) if (!pos) then continue end if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) //model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end SWEP.wRenderOrder = nil function SWEP:DrawWorldModel() if (self.ShowWorldModel == nil or self.ShowWorldModel) then self:DrawModel() end if (!self.WElements) then return end if (!self.wRenderOrder) then self.wRenderOrder = {} for k, v in pairs( self.WElements ) do if (v.type == "Model") then table.insert(self.wRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.wRenderOrder, k) end end end if (IsValid(self.Owner)) then bone_ent = self.Owner else --when the weapon is dropped bone_ent = self end for k, name in pairs( self.wRenderOrder ) do local v = self.WElements[name] if (!v) then self.wRenderOrder = nil break end if (v.hide) then continue end local pos, ang if (v.bone) then pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent ) else pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent, "ValveBiped.Bip01_R_Hand" ) end if (!pos) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) --model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end function SWEP:GetBoneOrientation( basetab, tab, ent, bone_override ) local bone, pos, ang if (tab.rel and tab.rel != "") then local v = basetab[tab.rel] if (!v) then return end -- Technically, if there exists an element with the same name as a bone -- you can get in an infinite loop. Let's just hope nobody's that stupid. pos, ang = self:GetBoneOrientation( basetab, v, ent ) if (!pos) then return end pos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) else bone = ent:LookupBone(bone_override or tab.bone) if (!bone) then return end pos, ang = Vector(0,0,0), Angle(0,0,0) local m = ent:GetBoneMatrix(bone) if (m) then pos, ang = m:GetTranslation(), m:GetAngles() end if (IsValid(self.Owner) and self.Owner:IsPlayer() and ent == self.Owner:GetViewModel() and self.ViewModelFlip) then ang.r = -ang.r // Fixes mirrored models end end return pos, ang end function SWEP:CreateModels( tab ) if (!tab) then return end -- Create the clientside models here because Garry says we can't do it in the render hook for k, v in pairs( tab ) do if (v.type == "Model" and v.model and v.model != "" and (!IsValid(v.modelEnt) or v.createdModel != v.model) and string.find(v.model, ".mdl") and file.Exists (v.model, "GAME") ) then v.modelEnt = ClientsideModel(v.model, RENDER_GROUP_VIEW_MODEL_OPAQUE) if (IsValid(v.modelEnt)) then v.modelEnt:SetPos(self:GetPos()) v.modelEnt:SetAngles(self:GetAngles()) v.modelEnt:SetParent(self) v.modelEnt:SetNoDraw(true) v.createdModel = v.model else v.modelEnt = nil end elseif (v.type == "Sprite" and v.sprite and v.sprite != "" and (!v.spriteMaterial or v.createdSprite != v.sprite) and file.Exists ("materials/"..v.sprite..".vmt", "GAME")) then local name = v.sprite.."-" local params = { ["$basetexture"] = v.sprite } -- make sure we create a unique name based on the selected options local tocheck = { "nocull", "additive", "vertexalpha", "vertexcolor", "ignorez" } for i, j in pairs( tocheck ) do if (v[j]) then params["$"..j] = 1 name = name.."1" else name = name.."0" end end v.createdSprite = v.sprite v.spriteMaterial = CreateMaterial(name,"UnlitGeneric",params) end end end local allbones local hasGarryFixedBoneScalingYet = false function SWEP:UpdateBonePositions(vm) if self.ViewModelBoneMods then if (!vm:GetBoneCount()) then return end -- !! WORKAROUND !! // -- We need to check all model names :/ local loopthrough = self.ViewModelBoneMods if (!hasGarryFixedBoneScalingYet) then allbones = {} for i=0, vm:GetBoneCount() do local bonename = vm:GetBoneName(i) if (self.ViewModelBoneMods[bonename]) then allbones[bonename] = self.ViewModelBoneMods[bonename] else allbones[bonename] = { scale = Vector(1,1,1), pos = Vector(0,0,0), angle = Angle(0,0,0) } end end loopthrough = allbones end -- !! ----------- !! // for k, v in pairs( loopthrough ) do local bone = vm:LookupBone(k) if (!bone) then continue end // !! WORKAROUND !! // local s = Vector(v.scale.x,v.scale.y,v.scale.z) local p = Vector(v.pos.x,v.pos.y,v.pos.z) local ms = Vector(1,1,1) if (!hasGarryFixedBoneScalingYet) then local cur = vm:GetBoneParent(bone) while(cur >= 0) do local pscale = loopthrough[vm:GetBoneName(cur)].scale ms = ms * pscale cur = vm:GetBoneParent(cur) end end s = s * ms -- !! ----------- !! // if vm:GetManipulateBoneScale(bone) != s then vm:ManipulateBoneScale( bone, s ) end if vm:GetManipulateBoneAngles(bone) != v.angle then vm:ManipulateBoneAngles( bone, v.angle ) end if vm:GetManipulateBonePosition(bone) != p then vm:ManipulateBonePosition( bone, p ) end end else self:ResetBonePositions(vm) end end function SWEP:ResetBonePositions(vm) if (!vm:GetBoneCount()) then return end for i=0, vm:GetBoneCount() do vm:ManipulateBoneScale( i, Vector(1, 1, 1) ) vm:ManipulateBoneAngles( i, Angle(0, 0, 0) ) vm:ManipulateBonePosition( i, Vector(0, 0, 0) ) end end --[[ Global utility code **************************]]-- --Fully copies the table, meaning all tables inside this table are copied too and so on (normal table.Copy copies only their reference). -- Does not copy entities of course, only copies their reference. -- WARNING: do not use on tables that contain themselves somewhere down the line or you'll get an infinite loop function table.FullCopy( tab ) if (!tab) then return nil end local res = {} for k, v in pairs( tab ) do if (type(v) == "table") then res[k] = table.FullCopy(v) // recursion ho! elseif (type(v) == "Vector") then res[k] = Vector(v.x, v.y, v.z) elseif (type(v) == "Angle") then res[k] = Angle(v.p, v.y, v.r) else res[k] = v end end return res end end
apache-2.0
Servius/tfa-sw-weapons-repository
In Development/servius_development/low_rez_kotor_assets/lua/weapons/heavyrepeatingblaster2/shared.lua
1
17589
SWEP.Author = "Velian" SWEP.Contact = "velianhailfrost@gmail.com" --SWEP.Purpose = "What your SWep does." --SWEP.Instructions = "How to operate your SWep" SWEP.PrintName = "HeavyRepeatingBlaster2" SWEP.Spawnable = true -- Whether regular players can see it SWEP.AdminSpawnable = true -- Whether Admins/Super Admins can see it SWEP.Category = "EOTOR Weapons" -- For our use in the game. ;) --This determins how big each clip/magazine for the gun is. You can --set it to -1 to disable the ammo system, meaning primary ammo will --not be displayed and will not be affected. SWEP.Primary.ClipSize = -1 --This sets the number of rounds in the clip when you first get the gun. Again it can be set to -1. SWEP.Primary.DefaultClip = -1 --Obvious. Determines whether the primary fire is automatic. This should be true/false SWEP.Primary.Automatic = true --Sets the ammunition type the gun uses, see below for a list of types. SWEP.Primary.Ammo = "none" SWEP.Base = "weapon_swsft_base" SWEP.Primary.Tracer = "effect_sw_laser_red" SWEP.Primary.Recoil = 0.5 SWEP.Primary.Damage = 20 SWEP.Primary.NumShots = 2 SWEP.Primary.Cone = 0.05 --0.0125 SWEP.Primary.ClipSize = -1 SWEP.Primary.Delay = 0.3 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Ammo = "pistol" local FireSound = Sound ("combat/sounds.bif_00831.wav"); --local ReloadSound = Sound ("weapons/DC17_reload.wav"); SWEP.HoldType = "shotgun" SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.UseHands = false SWEP.ViewModel = "models/weapons/v_shotgun.mdl" SWEP.WorldModel = "models/weapons/w_shotgun.mdl" SWEP.ShowViewModel = false SWEP.ShowWorldModel = false SWEP.ViewModelBoneMods = { ["ValveBiped.Gun"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) } } if SERVER then --This makes sure clients download the file AddCSLuaFile ("shared.lua") --How heavy the SWep is SWEP.Weight = 3 --Allow automatic switching to/from this weapon when weapons are picked up SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false elseif CLIENT then end function SWEP:Initialize() if CLIENT then self.VElements = { ["heavyrepeater"] = { type = "Model", model = "models/weapons/hrb_2.mdl", bone = "ValveBiped.Bip01", rel = "", pos = Vector(-5.715, -23.378, 11.947), angle = Angle(-94.676, 0, -90), size = Vector(1.274, 1.274, 1.274), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } self.WElements = { ["heavyrepeater"] = { type = "Model", model = "models/weapons/hrb_2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(5.714, 2.596, -5.715), angle = Angle(-180, 0, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } -- Create a new table for every weapon instance self.VElements = table.FullCopy( self.VElements ) self.WElements = table.FullCopy( self.WElements ) self.ViewModelBoneMods = table.FullCopy( self.ViewModelBoneMods ) self:CreateModels(self.VElements) -- create viewmodels self:CreateModels(self.WElements) -- create worldmodels -- init view model bone build function if IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:ResetBonePositions(vm) -- Init viewmodel visibility if (self.ShowViewModel == nil or self.ShowViewModel) then vm:SetColor(Color(255,255,255,255)) else -- we set the alpha to 1 instead of 0 because else ViewModelDrawn stops being called vm:SetColor(Color(255,255,255,1)) -- ^ stopped working in GMod 13 because you have to do Entity:SetRenderMode(1) for translucency to kick in -- however for some reason the view model resets to render mode 0 every frame so we just apply a debug material to prevent it from drawing vm:SetMaterial("Debug/hsv") end end end end end function SWEP:Holster() if CLIENT and IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:ResetBonePositions(vm) end end return true end function SWEP:PrimaryAttack() -- if self:Clip1() <= 0 then self:NpcReload() -- return end self.Weapon:SetNextSecondaryFire( CurTime() + self.Primary.Delay ) self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay ) --if ( !self:CanPrimaryAttack() ) then return end -- Play shoot sound self.Weapon:EmitSound( FireSound ) -- Shoot the bullet self:CSShootBullet( self.Primary.Damage, self.Primary.Recoil, self.Primary.NumShots, self.Primary.Cone ) -- Remove 1 bullet from our clip --self:TakePrimaryAmmo( 1 ) -- Punch the player's view self.Owner:ViewPunch( Angle( math.Rand(-0.2,-0.1) * self.Primary.Recoil, math.Rand(-0.1,0.1) *self.Primary.Recoil, 0 ) ) -- In singleplayer this function doesn't get called on the client, so we use a networked float -- to send the last shoot time. In multiplayer this is predicted clientside so we don't need to -- send the float. if ( (game.SinglePlayer() && SERVER) || CLIENT ) then self.Weapon:SetNetworkedFloat( "LastShootTime", CurTime() ) end end function SWEP:CSShootBullet( dmg, recoil, numbul, cone ) numbul = numbul or 1 cone = cone or 0.01 local bullet = {} bullet.Num = numbul bullet.Src = self.Owner:GetShootPos() // Source bullet.Dir = self.Owner:GetAimVector() // Dir of bullet bullet.Spread = Vector( cone, cone, 0 ) // Aim Cone bullet.Tracer = 1 // Show a tracer on every x bullets bullet.TracerName = self.Primary.Tracer bullet.Force = 5 // Amount of force to give to phys objects bullet.Damage = dmg self.Owner:FireBullets( bullet ) --self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) // View model animation self.Owner:MuzzleFlash() // Crappy muzzle light --self.Owner:SetAnimation( PLAYER_ATTACK1 ) // 3rd Person Animation if ( self.Owner:IsNPC() ) then return end // CUSTOM RECOIL ! if ( (game.SinglePlayer() && SERVER) || ( !game.SinglePlayer() && CLIENT && IsFirstTimePredicted() ) ) then local eyeang = self.Owner:EyeAngles() eyeang.pitch = eyeang.pitch - recoil self.Owner:SetEyeAngles( eyeang ) end end -- function SWEP:Deploy() -- self.Owner:DrawViewModel(false) -- end function SWEP:CanPrimaryAttack() return true end function SWEP:SecondaryAttack() end if CLIENT then SWEP.vRenderOrder = nil function SWEP:ViewModelDrawn() local vm = self.Owner:GetViewModel() if !IsValid(vm) then return end if (!self.VElements) then return end self:UpdateBonePositions(vm) if (!self.vRenderOrder) then -- we build a render order because sprites need to be drawn after models self.vRenderOrder = {} for k, v in pairs( self.VElements ) do if (v.type == "Model") then table.insert(self.vRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.vRenderOrder, k) end end end for k, name in ipairs( self.vRenderOrder ) do local v = self.VElements[name] if (!v) then self.vRenderOrder = nil break end if (v.hide) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (!v.bone) then continue end local pos, ang = self:GetBoneOrientation( self.VElements, v, vm ) if (!pos) then continue end if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) //model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end SWEP.wRenderOrder = nil function SWEP:DrawWorldModel() if (self.ShowWorldModel == nil or self.ShowWorldModel) then self:DrawModel() end if (!self.WElements) then return end if (!self.wRenderOrder) then self.wRenderOrder = {} for k, v in pairs( self.WElements ) do if (v.type == "Model") then table.insert(self.wRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.wRenderOrder, k) end end end if (IsValid(self.Owner)) then bone_ent = self.Owner else --when the weapon is dropped bone_ent = self end for k, name in pairs( self.wRenderOrder ) do local v = self.WElements[name] if (!v) then self.wRenderOrder = nil break end if (v.hide) then continue end local pos, ang if (v.bone) then pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent ) else pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent, "ValveBiped.Bip01_R_Hand" ) end if (!pos) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) --model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end function SWEP:GetBoneOrientation( basetab, tab, ent, bone_override ) local bone, pos, ang if (tab.rel and tab.rel != "") then local v = basetab[tab.rel] if (!v) then return end -- Technically, if there exists an element with the same name as a bone -- you can get in an infinite loop. Let's just hope nobody's that stupid. pos, ang = self:GetBoneOrientation( basetab, v, ent ) if (!pos) then return end pos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) else bone = ent:LookupBone(bone_override or tab.bone) if (!bone) then return end pos, ang = Vector(0,0,0), Angle(0,0,0) local m = ent:GetBoneMatrix(bone) if (m) then pos, ang = m:GetTranslation(), m:GetAngles() end if (IsValid(self.Owner) and self.Owner:IsPlayer() and ent == self.Owner:GetViewModel() and self.ViewModelFlip) then ang.r = -ang.r // Fixes mirrored models end end return pos, ang end function SWEP:CreateModels( tab ) if (!tab) then return end -- Create the clientside models here because Garry says we can't do it in the render hook for k, v in pairs( tab ) do if (v.type == "Model" and v.model and v.model != "" and (!IsValid(v.modelEnt) or v.createdModel != v.model) and string.find(v.model, ".mdl") and file.Exists (v.model, "GAME") ) then v.modelEnt = ClientsideModel(v.model, RENDER_GROUP_VIEW_MODEL_OPAQUE) if (IsValid(v.modelEnt)) then v.modelEnt:SetPos(self:GetPos()) v.modelEnt:SetAngles(self:GetAngles()) v.modelEnt:SetParent(self) v.modelEnt:SetNoDraw(true) v.createdModel = v.model else v.modelEnt = nil end elseif (v.type == "Sprite" and v.sprite and v.sprite != "" and (!v.spriteMaterial or v.createdSprite != v.sprite) and file.Exists ("materials/"..v.sprite..".vmt", "GAME")) then local name = v.sprite.."-" local params = { ["$basetexture"] = v.sprite } -- make sure we create a unique name based on the selected options local tocheck = { "nocull", "additive", "vertexalpha", "vertexcolor", "ignorez" } for i, j in pairs( tocheck ) do if (v[j]) then params["$"..j] = 1 name = name.."1" else name = name.."0" end end v.createdSprite = v.sprite v.spriteMaterial = CreateMaterial(name,"UnlitGeneric",params) end end end local allbones local hasGarryFixedBoneScalingYet = false function SWEP:UpdateBonePositions(vm) if self.ViewModelBoneMods then if (!vm:GetBoneCount()) then return end -- !! WORKAROUND !! // -- We need to check all model names :/ local loopthrough = self.ViewModelBoneMods if (!hasGarryFixedBoneScalingYet) then allbones = {} for i=0, vm:GetBoneCount() do local bonename = vm:GetBoneName(i) if (self.ViewModelBoneMods[bonename]) then allbones[bonename] = self.ViewModelBoneMods[bonename] else allbones[bonename] = { scale = Vector(1,1,1), pos = Vector(0,0,0), angle = Angle(0,0,0) } end end loopthrough = allbones end -- !! ----------- !! // for k, v in pairs( loopthrough ) do local bone = vm:LookupBone(k) if (!bone) then continue end // !! WORKAROUND !! // local s = Vector(v.scale.x,v.scale.y,v.scale.z) local p = Vector(v.pos.x,v.pos.y,v.pos.z) local ms = Vector(1,1,1) if (!hasGarryFixedBoneScalingYet) then local cur = vm:GetBoneParent(bone) while(cur >= 0) do local pscale = loopthrough[vm:GetBoneName(cur)].scale ms = ms * pscale cur = vm:GetBoneParent(cur) end end s = s * ms -- !! ----------- !! // if vm:GetManipulateBoneScale(bone) != s then vm:ManipulateBoneScale( bone, s ) end if vm:GetManipulateBoneAngles(bone) != v.angle then vm:ManipulateBoneAngles( bone, v.angle ) end if vm:GetManipulateBonePosition(bone) != p then vm:ManipulateBonePosition( bone, p ) end end else self:ResetBonePositions(vm) end end function SWEP:ResetBonePositions(vm) if (!vm:GetBoneCount()) then return end for i=0, vm:GetBoneCount() do vm:ManipulateBoneScale( i, Vector(1, 1, 1) ) vm:ManipulateBoneAngles( i, Angle(0, 0, 0) ) vm:ManipulateBonePosition( i, Vector(0, 0, 0) ) end end --[[ Global utility code **************************]]-- --Fully copies the table, meaning all tables inside this table are copied too and so on (normal table.Copy copies only their reference). -- Does not copy entities of course, only copies their reference. -- WARNING: do not use on tables that contain themselves somewhere down the line or you'll get an infinite loop function table.FullCopy( tab ) if (!tab) then return nil end local res = {} for k, v in pairs( tab ) do if (type(v) == "table") then res[k] = table.FullCopy(v) // recursion ho! elseif (type(v) == "Vector") then res[k] = Vector(v.x, v.y, v.z) elseif (type(v) == "Angle") then res[k] = Angle(v.p, v.y, v.r) else res[k] = v end end return res end end
apache-2.0
bright-things/ionic-luci
applications/luci-app-adblock/luasrc/model/cbi/adblock.lua
1
2909
-- Copyright 2016 Openwrt.org -- Licensed to the public under the Apache License 2.0. m = Map("adblock", translate("Adblock"), translate("Configuration of the adblock package to block ad/abuse domains by using DNS.")) -- General options s = m:section(NamedSection, "global", "adblock", translate("Global options")) o1 = s:option(Flag, "adb_enabled", translate("Enable adblock")) o1.rmempty = false o1.default = 0 o3 = s:option(Value, "adb_whitelist", translate("Whitelist file"), translate("File with whitelisted hosts/domains that are allowed despite being on a blocklist.")) o3.rmempty = false o3.datatype = "file" fdns = s:option(Flag, "adb_forcedns", translate("Redirect all DNS queries to the local resolver"), translate("When adblock is active, all DNS queries are redirected to the local resolver " .. "in this server by default. You can disable that to allow queries to external DNS servers.")) fdns.rmempty = false fdns.default = fdns.enabled tot = s:option(DummyValue, "adb_overall_count", translate("Total count of blocked domains")) -- Blocklist options bl = m:section(TypedSection, "source", translate("Blocklist sources"), translate("Available blocklist sources (") .. [[<a href="https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md" target="_blank">]] .. translate("see list details") .. [[</a>]] .. translate("). Note that list URLs and Shallalist category selections are not configurable via Luci.")) bl.template = "cbi/tblsection" name = bl:option(Flag, "enabled", translate("Enabled")) name.rmempty = false des = bl:option(DummyValue, "adb_src_desc", translate("Description")) cou = bl:option(DummyValue, "adb_src_count", translate("Count")) upd = bl:option(DummyValue, "adb_src_timestamp", translate("List date/state")) -- Additional options s2 = m:section(NamedSection, "backup", "service", translate("Backup options")) o4 = s2:option(Flag, "enabled", translate("Enable blocklist backup")) o4.rmempty = false o4.default = 0 o5 = s2:option(Value, "adb_dir", translate("Backup directory")) o5.rmempty = false o5.datatype = "directory" -- Extra options e = m:section(NamedSection, "global", "adblock", translate("Extra options"), translate("Options for further tweaking in case the defaults are not suitable for you.")) a1 = e:option(Value, "adb_nullport", translate("Port of the adblock uhttpd instance")) a1.optional = true a1.default = 65535 a1.datatype = "port" a2 = e:option(Value, "adb_nullipv4", translate("IPv4 blackhole ip address")) a2.optional = true a2.default = "192.0.2.1" a2.datatype = "ip4addr" a3 = e:option(Value, "adb_nullipv6", translate("IPv6 blackhole ip address")) a3.optional = true a3.default = "::ffff:c000:0201" a3.datatype = "ip6addr" a7 = e:option(Value, "adb_lanif", translate("Name of the logical lan interface")) a7.optional = true a7.default = "lan" a7.datatype = "network" return m
apache-2.0
projectbismark/luci-bismark
applications/luci-ahcp/luasrc/controller/ahcp.lua
13
1547
--[[ LuCI - Lua Configuration Interface Copyright 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 $Id: init.lua 6731 2011-01-14 19:44:03Z soma $ ]]-- module("luci.controller.ahcp", package.seeall) function index() if not nixio.fs.access("/etc/config/ahcpd") then return end entry({"admin", "network", "ahcpd"}, cbi("ahcp"), _("AHCP Server"), 90).i18n = "ahcp" entry({"admin", "network", "ahcpd", "status"}, call("ahcp_status")) end function ahcp_status() local nfs = require "nixio.fs" local uci = require "luci.model.uci".cursor() local lsd = uci:get_first("ahcpd", "ahcpd", "lease_dir") or "/var/lib/leases" local idf = uci:get_first("ahcpd", "ahcpd", "id_file") or "/var/lib/ahcpd-unique-id" local rv = { uid = "00:00:00:00:00:00:00:00", leases = { } } idf = nfs.readfile(idf) if idf and #idf == 8 then rv.uid = "%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X" %{ idf:byte(1, 8) } end local itr = nfs.dir(lsd) if itr then local addr for addr in itr do if addr:match("^%d+%.%d+%.%d+%.%d+$") then local s = nfs.stat(lsd .. "/" .. addr) rv.leases[#rv.leases+1] = { addr = addr, age = s and (os.time() - s.mtime) or 0 } end end end table.sort(rv.leases, function(a, b) return a.age < b.age end) luci.http.prepare_content("application/json") luci.http.write_json(rv) end
apache-2.0
Sonicrich05/FFXI-Server
scripts/zones/Bhaflau_Thickets/npcs/qm1.lua
16
1188
----------------------------------- -- Area: Bhaflau Thickets -- NPC: ??? (Spawn Lividroot Amooshah(ZNM T2)) -- @pos 334 -10 184 52 ----------------------------------- package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bhaflau_Thickets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2578,1) and trade:getItemCount() == 1) then -- Trade Oily Blood player:tradeComplete(); SpawnMob(16990473,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/globals/mobskills/Bilgestorm.lua
12
1250
--------------------------------------------- -- Bilgestorm -- -- Description: Deals damage in an area of effect. Additional effect: Lowers attack, accuracy, and defense -- Type: Physical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown -- Notes: Only used at low health.*Experienced the use at 75%* --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local power = math.random(20,25); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_ACCURACY_DOWN, power, 0, 60); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_ATTACK_DOWN, power, 0, 60); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, power, 0, 60); local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
mandrav/moai_pex_editor
src/hp/util/MOAIPropUtil.lua
1
11370
-------------------------------------------------------------------------------- -- This is a utility class for MOAIProp.<br> -------------------------------------------------------------------------------- local M = {} -------------------------------------------------------------------------------- -- Sets the position of the left. -- @param prop MOAIProp instance. -- @param left Position of the left. -------------------------------------------------------------------------------- function M.setLeft(prop, left) local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 if prop.getBounds then xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() xMin = math.min(xMin or 0, xMax or 0) end local pivX, pivY, pivZ = prop:getPiv() local locX, locY, locZ = prop:getLoc() prop:setLoc(left + pivX - xMin, locY, locZ) end -------------------------------------------------------------------------------- -- Returns the position of the left. -- @param prop MOAIProp instance. -- @return Position of the left. -------------------------------------------------------------------------------- function M.getLeft(prop) local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 if prop.getBounds then xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() xMin = math.min(xMin or 0, xMax or 0) end local pivX, pivY, pivZ = prop:getPiv() local locX, locY, locZ = prop:getLoc() return locX - pivX + xMin end -------------------------------------------------------------------------------- -- Sets the position of the right. -- @param prop MOAIProp instance. -- @param right Position of the right. -------------------------------------------------------------------------------- function M.setRight(prop, right) local width = M.getWidth(prop) M.setLeft(prop, right - width) end -------------------------------------------------------------------------------- -- Returns the position of the right. -- @param prop MOAIProp instance. -- @return Position of the right. -------------------------------------------------------------------------------- function M.getRight(prop) local left = M.getLeft(prop) local width = M.getWidth(prop) return left + width end -------------------------------------------------------------------------------- -- Sets the position of the top. -- @param prop MOAIProp instance. -- @param top Position of the top. -------------------------------------------------------------------------------- function M.setTop(prop, top) local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 if prop.getBounds then xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() yMin = math.min(yMin or 0, yMax or 0) end local pivX, pivY, pivZ = prop:getPiv() local locX, locY, locZ = prop:getLoc() prop:setLoc(locX, top + pivY - yMin, locZ) end -------------------------------------------------------------------------------- -- Returns the position of the top. -- @param prop MOAIProp instance. -- @return Position of the top. -------------------------------------------------------------------------------- function M.getTop(prop) local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 if prop.getBounds then xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() yMin = math.min(yMin or 0, yMax or 0) end local pivX, pivY, pivZ = prop:getPiv() local locX, locY, locZ = prop:getLoc() return locY - pivY + yMin end -------------------------------------------------------------------------------- -- Sets the position of the bottom. -- @param prop MOAIProp instance. -- @param bottom Position of the bottom. -------------------------------------------------------------------------------- function M.setBottom(prop, bottom) local height = M.getHeight(prop) M.setTop(prop, bottom - height) end -------------------------------------------------------------------------------- -- Returns the position of the bottom. -- @param prop MOAIProp instance. -- @return Position of the bottom. -------------------------------------------------------------------------------- function M.getBottom(prop) local top = M.getTop(prop) local height = M.getHeight(prop) return top + height end -------------------------------------------------------------------------------- -- Sets the position of the left and top. -- @param prop MOAIProp -- @param left Position of the left. -- @param top Position of the top. -------------------------------------------------------------------------------- function M.setPos(prop, left, top) M.setLeft(prop, left) M.setTop(prop, top) end -------------------------------------------------------------------------------- -- Returns the position of the center. -- @param prop MOAIProp instance. -- @return centerX -- @return centerY -------------------------------------------------------------------------------- function M.getCenterPos(prop) local left, top = M.getPos(prop) local w, h = M.getSize(prop) return left + w / 2, top + h / 2 end -------------------------------------------------------------------------------- -- Sets the position of the centeX and centerY. -- @param prop MOAIProp -- @param x Position of the centerX. -- @param y Position of the centerY. -------------------------------------------------------------------------------- function M.setCenterPos(prop, x, y) local w, h = M.getSize(prop) M.setPos(prop, x - w / 2, y - h / 2) end -------------------------------------------------------------------------------- -- Returns the position of the left and top. -- @param prop MOAIProp instance. -- @return Position of the left and top. -------------------------------------------------------------------------------- function M.getPos(prop) return M.getLeft(prop), M.getTop(prop) end -------------------------------------------------------------------------------- -- Returns the width. -- @param prop MOAIProp instance. -- @return width -------------------------------------------------------------------------------- function M.getWidth(prop) local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() return math.abs(xMax - xMin) end -------------------------------------------------------------------------------- -- Returns the height. -- @param prop MOAIProp instance. -- @return height -------------------------------------------------------------------------------- function M.getHeight(prop) local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() return math.abs(yMax - yMin) end -------------------------------------------------------------------------------- -- Returns the width and height. -- @param prop MOAIProp instance. -- @return width -- @return height -------------------------------------------------------------------------------- function M.getSize(prop) local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() return math.abs(xMax - xMin), math.abs(yMax - yMin) end -------------------------------------------------------------------------------- -- Returns the color. -- @param prop MOAIProp instance. -- @return red -- @return green -- @return blue -- @return alpha -------------------------------------------------------------------------------- function M.getColor(prop) local r = prop:getAttr(MOAIColor.ATTR_R_COL) local g = prop:getAttr(MOAIColor.ATTR_G_COL) local b = prop:getAttr(MOAIColor.ATTR_B_COL) local a = prop:getAttr(MOAIColor.ATTR_A_COL) return r, g, b, a end -------------------------------------------------------------------------------- -- Returns the red. -- @param prop MOAIProp instance. -- @return red -------------------------------------------------------------------------------- function M.getRed(prop) local r = prop:getAttr(MOAIColor.ATTR_R_COL) return r end -------------------------------------------------------------------------------- -- Sets the red. -- @param prop MOAIProp instance. -- @param red red value -------------------------------------------------------------------------------- function M.setRed(prop, red) prop:setAttr(MOAIColor.ATTR_R_COL, red) end -------------------------------------------------------------------------------- -- Returns the green. -- @param prop MOAIProp instance. -- @return green -------------------------------------------------------------------------------- function M.getGreen(prop) local g = prop:getAttr(MOAIColor.ATTR_G_COL) return g end -------------------------------------------------------------------------------- -- Sets the green. -- @param prop MOAIProp instance. -- @param green green value -------------------------------------------------------------------------------- function M.setGreen(prop, green) prop:setAttr(MOAIColor.ATTR_G_COL, green) end -------------------------------------------------------------------------------- -- Returns the blue. -- @param prop MOAIProp instance. -- @return blue -------------------------------------------------------------------------------- function M.getBlue(prop) local b = prop:getAttr(MOAIColor.ATTR_B_COL) return b end -------------------------------------------------------------------------------- -- Sets the blue. -- @param prop MOAIProp instance. -- @param blue blue value -------------------------------------------------------------------------------- function M.setBlue(prop, blue) prop:setAttr(MOAIColor.ATTR_B_COL, blue) end -------------------------------------------------------------------------------- -- Returns the alpha. -- @param prop MOAIProp instance. -- @return alpha -------------------------------------------------------------------------------- function M.getAlpha(prop) local a = prop:getAttr(MOAIColor.ATTR_A_COL) return a end -------------------------------------------------------------------------------- -- Sets the alpha. -- @param prop MOAIProp instance. -- @param a alpha value -------------------------------------------------------------------------------- function M.setAlpha(prop, a) prop:setAttr(MOAIColor.ATTR_A_COL, a) end -------------------------------------------------------------------------------- -- Sets the color by RGB255 format. -- @param prop MOAIProp instance. -- @param r Red(0-255). -- @param g Green(0-255). -- @param b Blue(0-255). -------------------------------------------------------------------------------- function M.setRGB(prop, r, g, b) local a = MOAIPropUtil.getAlpha(prop) prop:setColor(r / 255, g / 255, b / 255, a) end -------------------------------------------------------------------------------- -- Sets the color by RGBA255 format. -- @param prop MOAIProp instance. -- @param r Red(0-255). -- @param g Green(0-255). -- @param b Blue(0-255). -- @param a Alpha(0-1). -------------------------------------------------------------------------------- function M.setRGBA(prop, r, g, b, a) a = a or MOAIPropUtil.getAlpha(prop) prop:setColor(r / 255, g / 255, b / 255, a) end -------------------------------------------------------------------------------- -- Returns the visible. -- @param prop MOAIProp instance. -- @return visible -------------------------------------------------------------------------------- function M.getVisible(prop) return prop:getAttr(MOAIProp.ATTR_VISIBLE) end return M
mit
emadni/launcherlordbot
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
Siliconsoul/mirror-askozia-svn
misc/luabash/md5/md5.lua
4
1253
-- --- T2-COPYRIGHT-NOTE-BEGIN --- -- This copyright note is auto-generated by ./scripts/Create-CopyPatch. -- -- T2 SDE: misc/luabash/md5/md5.lua -- Copyright (C) 2006 The T2 SDE Project -- Copyright (C) 2005 Roberto Ierusalimschy -- -- More information can be found in the files COPYING and README. -- -- 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; version 2 of the License. A copy of the -- GNU General Public License can be found in the file COPYING. -- --- T2-COPYRIGHT-NOTE-END --- ---------------------------------------------------------------------------- -- $Id: md5.lua,v 1.4 2006/08/21 19:24:21 carregal Exp $ ---------------------------------------------------------------------------- local core = require"md5.core" local string = require"string" module ("md5") ---------------------------------------------------------------------------- -- @param k String with original message. -- @return String with the md5 hash value converted to hexadecimal digits function sum (k) return (string.gsub(core.dosum(k), ".", function (c) return string.format("%02x", string.byte(c)) end)) end
gpl-2.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/The_Sanctuary_of_ZiTah/npcs/Credaurion_RK.lua
4
2959
----------------------------------- -- Area: The Sanctuary of Zi'Tah -- NPC: Credaurion, R.K. -- Outpost Conquest Guards -- @pos -40.079 -0.642 -148.785 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/conquest"); require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border region = LITELOR; csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Konschtat_Highlands/npcs/Telepoint.lua
2
1563
----------------------------------- -- Area: Konschtat Highlands -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Konschtat_Highlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) item = trade:getItem(); if(trade:getItemCount() == 1 and item > 4095 and item < 4104) then if(player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(DEM_GATE_CRYSTAL) == false) then player:addKeyItem(DEM_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,DEM_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/globals/items/smoked_salmon.lua
35
1196
----------------------------------------- -- ID: 4380 -- Item: smoked_salmon -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4380); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -3); end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/Parike-Poranke.lua
3
1045
----------------------------------- -- Area: Lower Jeuno -- NPC: Parike-Poranke -- Type: Adventurer's Assistant -- @zone: 245 -- @pos: -33.161 -1 -61.303 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x273c); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Northern_San_dOria/npcs/Danngogg.lua
36
1427
----------------------------------- -- Area: Northern San d'Oria -- NPC: Danngogg -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x021c); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Port_Jeuno/npcs/_6u4.lua
17
1390
----------------------------------- -- Area: Port Jeuno -- NPC: Door: Departures Exit (for San D'Oria) -- @zone 246 -- @pos -76 8 54 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x0026); else player:startEvent(0x002e); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0026) then Z = player:getZPos(); if (Z >= 58 and Z <= 61) then player:delGil(200); end end end;
gpl-3.0
correa/domoticz
dzVents/runtime/integration-tests/scScene.lua
19
1493
local log local dz local err = function(msg) log(msg, dz.LOG_ERROR) end local tstMsg = function(msg, res) print('Scene trigger, ' .. msg .. ': ' .. tostring(res and 'OK' or 'FAILED')) end local expectEql = function(attr, test, marker) if (attr ~= test) then local msg = tostring(attr) .. '~=' .. tostring(test) if (marker ~= nil) then msg = msg .. ' (' .. tostring(marker) .. ')' end err(msg) print(debug.traceback()) return false end return true end local testLastUpdate = function(trigger) -- check if trigger.lastUpdate is older than the current time local now = dz.time.secondsSinceMidnight local results = (trigger.lastUpdate.secondsSinceMidnight < now) if (not results) then print('Error: Now: ' .. tostring(now) .. ' lastUpdate: ' .. tostring(trigger.lastUpdate.secondsSinceMidnight) .. ' should be different.') end expectEql(true, results, trigger.name .. '.lastUpdate should be in the past') tstMsg('Test scene lastUpdate', results) return results end return { active = true, on = { scenes = { 'scScene' } }, execute = function(domoticz, scene) local res = true dz = domoticz log = dz.log res = res and testLastUpdate(scene) if (not scene.name == 'sceneSwitch1' or not res) then dz.log('scScene: Test scene event: FAILED', dz.LOG_ERROR) dz.devices('scSceneResults').updateText('FAILED') else dz.log('scScene: Test scene event: OK') dz.devices('scSceneResults').updateText('SCENE SUCCEEDED') end end }
gpl-3.0
Sonicrich05/FFXI-Server
scripts/globals/items/marron_glace.lua
35
1337
----------------------------------------- -- ID: 4502 -- Item: Marron Glace -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic % 13 -- Magic Cap 85 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4502); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 13); target:addMod(MOD_FOOD_MP_CAP, 85); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 13); target:delMod(MOD_FOOD_MP_CAP, 85); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
bright-things/ionic-luci
protocols/luci-proto-3g/luasrc/model/cbi/admin_network/proto_3g.lua
52
4346
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password, dialnumber local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty[A-Z]*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end service = section:taboption("general", Value, "service", translate("Service Type")) service:value("", translate("-- Please choose --")) service:value("umts", "UMTS/GPRS") service:value("umts_only", translate("UMTS only")) service:value("gprs_only", translate("GPRS only")) service:value("evdo", "CDMA/EV-DO") apn = section:taboption("general", Value, "apn", translate("APN")) pincode = section:taboption("general", Value, "pincode", translate("PIN")) username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true dialnumber = section:taboption("general", Value, "dialnumber", translate("Dial number")) dialnumber.placeholder = "*99***1#" if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end maxwait = section:taboption("advanced", Value, "maxwait", translate("Modem init timeout"), translate("Maximum amount of seconds to wait for the modem to become ready")) maxwait.placeholder = "20" maxwait.datatype = "min(1)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger"
apache-2.0
premake/premake-core
modules/vstudio/tests/vc200x/test_platforms.lua
12
1318
-- -- tests/actions/vstudio/vc200x/test_platforms.lua -- Test the Visual Studio 2002-2008 project's Platforms block -- Copyright (c) 2009-2012 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vc200x_platforms") local vc200x = p.vstudio.vc200x -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2008") wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) vc200x.platforms(prj) end -- -- If no architectures are specified, Win32 should be the default. -- function suite.win32Listed_onNoPlatforms() prepare() test.capture [[ <Platforms> <Platform Name="Win32" /> </Platforms> ]] end -- -- If multiple configurations use the same architecture, it should -- still only be listed once. -- function suite.architectureListedOnlyOnce_onMultipleConfigurations() platforms { "Static", "Dynamic" } prepare() test.capture [[ <Platforms> <Platform Name="Win32" /> </Platforms> ]] end -- -- If multiple architectures are used, they should all be listed. -- function suite.allArchitecturesListed_onMultipleArchitectures() platforms { "x86", "x86_64" } prepare() test.capture [[ <Platforms> <Platform Name="Win32" /> <Platform Name="x64" /> </Platforms> ]] end
bsd-3-clause
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/scream_fungus.lua
3
1084
----------------------------------------- -- ID: 4447 -- Item: scream_fungus -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -4 -- Mind 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4447); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -4); target:addMod(MOD_MND, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -4); target:delMod(MOD_MND, 2); end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/spells/noctohelix.lua
2
1474
-------------------------------------- -- Spell: Noctohelix -- Deals dark damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); --calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); --add in target adjustment dmg = adjustForTarget(target,dmg); --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); target:addStatusEffect(EFFECT_HELIX,dmg,3,duration); return dmg; end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Qufim_Island/npcs/Trodden_Snow.lua
19
4780
----------------------------------- -- Area: Qufim Island -- NPC: Trodden Snow -- Mission: ASA - THAT_WHICH_CURDLES_BLOOD -- Mission: ASA - SUGAR_COATED_DIRECTIVE -- @zone 126 -- @pos -19 -17 104 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Qufim_Island/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) -- Trade Enfeebling Kit if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if (asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end if (trade:getItemCount() == 1 and trade:hasItemQty(item,1)) then player:tradeComplete(); player:startEvent(0x002c); end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) --ASA 4 CS: Triggers With At Least 3 Counterseals. if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE) then local completedSeals = 0; if (player:hasKeyItem(AMBER_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(AZURE_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(CERULEAN_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(EMERALD_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(SCARLET_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(VIOLET_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (completedSeals >= 3) then player:setVar("ASA_Status", completedSeals); player:startEvent(0x002d); end; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x002c) then player:addKeyItem(DOMINAS_SCARLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_SCARLET_SEAL); player:addKeyItem(DOMINAS_CERULEAN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_CERULEAN_SEAL); player:addKeyItem(DOMINAS_EMERALD_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_EMERALD_SEAL); player:addKeyItem(DOMINAS_AMBER_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AMBER_SEAL); player:addKeyItem(DOMINAS_VIOLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_VIOLET_SEAL); player:addKeyItem(DOMINAS_AZURE_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AZURE_SEAL); player:completeMission(ASA,THAT_WHICH_CURDLES_BLOOD); player:addMission(ASA,SUGAR_COATED_DIRECTIVE); player:setVar("ASA_Status",0); player:setVar("ASA4_Amber","0"); player:setVar("ASA4_Azure","0"); player:setVar("ASA4_Cerulean","0"); player:setVar("ASA4_Emerald","0"); player:setVar("ASA4_Scarlet","0"); player:setVar("ASA4_Violet","0"); elseif (csid==0x002d) then local completedSeals = player:getVar("ASA_Status"); -- Calculate Reward if (completedSeals == 3) then player:addGil(GIL_RATE*3000); elseif (completedSeals == 4) then player:addGil(GIL_RATE*10000); elseif (completedSeals == 5) then player:addGil(GIL_RATE*30000); elseif (completedSeals == 6) then player:addGil(GIL_RATE*50000); end -- Clean Up Remaining Key Items player:delKeyItem(DOMINAS_SCARLET_SEAL); player:delKeyItem(DOMINAS_CERULEAN_SEAL); player:delKeyItem(DOMINAS_EMERALD_SEAL); player:delKeyItem(DOMINAS_AMBER_SEAL); player:delKeyItem(DOMINAS_VIOLET_SEAL); player:delKeyItem(DOMINAS_AZURE_SEAL); player:delKeyItem(SCARLET_COUNTERSEAL); player:delKeyItem(CERULEAN_COUNTERSEAL); player:delKeyItem(EMERALD_COUNTERSEAL); player:delKeyItem(AMBER_COUNTERSEAL); player:delKeyItem(VIOLET_COUNTERSEAL); player:delKeyItem(AZURE_COUNTERSEAL); -- Advance Mission player:completeMission(ASA,SUGAR_COATED_DIRECTIVE); player:addMission(ASA,ENEMY_OF_THE_EMPIRE_I); player:setVar("ASA_Status",0); end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/The_Eldieme_Necropolis/npcs/_5f4.lua
34
1106
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Titan's Gate -- @pos 180 -34 -15 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; end; -- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
FelixPe/nodemcu-firmware
tests/NTest_file_lfs.lua
4
2629
-- luacheck: globals file -- luacheck: new read globals node.LFS.resource file = require("file_lfs") local Nt = ... Nt = (Nt or require "NTest") -- check standard SPIFFS file functions loadfile("NTest_file.lua")(Nt) local N = Nt("file_lfs") N.test('resource.lua in LFS', function() ok(node.LFS.resource~=nil, "resource.lua embedded in LFS") end) local testfile = "index.html" if node.LFS.resource("index.html") then testfile = "index.html" elseif node.LFS.resource("favicon.ico") then testfile = "favicon.ico" elseif node.LFS.resource("test.txt") then testfile = "test.txt" else error "No 'index.html' nor 'favicon.ico' nor 'text.txt' file stored in LFS resource module. Can't run LFS file tests." end N.test('exist file LFS', function() ok(file.exists(testfile), "existing file") end) N.test('getcontents file LFS', function() local testcontent = node.LFS.resource(testfile) local content = file.getcontents(testfile) ok(eq(testcontent, content),"contents") end) N.test('read more than 1K file LFS', function() local f = file.open(testfile,"r") local size = #node.LFS.resource(testfile) local buffer = f:read() print(#buffer) ok(eq(#buffer < 1024 and size or 1024, 1024), "first block") buffer = f:read() f:close() ok(eq(#buffer, size-1024 > 1024 and 1024 or size-1024), "second block") end) N.test('open existing file LFS', function() file.remove(testfile) local function testopen(mode, position) file.putcontents(testfile, "testcontent") ok(file.open(testfile, mode), mode) file.write("") ok(eq(file.seek(), position), "seek check") file.close() end testopen("r", 0) testopen("w", 0) file.remove(testfile) testopen("a", 11) file.remove(testfile) testopen("r+", 0) file.remove(testfile) testopen("w+", 0) file.remove(testfile) testopen("a+", 11) file.remove(testfile) end) N.test('seek file LFS', function() local testcontent = node.LFS.resource(testfile) local content local f = file.open(testfile) f:seek("set", 0) content = f:read(10) ok(eq(testcontent:sub(1,10), content),"set 0") f:seek("set", 99) content = f:read(10) ok(eq(testcontent:sub(100,109), content),"set 100") f:seek("cur", 10) content = f:read(10) ok(eq(testcontent:sub(120,129), content),"cur 10") f:seek("cur", -50) content = f:read(10) ok(eq(testcontent:sub(80,89), content),"cur -50") f:seek("end", -50) content = f:read(10) ok(eq(testcontent:sub(#testcontent+1-50,#testcontent+1-41), content),"end -50") end) N.test('rename file LFS', function() nok(file.rename(testfile, "testfile"), "cannot rename LFS file") end)
mit
Sonicrich05/FFXI-Server
scripts/zones/Selbina/npcs/Vobo.lua
17
1507
----------------------------------- -- Area: Selbina -- NPC: Vobo -- Involved in Quest: Riding on the Clouds -- @pos 37 -14 81 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 2) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02C6); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ferisystem/TeleTard
plugins/banhammer.lua
214
11956
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end local bots_protection = "Yes" local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = '' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if member_id == our_id then return false end if get_cmd == 'kick' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') return unbanall_user(member_id, chat_id) end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end local receiver = get_receiver(msg) if matches[1]:lower() == 'kickme' then-- /kickme if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return nil end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'ban' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end return end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'kick' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'banall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unbanall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
Sonicrich05/FFXI-Server
scripts/zones/Windurst_Waters/npcs/Ohbiru-Dohbiru.lua
5
9387
----------------------------------- -- Area: Windurst Waters -- NPC: Ohbiru-Dohbiru -- Involved in quest: Food For Thought -- Starts and finishes quest: Toraimarai Turmoil ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); local count = trade:getItemCount(); if (player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_ACCEPTED) then if (trade:hasItemQty(4351,1) and count == 1) then player:startEvent(0x0163,900); end elseif (player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then local OhbiruFood = player:getVar("Ohbiru_Food_var"); if (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood ~= 2) then -- Traded all 3 items & Didn't ask for order rand = math.random(1,2); if (rand == 1) then player:startEvent(0x0145,440); else player:startEvent(0x0146); end elseif (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood == 2) then -- Traded all 3 items after receiving order player:startEvent(0x0142,440); end elseif (turmoil == QUEST_ACCEPTED) then if (count == 3 and trade:getGil() == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(0x0317); else player:startEvent(0x0312,4500,267,906); -- Reminder of needed items end elseif (turmoil == QUEST_COMPLETED) then if (count == 3 and trade:getGil () == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(0x0317); else player:startEvent(0x031b,4500,0,906); -- Reminder of needed items for repeated quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check for Missions first (priority?) -- If the player has started the mission or not local pfame = player:getFameLevel(WINDURST); local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); local FoodForThought = player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT); local needToZone = player:needToZone(); local OhbiruFood = player:getVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought local waterWayToGo = player:getQuestStatus(WINDURST,WATER_WAY_TO_GO); local overnightDelivery = player:getQuestStatus(WINDURST,OVERNIGHT_DELIVERY); if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==2) then player:startEvent(0x0368); elseif (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then if (player:getVar("ohbiru_dohbiru_talk") == 1) then player:startEvent(0x8f); else player:startEvent(0x90); end elseif (waterWayToGo == QUEST_COMPLETED and needToZone) then player:startEvent(0x0164,0,4351); elseif (waterWayToGo == QUEST_ACCEPTED) then if (player:hasItem(504) == false and player:hasItem(4351) == false) then player:startEvent(0x0162); else player:startEvent(0x0161); end elseif (waterWayToGo == QUEST_AVAILABLE and overnightDelivery == QUEST_COMPLETED and pfame >= 3) then player:startEvent(0x0160,0,4351); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 0) then player:startEvent(0x0134); -- Hungry; mentions the experiment. First step in quest for this NPC. player:setVar("Ohbiru_Food_var",1); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 1) then player:startEvent(0x0135); -- Hungry. The NPC complains of being hungry before the quest is active. elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood < 2) then player:startEvent(0x013c,0,4493,624,4408); -- Gives Order player:setVar("Ohbiru_Food_var",2); elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 2) then player:startEvent(0x013d,0,4493,624,4408); -- Repeats Order elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 3) then player:startEvent(0x0144); -- Reminds player to check on friends if he has been given his food. elseif (FoodForThought == QUEST_COMPLETED and needToZone == true) then player:startEvent(0x0158); -- Post Food for Thought Dialogue elseif (overnightDelivery == QUEST_COMPLETED and pfame < 6) then player:startEvent(0x015f); -- Post Overnight Delivery Dialogue -- -- Begin Toraimarai Turmoil Section -- elseif (turmoil == QUEST_AVAILABLE and pfame >= 6 and needToZone == false) then player:startEvent(0x0311,4500,267,906); elseif (turmoil == QUEST_ACCEPTED) then player:startEvent(0x0312,4500,267,906); -- Reminder of needed items elseif (turmoil == QUEST_COMPLETED) then player:startEvent(0x031b,4500,0,906); -- Allows player to initiate repeat of Toraimarai Turmoil else player:startEvent(0x0158); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); -- Check Missions first (priority?) turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); if (csid == 0x8f) then player:setVar("ohbiru_dohbiru_talk",2); elseif (csid == 0x0142 or csid == 0x0145) then if (player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed player:tradeComplete(); player:completeQuest(WINDURST,FOOD_FOR_THOUGHT); player:addTitle(FAST_FOOD_DELIVERER); player:addGil(GIL_RATE*440); player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------ player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------ player:addFame(WINDURST,WIN_FAME*100); player:needToZone(true); else player:tradeComplete(); player:addGil(GIL_RATE*440); player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed. end elseif (csid == 0x0146) then if (player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed player:tradeComplete(); player:completeQuest(WINDURST,FOOD_FOR_THOUGHT); player:addTitle(FAST_FOOD_DELIVERER); player:addGil(GIL_RATE*440); player:messageSpecial(GIL_OBTAINED,GIL_RATE*440); player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------ player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------ player:addFame(WINDURST,WIN_FAME*100); player:needToZone(true); else player:tradeComplete(); player:addGil(GIL_RATE*440); player:messageSpecial(GIL_OBTAINED,GIL_RATE*440); player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed. end elseif (csid == 0x0311 and option == 1) then -- Adds Toraimarai turmoil player:addQuest(WINDURST,TORAIMARAI_TURMOIL); player:messageSpecial(KEYITEM_OBTAINED,267); player:addKeyItem(267); -- Rhinostery Certificate elseif (csid == 0x0317 and turmoil == QUEST_ACCEPTED) then -- Completes Toraimarai turmoil - first time player:addGil(GIL_RATE*4500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500); player:completeQuest(WINDURST,TORAIMARAI_TURMOIL); player:addFame(WINDURST,WIN_FAME*100); player:addTitle(CERTIFIED_RHINOSTERY_VENTURER); player:tradeComplete(); elseif (csid == 0x0317 and turmoil == 2) then -- Completes Toraimarai turmoil - repeats player:addGil(GIL_RATE*4500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500); player:addFame(WINDURST,WIN_FAME*50); player:tradeComplete(); elseif (csid == 0x0160 and option == 0 or csid == 0x0162) then if (player:getFreeSlotsCount() >= 1) then if (player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_AVAILABLE) then player:addQuest(WINDURST,WATER_WAY_TO_GO); end player:addItem(504); player:messageSpecial(ITEM_OBTAINED,504); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,504); end elseif (csid == 0x0163) then player:addGil(GIL_RATE*900); player:completeQuest(WINDURST,WATER_WAY_TO_GO); player:addFame(WINDURST,WIN_FAME*40); player:tradeComplete(); player:needToZone(true); elseif (csid == 0x0368) then player:setVar("MEMORIES_OF_A_MAIDEN_Status",3); end end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Delkfutts_Tower/npcs/_545.lua
2
1534
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Spawns a mob in CoP. Never opens. ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 6 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then SpawnMob(17531121,180):updateEnmity(player); elseif(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 7 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then player:startEvent(0x0019); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if(csid == 0x0019)then player:setVar("COP_Tenzen_s_Path",8); end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Valkurm_Dunes/npcs/Song_Runes.lua
17
1718
----------------------------------- -- Area: Valkurm Dunes -- NPC: Song Runes -- Finishes Quest: Path of the Bard -- @pos -721 -7 102 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(JEUNO,PATH_OF_THE_BARD) == QUEST_AVAILABLE and player:getVar("PathOfTheBard_Event") == 1) then player:startEvent(0x0002); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0002) then player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:addTitle(WANDERING_MINSTREL); player:unlockJob(10); -- Bard player:messageSpecial(UNLOCK_BARD); --You can now become a bard! player:setVar("PathOfTheBard_Event",0); player:addFame(JEUNO,30); player:completeQuest(JEUNO,PATH_OF_THE_BARD); end end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Prerivon.lua
5
1026
----------------------------------- -- Area: Northern San d'Oria -- NPC: Prerivon -- Type: Standard Dialogue NPC -- @zone: 231 -- @pos: 142.324 0.000 132.515 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PRERIVON_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nrodriguez/SpellGainz
libs/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua
65
4515
--[[----------------------------------------------------------------------------- DropdownGroup Container Container controlled by a dropdown on the top. -------------------------------------------------------------------------------]] local Type, Version = "DropdownGroup", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local assert, pairs, type = assert, pairs, type -- WoW APIs local CreateFrame = CreateFrame --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function SelectedGroup(self, event, value) local group = self.parentgroup local status = group.status or group.localstatus status.selected = value self.parentgroup:Fire("OnGroupSelected", value) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self.dropdown:SetText("") self:SetDropdownWidth(200) self:SetTitle("") end, ["OnRelease"] = function(self) self.dropdown.list = nil self.status = nil for k in pairs(self.localstatus) do self.localstatus[k] = nil end end, ["SetTitle"] = function(self, title) self.titletext:SetText(title) self.dropdown.frame:ClearAllPoints() if title and title ~= "" then self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0) else self.dropdown.frame:SetPoint("TOPLEFT", -1, 0) end end, ["SetGroupList"] = function(self,list,order) self.dropdown:SetList(list,order) end, ["SetStatusTable"] = function(self, status) assert(type(status) == "table") self.status = status end, ["SetGroup"] = function(self,group) self.dropdown:SetValue(group) local status = self.status or self.localstatus status.selected = group self:Fire("OnGroupSelected", group) end, ["OnWidthSet"] = function(self, width) local content = self.content local contentwidth = width - 26 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end, ["OnHeightSet"] = function(self, height) local content = self.content local contentheight = height - 63 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end, ["LayoutFinished"] = function(self, width, height) self:SetHeight((height or 0) + 63) end, ["SetDropdownWidth"] = function(self, width) self.dropdown:SetWidth(width) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local PaneBackdrop = { bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 5, bottom = 3 } } local function Constructor() local frame = CreateFrame("Frame") frame:SetHeight(100) frame:SetWidth(100) frame:SetFrameStrata("FULLSCREEN_DIALOG") local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") titletext:SetPoint("TOPLEFT", 4, -5) titletext:SetPoint("TOPRIGHT", -4, -5) titletext:SetJustifyH("LEFT") titletext:SetHeight(18) local dropdown = AceGUI:Create("Dropdown") dropdown.frame:SetParent(frame) dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2) dropdown:SetCallback("OnValueChanged", SelectedGroup) dropdown.frame:SetPoint("TOPLEFT", -1, 0) dropdown.frame:Show() dropdown:SetLabel("") local border = CreateFrame("Frame", nil, frame) border:SetPoint("TOPLEFT", 0, -26) border:SetPoint("BOTTOMRIGHT", 0, 3) border:SetBackdrop(PaneBackdrop) border:SetBackdropColor(0.1,0.1,0.1,0.5) border:SetBackdropBorderColor(0.4,0.4,0.4) --Container Support local content = CreateFrame("Frame", nil, border) content:SetPoint("TOPLEFT", 10, -10) content:SetPoint("BOTTOMRIGHT", -10, 10) local widget = { frame = frame, localstatus = {}, titletext = titletext, dropdown = dropdown, border = border, content = content, type = Type } for method, func in pairs(methods) do widget[method] = func end dropdown.parentgroup = widget return AceGUI:RegisterAsContainer(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
gpl-3.0
ShmooDude/ovale
libs/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua
65
4515
--[[----------------------------------------------------------------------------- DropdownGroup Container Container controlled by a dropdown on the top. -------------------------------------------------------------------------------]] local Type, Version = "DropdownGroup", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local assert, pairs, type = assert, pairs, type -- WoW APIs local CreateFrame = CreateFrame --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function SelectedGroup(self, event, value) local group = self.parentgroup local status = group.status or group.localstatus status.selected = value self.parentgroup:Fire("OnGroupSelected", value) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self.dropdown:SetText("") self:SetDropdownWidth(200) self:SetTitle("") end, ["OnRelease"] = function(self) self.dropdown.list = nil self.status = nil for k in pairs(self.localstatus) do self.localstatus[k] = nil end end, ["SetTitle"] = function(self, title) self.titletext:SetText(title) self.dropdown.frame:ClearAllPoints() if title and title ~= "" then self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0) else self.dropdown.frame:SetPoint("TOPLEFT", -1, 0) end end, ["SetGroupList"] = function(self,list,order) self.dropdown:SetList(list,order) end, ["SetStatusTable"] = function(self, status) assert(type(status) == "table") self.status = status end, ["SetGroup"] = function(self,group) self.dropdown:SetValue(group) local status = self.status or self.localstatus status.selected = group self:Fire("OnGroupSelected", group) end, ["OnWidthSet"] = function(self, width) local content = self.content local contentwidth = width - 26 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end, ["OnHeightSet"] = function(self, height) local content = self.content local contentheight = height - 63 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end, ["LayoutFinished"] = function(self, width, height) self:SetHeight((height or 0) + 63) end, ["SetDropdownWidth"] = function(self, width) self.dropdown:SetWidth(width) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local PaneBackdrop = { bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 5, bottom = 3 } } local function Constructor() local frame = CreateFrame("Frame") frame:SetHeight(100) frame:SetWidth(100) frame:SetFrameStrata("FULLSCREEN_DIALOG") local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") titletext:SetPoint("TOPLEFT", 4, -5) titletext:SetPoint("TOPRIGHT", -4, -5) titletext:SetJustifyH("LEFT") titletext:SetHeight(18) local dropdown = AceGUI:Create("Dropdown") dropdown.frame:SetParent(frame) dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2) dropdown:SetCallback("OnValueChanged", SelectedGroup) dropdown.frame:SetPoint("TOPLEFT", -1, 0) dropdown.frame:Show() dropdown:SetLabel("") local border = CreateFrame("Frame", nil, frame) border:SetPoint("TOPLEFT", 0, -26) border:SetPoint("BOTTOMRIGHT", 0, 3) border:SetBackdrop(PaneBackdrop) border:SetBackdropColor(0.1,0.1,0.1,0.5) border:SetBackdropBorderColor(0.4,0.4,0.4) --Container Support local content = CreateFrame("Frame", nil, border) content:SetPoint("TOPLEFT", 10, -10) content:SetPoint("BOTTOMRIGHT", -10, 10) local widget = { frame = frame, localstatus = {}, titletext = titletext, dropdown = dropdown, border = border, content = content, type = Type } for method, func in pairs(methods) do widget[method] = func end dropdown.parentgroup = widget return AceGUI:RegisterAsContainer(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
gpl-2.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Yuhtunga_Jungle/mobs/Overgrown_Rose.lua
4
1327
----------------------------------- -- Area: Yuhtunga Jungle -- MOB: Overgrown Rose ----------------------------------- function OnMobRoam(mob) local Rose_Garden = 17281357; local Rose_Garden_PH = 0; local Rose_Garden_PH_Table = { 17281356 }; local Rose_Garden_ToD = GetMobByID(Rose_Garden):getExtraVar(1); if (Rose_Garden_ToD <= os.time()) then Rose_Garden_PH = math.random((0), (table.getn(Rose_Garden_PH_Table))); if (Rose_Garden_PH_Table[Rose_Garden_PH] ~= nil) then if (GetMobAction(Rose_Garden) == 0) then SetServerVariable("Rose_Garden_PH", Rose_Garden_PH_Table[Rose_Garden_PH]); DeterMob(Rose_Garden_PH_Table[Rose_Garden_PH], true); DeterMob(Rose_Garden, false); DespawnMob(Rose_Garden_PH_Table[Rose_Garden_PH]); SpawnMob(Rose_Garden, "", 0); end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) local Overgrown_Rose = mob:getID(); local Rose_Garden = 17281357; local Rose_Garden_PH_Table = { 17281356 }; for i = 1, table.getn(Rose_Garden_PH_Table), 1 do if (Rose_Garden_PH_Table[i] ~= nil) then if (Overgrown_Rose == Rose_Garden_PH_Table[i]) then GetMobByID(Rose_Garden):setExtraVar(os.time() + math.random((36000), (37800))); end end end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Southern_San_dOria/npcs/Vemalpeau.lua
17
2519
----------------------------------- -- Area: Southern San d'Oria -- NPC: Vemalpeau -- Involved in Quests: Under Oath ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA,UNDER_OATH) == QUEST_ACCEPTED and player:getVar("UnderOathCS") == 0) then -- Quest: Under Oath - PLD AF3 player:startEvent(0x007); --Under Oath - mentions the boy missing elseif (player:getVar("UnderOathCS") == 3 and player:hasKeyItem(MIQUES_PAINTBRUSH)) then player:startEvent(0x005); --Under Oath - upset about the paintbrush elseif (player:getVar("UnderOathCS") == 4 and player:hasKeyItem(STRANGE_SHEET_OF_PAPER)) then player:startEvent(0x003); -- Under Oath - mentions commanding officer elseif (player:getVar("UnderOathCS") == 9 and player:hasKeyItem(KNIGHTS_CONFESSION)) then player:startEvent(0x002); -- Under Oath - Thanks you and concludes quest else player:startEvent(0x001); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x007) then player:setVar("UnderOathCS", 1) elseif (csid == 0x005) then player:setVar("UnderOathCS", 4) player:delKeyItem(MIQUES_PAINTBRUSH); elseif (csid == 0x002) then player:setVar("UnderOathCS", 0) player:delKeyItem(KNIGHTS_CONFESSION); end end;
gpl-3.0
resistor58/deaths-gmod-server
Mad Cows FoF Weapons/lua/weapons/weapon_mad_fof_coachgun/shared.lua
1
1808
// Variables that are used on both client and server SWEP.Base = "weapon_mad_fof_base" SWEP.ViewModelFOV = 55 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/weapons/v_coachgun.mdl" SWEP.WorldModel = "models/weapons/w_coachgun.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = false SWEP.Primary.Sound = Sound("Weapon_Coachgun.Single") SWEP.Primary.Recoil = 5.5 SWEP.Primary.Damage = 12 SWEP.Primary.NumShots = 8 SWEP.Primary.Cone = 0.04 SWEP.Primary.Delay = 0.25 SWEP.Primary.ClipSize = 2 // Size of a clip SWEP.Primary.DefaultClip = 2 // Default number of bullets in a clip SWEP.Primary.Automatic = false // Automatic/Semi Auto SWEP.Primary.Ammo = "Buckshot" SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none" SWEP.ShellEffect = "none" // "effect_mad_shell_pistol" or "effect_mad_shell_rifle" or "effect_mad_shell_shotgun" SWEP.ShellDelay = 0 SWEP.Pistol = false SWEP.Rifle = false SWEP.Shotgun = true SWEP.Sniper = false SWEP.IronSightsPos = Vector (-5.8205, -0.1201, 4.7958) SWEP.IronSightsAng = Vector (0.1289, -0.0233, 0) SWEP.RunArmOffset = Vector (1.1505, 0, 5.7803) SWEP.RunArmAngle = Vector (-19.6556, 3.7158, 0) SWEP.Penetration = false SWEP.Ricochet = false /*--------------------------------------------------------- Name: SWEP:Precache() Desc: Use this function to precache stuff. ---------------------------------------------------------*/ function SWEP:Precache() util.PrecacheSound("weapons/coachgun/coach_fire1.wav") util.PrecacheSound("weapons/coachgun/coach_fire2.wav") end
gpl-3.0
maxmax1/fooniks
resources/scoreboard/scoreboard_exports.lua
2
3308
local NAMECOLUMNSIZE = .55 local PINGCOLUMNSIZE = .1 resourceColumns = {} isColumn = {name=true,ping=true} scoreboardColumns = { {name="name",size=NAMECOLUMNSIZE}, {name="ping",size=PINGCOLUMNSIZE}, } local rootElement = getRootElement() addEvent("onClientScoreboardLoaded", true) addEvent("onClientVisibilityChange", true) local function sendVisibleColumns(aClient) client = aClient or client local clientColumnData = {} for i, column in ipairs(scoreboardColumns) do local visibleToElement = column.visibleTo if visibleToElement == nil or visibleToElement == rootElement then table.insert(clientColumnData,{column.name,column.size}) else if getElementType(visibleToElement) == "team" and getPlayerTeam(client) == visibleToElement then table.insert(clientColumnData,{column.name,column.size}) else local ancestorElement = client while ancestorElement ~= rootElement do if ancestorElement == visibleToElement then table.insert(clientColumnData,{column.name,column.size}) break end ancestorElement = getElementParent(ancestorElement) end end end end triggerClientEvent(client,"onServerSendColumns",rootElement,clientColumnData) end addEventHandler("onClientScoreboardLoaded",rootElement,sendVisibleColumns) addEventHandler("onClientVisibilityChange",rootElement,sendVisibleColumns) function addScoreboardColumn(name, element, position, size) if name and not isColumn[name] then isColumn[name] = true table.insert(scoreboardColumns,position or #scoreboardColumns,{name=name,visibleTo=element,size=size}) if sourceResource then resourceColumns[sourceResource] = resourceColumns[sourceResource] or {} table.insert ( resourceColumns[sourceResource], name ) end return triggerClientEvent(element or rootElement,"doAddColumn",rootElement,{name,size},position) else return false end end function removeScoreboardColumn(name) if name and isColumn[name] then for i, column in ipairs(scoreboardColumns) do if column.name == name then isColumn[name] = nil table.remove(scoreboardColumns,i) return triggerClientEvent(rootElement,"doRemoveColumn",rootElement,name) end end else return false end end function resetScoreboardColumns() local nameExists, pingExists = false, false for i, column in ipairs(scoreboardColumns) do if column.name == "name" then nameExists = true elseif column.name == "ping" then pingExists = true else isColumn[column.name] = nil table.remove(scoreboardColumns,i) triggerClientEvent(rootElement,"doRemoveColumn",rootElement,column.name) end end if not nameExists then addScoreboardColumn("name", rootElement, 1, NAMECOLUMNSIZE) end if not pingExists then addScoreboardColumn("ping", rootElement, #scoreboardColumns, PINGCOLUMNSIZE) end return true end function setPlayerScoreboardForced(element, state) return triggerClientEvent(element,"doForceScoreboard",rootElement,state) end addEventHandler ( "onResourceStop",rootElement, function(resource) if resourceColumns[resource] then for i,name in ipairs(resourceColumns[resource]) do removeScoreboardColumn(name) end resourceColumns[resource] = nil end end )
gpl-3.0
resistor58/deaths-gmod-server
Mad Cows Weapons/lua/weapons/weapon_mad_dual/shared.lua
1
5954
// Variables that are used on both client and server SWEP.Base = "weapon_mad_base" SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = true SWEP.ViewModel = "models/weapons/v_pist_elite.mdl" SWEP.WorldModel = "models/weapons/w_pist_elite.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = false SWEP.Primary.Sound = Sound("Weapon_Elite.Single") SWEP.Primary.Recoil = 0.5 SWEP.Primary.Damage = 15 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.016 SWEP.Primary.Delay = 0.125 SWEP.Primary.ClipSize = 30 // Size of a clip SWEP.Primary.DefaultClip = 30 // Default number of bullets in a clip SWEP.Primary.Automatic = false // Automatic/Semi Auto SWEP.Primary.Ammo = "Battery" SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none" SWEP.ShellEffect = "effect_mad_shell_pistol" // "effect_mad_shell_pistol" or "effect_mad_shell_rifle" or "effect_mad_shell_shotgun" SWEP.ShellDelay = 0 SWEP.Pistol = true SWEP.Rifle = false SWEP.Shotgun = false SWEP.Sniper = false SWEP.DualRightSeq = 5 SWEP.DualLeftSeq = 2 SWEP.DeployDelay = 1.25 /*--------------------------------------------------------- Name: SWEP:Precache() Desc: Use this function to precache stuff. ---------------------------------------------------------*/ function SWEP:Precache() util.PrecacheSound("weapons/elite/elite-1.wav") end /*--------------------------------------------------------- Name: SWEP:SecondaryAttack() Desc: +attack2 has been pressed. ---------------------------------------------------------*/ function SWEP:SecondaryAttack() end /*--------------------------------------------------------- Name: SWEP:ShootBullet() Desc: A convenience function to shoot bullets. ---------------------------------------------------------*/ SWEP.ShootPos = 0 function SWEP:ShootBullet(damage, recoil, num_bullets, aimcone) num_bullets = num_bullets or 1 aimcone = aimcone or 0 local isright = self.Weapon:GetNetworkedBool("RightGun", false) local attach = self.Owner:GetViewModel():LookupAttachment("1") if (!isright) then if (self.Weapon:Clip1() <= 2) then attach = self.Owner:GetViewModel():LookupAttachment("2") self.Owner:GetViewModel():SetSequence("shoot_leftlast") else attach = self.Owner:GetViewModel():LookupAttachment("2") self.Owner:GetViewModel():SetSequence(self.DualLeftSeq) end else if (self.Weapon:Clip1() < 2) then attach = self.Owner:GetViewModel():LookupAttachment("1") self.Owner:GetViewModel():SetSequence("shoot_rightlast") else attach = self.Owner:GetViewModel():LookupAttachment("1") self.Owner:GetViewModel():SetSequence(self.DualRightSeq) end end if (self.Weapon:Clip1() < 2) then local WeaponModel = self.Weapon:GetOwner():GetActiveWeapon():GetClass() timer.Simple(self.Primary.Delay + 0.1, function() if self.Weapon:GetOwner():GetActiveWeapon():GetClass() == WeaponModel and self.Owner:Alive() then self:Reload() end end) end local shootpos = self.Owner:GetViewModel():GetAttachment(attach).Pos self.ShootPos = attach self.Weapon:SetNetworkedBool("RightGun", !isright) local bullet = {} bullet.Num = num_bullets bullet.Src = self.Owner:GetShootPos() // Source bullet.Dir = self.Owner:GetAimVector() // Dir of bullet bullet.Spread = Vector(aimcone, aimcone, 0) // Aim Cone bullet.Tracer = 1 // Show a tracer on every x bullets bullet.Force = damage * 0.5 // Amount of force to give to phys objects bullet.Damage = damage bullet.Callback = function(attacker, tr, dmginfo) if not self.Owner:IsNPC() and self.Owner:GetNetworkedInt("Fuel") > 0 then self:ShootFire(attacker, tr, dmginfo) end return self:RicochetCallback_Redirect(attacker, tr, dmginfo) end self.Owner:FireBullets(bullet) self.Owner:MuzzleFlash() // Crappy muzzle light self.Owner:SetAnimation(PLAYER_ATTACK1) // 3rd Person Animation local effectdata = EffectData() effectdata:SetOrigin(shootpos) effectdata:SetEntity(self.Weapon) effectdata:SetStart(shootpos) effectdata:SetNormal(self.Owner:GetAimVector()) effectdata:SetAttachment(attach) if (self.Shotgun) then util.Effect("effect_mad_shotgunsmoke", effectdata) else util.Effect("effect_mad_gunsmoke", effectdata) end timer.Simple(self.ShellDelay, function() if not IsFirstTimePredicted() then return end if not self.Owner:IsNPC() and not self.Owner:Alive() then return end local effectdata = EffectData() effectdata:SetEntity(self.Weapon) effectdata:SetNormal(self.Owner:GetAimVector()) effectdata:SetAttachment(attach) util.Effect(self.ShellEffect, effectdata) end) if (not self.Owner:IsNPC()) and ((SinglePlayer() and SERVER) or (not SinglePlayer() and CLIENT)) then local eyeangle = self.Owner:EyeAngles() eyeangle.pitch = eyeangle.pitch - recoil self.Owner:SetEyeAngles(eyeangle) end end /*--------------------------------------------------------- Name: SWEP:GetTracerOrigin() Desc: Allows you to override where the tracer comes from (in first person view) returning anything but a vector indicates that you want the default action. ---------------------------------------------------------*/ local pos function SWEP:GetTracerOrigin() local isright = self.Weapon:GetNetworkedBool("RightGun", true) if (!isright) then pos = self:GetOwner():GetShootPos() + self:GetOwner():EyeAngles():Right() * -5 + self:GetOwner():EyeAngles():Up() * -3.5 else pos = self:GetOwner():GetShootPos() + self:GetOwner():EyeAngles():Right() * 5 + self:GetOwner():EyeAngles():Up() * -3.5 end return pos end
gpl-3.0
oratory/wago.io
backend/api/lua/libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua
52
9726
local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local pairs, assert, type = pairs, assert, type -- WoW APIs local PlaySound = PlaySound local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GameFontNormal ---------------- -- Main Frame -- ---------------- --[[ Events : OnClose ]] do local Type = "Window" local Version = 4 local function frameOnClose(this) this.obj:Fire("OnClose") end local function closeOnClick(this) PlaySound("gsTitleOptionExit") this.obj:Hide() end local function frameOnMouseDown(this) AceGUI:ClearFocus() end local function titleOnMouseDown(this) this:GetParent():StartMoving() AceGUI:ClearFocus() end local function frameOnMouseUp(this) local frame = this:GetParent() frame:StopMovingOrSizing() local self = frame.obj local status = self.status or self.localstatus status.width = frame:GetWidth() status.height = frame:GetHeight() status.top = frame:GetTop() status.left = frame:GetLeft() end local function sizerseOnMouseDown(this) this:GetParent():StartSizing("BOTTOMRIGHT") AceGUI:ClearFocus() end local function sizersOnMouseDown(this) this:GetParent():StartSizing("BOTTOM") AceGUI:ClearFocus() end local function sizereOnMouseDown(this) this:GetParent():StartSizing("RIGHT") AceGUI:ClearFocus() end local function sizerOnMouseUp(this) this:GetParent():StopMovingOrSizing() end local function SetTitle(self,title) self.titletext:SetText(title) end local function SetStatusText(self,text) -- self.statustext:SetText(text) end local function Hide(self) self.frame:Hide() end local function Show(self) self.frame:Show() end local function OnAcquire(self) self.frame:SetParent(UIParent) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") self:ApplyStatus() self:EnableResize(true) self:Show() end local function OnRelease(self) self.status = nil for k in pairs(self.localstatus) do self.localstatus[k] = nil end end -- called to set an external table to store status in local function SetStatusTable(self, status) assert(type(status) == "table") self.status = status self:ApplyStatus() end local function ApplyStatus(self) local status = self.status or self.localstatus local frame = self.frame self:SetWidth(status.width or 700) self:SetHeight(status.height or 500) if status.top and status.left then frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top) frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0) else frame:SetPoint("CENTER",UIParent,"CENTER") end end local function OnWidthSet(self, width) local content = self.content local contentwidth = width - 34 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end local function OnHeightSet(self, height) local content = self.content local contentheight = height - 57 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end local function EnableResize(self, state) local func = state and "Show" or "Hide" self.sizer_se[func](self.sizer_se) self.sizer_s[func](self.sizer_s) self.sizer_e[func](self.sizer_e) end local function Constructor() local frame = CreateFrame("Frame",nil,UIParent) local self = {} self.type = "Window" self.Hide = Hide self.Show = Show self.SetTitle = SetTitle self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.SetStatusText = SetStatusText self.SetStatusTable = SetStatusTable self.ApplyStatus = ApplyStatus self.OnWidthSet = OnWidthSet self.OnHeightSet = OnHeightSet self.EnableResize = EnableResize self.localstatus = {} self.frame = frame frame.obj = self frame:SetWidth(700) frame:SetHeight(500) frame:SetPoint("CENTER",UIParent,"CENTER",0,0) frame:EnableMouse() frame:SetMovable(true) frame:SetResizable(true) frame:SetFrameStrata("FULLSCREEN_DIALOG") frame:SetScript("OnMouseDown", frameOnMouseDown) frame:SetScript("OnHide",frameOnClose) frame:SetMinResize(240,240) frame:SetToplevel(true) local titlebg = frame:CreateTexture(nil, "BACKGROUND") titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]]) titlebg:SetPoint("TOPLEFT", 9, -6) titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24) local dialogbg = frame:CreateTexture(nil, "BACKGROUND") dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]]) dialogbg:SetPoint("TOPLEFT", 8, -24) dialogbg:SetPoint("BOTTOMRIGHT", -6, 8) dialogbg:SetVertexColor(0, 0, 0, .75) local topleft = frame:CreateTexture(nil, "BORDER") topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) topleft:SetWidth(64) topleft:SetHeight(64) topleft:SetPoint("TOPLEFT") topleft:SetTexCoord(0.501953125, 0.625, 0, 1) local topright = frame:CreateTexture(nil, "BORDER") topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) topright:SetWidth(64) topright:SetHeight(64) topright:SetPoint("TOPRIGHT") topright:SetTexCoord(0.625, 0.75, 0, 1) local top = frame:CreateTexture(nil, "BORDER") top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) top:SetHeight(64) top:SetPoint("TOPLEFT", topleft, "TOPRIGHT") top:SetPoint("TOPRIGHT", topright, "TOPLEFT") top:SetTexCoord(0.25, 0.369140625, 0, 1) local bottomleft = frame:CreateTexture(nil, "BORDER") bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottomleft:SetWidth(64) bottomleft:SetHeight(64) bottomleft:SetPoint("BOTTOMLEFT") bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1) local bottomright = frame:CreateTexture(nil, "BORDER") bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottomright:SetWidth(64) bottomright:SetHeight(64) bottomright:SetPoint("BOTTOMRIGHT") bottomright:SetTexCoord(0.875, 1, 0, 1) local bottom = frame:CreateTexture(nil, "BORDER") bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottom:SetHeight(64) bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT") bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT") bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1) local left = frame:CreateTexture(nil, "BORDER") left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) left:SetWidth(64) left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT") left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT") left:SetTexCoord(0.001953125, 0.125, 0, 1) local right = frame:CreateTexture(nil, "BORDER") right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) right:SetWidth(64) right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT") right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT") right:SetTexCoord(0.1171875, 0.2421875, 0, 1) local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", 2, 1) close:SetScript("OnClick", closeOnClick) self.closebutton = close close.obj = self local titletext = frame:CreateFontString(nil, "ARTWORK") titletext:SetFontObject(GameFontNormal) titletext:SetPoint("TOPLEFT", 12, -8) titletext:SetPoint("TOPRIGHT", -32, -8) self.titletext = titletext local title = CreateFrame("Button", nil, frame) title:SetPoint("TOPLEFT", titlebg) title:SetPoint("BOTTOMRIGHT", titlebg) title:EnableMouse() title:SetScript("OnMouseDown",titleOnMouseDown) title:SetScript("OnMouseUp", frameOnMouseUp) self.title = title local sizer_se = CreateFrame("Frame",nil,frame) sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) sizer_se:SetWidth(25) sizer_se:SetHeight(25) sizer_se:EnableMouse() sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown) sizer_se:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_se = sizer_se local line1 = sizer_se:CreateTexture(nil, "BACKGROUND") self.line1 = line1 line1:SetWidth(14) line1:SetHeight(14) line1:SetPoint("BOTTOMRIGHT", -8, 8) line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 14/17 line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local line2 = sizer_se:CreateTexture(nil, "BACKGROUND") self.line2 = line2 line2:SetWidth(8) line2:SetHeight(8) line2:SetPoint("BOTTOMRIGHT", -8, 8) line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 8/17 line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local sizer_s = CreateFrame("Frame",nil,frame) sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0) sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0) sizer_s:SetHeight(25) sizer_s:EnableMouse() sizer_s:SetScript("OnMouseDown",sizersOnMouseDown) sizer_s:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_s = sizer_s local sizer_e = CreateFrame("Frame",nil,frame) sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25) sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0) sizer_e:SetWidth(25) sizer_e:EnableMouse() sizer_e:SetScript("OnMouseDown",sizereOnMouseDown) sizer_e:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_e = sizer_e --Container Support local content = CreateFrame("Frame",nil,frame) self.content = content content.obj = self content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32) content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13) AceGUI:RegisterAsContainer(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
mit
oratory/wago.io
backend/api/lua/libs/AceGUI-3.0-SharedMediaWidgets/Libs/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
30
7163
--[[----------------------------------------------------------------------------- EditBox Widget -------------------------------------------------------------------------------]] local Type, Version = "EditBox", 25 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local tostring, pairs = tostring, pairs -- WoW APIs local PlaySound = PlaySound local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo local CreateFrame, UIParent = CreateFrame, UIParent local _G = _G -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] if not AceGUIEditBoxInsertLink then -- upgradeable hook hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end) end function _G.AceGUIEditBoxInsertLink(text) for i = 1, AceGUI:GetWidgetCount(Type) do local editbox = _G["AceGUI-3.0EditBox"..i] if editbox and editbox:IsVisible() and editbox:HasFocus() then editbox:Insert(text) return true end end end local function ShowButton(self) if not self.disablebutton then self.button:Show() self.editbox:SetTextInsets(0, 20, 3, 3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0, 0, 3, 3) end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Frame_OnShowFocus(frame) frame.obj.editbox:SetFocus() frame:SetScript("OnShow", nil) end local function EditBox_OnEscapePressed(frame) AceGUI:ClearFocus() end local function EditBox_OnEnterPressed(frame) local self = frame.obj local value = frame:GetText() local cancel = self:Fire("OnEnterPressed", value) if not cancel then PlaySound("igMainMenuOptionCheckBoxOn") HideButton(self) end end local function EditBox_OnReceiveDrag(frame) local self = frame.obj local type, id, info = GetCursorInfo() if type == "item" then self:SetText(info) self:Fire("OnEnterPressed", info) ClearCursor() elseif type == "spell" then local name = GetSpellInfo(id, info) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() elseif type == "macro" then local name = GetMacroInfo(id) self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() end HideButton(self) AceGUI:ClearFocus() end local function EditBox_OnTextChanged(frame) local self = frame.obj local value = frame:GetText() if tostring(value) ~= tostring(self.lasttext) then self:Fire("OnTextChanged", value) self.lasttext = value ShowButton(self) end end local function EditBox_OnFocusGained(frame) AceGUI:SetFocus(frame.obj) end local function Button_OnClick(frame) local editbox = frame.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- height is controlled by SetLabel self:SetWidth(200) self:SetDisabled(false) self:SetLabel() self:SetText() self:DisableButton(false) self:SetMaxLetters(0) end, ["OnRelease"] = function(self) self:ClearFocus() end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5,0.5,0.5) self.label:SetTextColor(0.5,0.5,0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1,1,1) self.label:SetTextColor(1,.82,0) end end, ["SetText"] = function(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end, ["GetText"] = function(self, text) return self.editbox:GetText() end, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18) self:SetHeight(44) self.alignoffset = 30 else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0) self:SetHeight(26) self.alignoffset = 12 end end, ["DisableButton"] = function(self, disabled) self.disablebutton = disabled if disabled then HideButton(self) end end, ["SetMaxLetters"] = function (self, num) self.editbox:SetMaxLetters(num or 0) end, ["ClearFocus"] = function(self) self.editbox:ClearFocus() self.frame:SetScript("OnShow", nil) end, ["SetFocus"] = function(self) self.editbox:SetFocus() if not self.frame:IsShown() then self.frame:SetScript("OnShow", Frame_OnShowFocus) end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox"..num, frame, "InputBoxTemplate") editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEnter", Control_OnEnter) editbox:SetScript("OnLeave", Control_OnLeave) editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged", EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained) editbox:SetTextInsets(0, 0, 3, 3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT", 6, 0) editbox:SetPoint("BOTTOMRIGHT") editbox:SetHeight(19) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") label:SetPoint("TOPLEFT", 0, -2) label:SetPoint("TOPRIGHT", 0, -2) label:SetJustifyH("LEFT") label:SetHeight(18) local button = CreateFrame("Button", nil, editbox, "UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT", -2, 0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() local widget = { alignoffset = 30, editbox = editbox, label = label, button = button, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end editbox.obj, button.obj = widget, widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
mahdib9/mahdi
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
mamaddeveloper/mmddev
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
mamadtnt/bot
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
ReccaStudio/ActiveStar
cocos2d/external/lua/luajit/src/src/host/genminilua.lua
73
11943
---------------------------------------------------------------------------- -- Lua script to generate a customized, minified version of Lua. -- The resulting 'minilua' is used for the build process of LuaJIT. ---------------------------------------------------------------------------- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- local sub, match, gsub = string.sub, string.match, string.gsub local LUA_VERSION = "5.1.5" local LUA_SOURCE local function usage() io.stderr:write("Usage: ", arg and arg[0] or "genminilua", " lua-", LUA_VERSION, "-source-dir\n") os.exit(1) end local function find_sources() LUA_SOURCE = arg and arg[1] if not LUA_SOURCE then usage() end if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end local fp = io.open(LUA_SOURCE .. "lua.h") if not fp then LUA_SOURCE = LUA_SOURCE.."src/" fp = io.open(LUA_SOURCE .. "lua.h") if not fp then usage() end end local all = fp:read("*a") fp:close() if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then io.stderr:write("Error: version mismatch\n") usage() end end local LUA_FILES = { "lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c", "lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c", "llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c", "lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c", } local REMOVE_LIB = {} gsub([[ collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset select tostring xpcall foreach foreachi getn maxn setn popen tmpfile seek setvbuf __tostring clock date difftime execute getenv rename setlocale time tmpname dump gfind len reverse LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME ]], "%S+", function(name) REMOVE_LIB[name] = true end) local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, } local CUSTOM_MAIN = [[ typedef unsigned int UB; static UB barg(lua_State *L,int idx){ union{lua_Number n;U64 b;}bn; bn.n=lua_tonumber(L,idx)+6755399441055744.0; if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number"); return(UB)bn.b; } #define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1; static int tobit(lua_State *L){ BRET(barg(L,1))} static int bnot(lua_State *L){ BRET(~barg(L,1))} static int band(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)} static int bor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)} static int bxor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)} static int lshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)} static int rshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)} static int arshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)} static int rol(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))} static int ror(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))} static int bswap(lua_State *L){ UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)} static int tohex(lua_State *L){ UB b=barg(L,1); int n=lua_isnone(L,2)?8:(int)barg(L,2); const char *hexdigits="0123456789abcdef"; char buf[8]; int i; if(n<0){n=-n;hexdigits="0123456789ABCDEF";} if(n>8)n=8; for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;} lua_pushlstring(L,buf,(size_t)n); return 1; } static const struct luaL_Reg bitlib[] = { {"tobit",tobit}, {"bnot",bnot}, {"band",band}, {"bor",bor}, {"bxor",bxor}, {"lshift",lshift}, {"rshift",rshift}, {"arshift",arshift}, {"rol",rol}, {"ror",ror}, {"bswap",bswap}, {"tohex",tohex}, {NULL,NULL} }; int main(int argc, char **argv){ lua_State *L = luaL_newstate(); int i; luaL_openlibs(L); luaL_register(L, "bit", bitlib); if (argc < 2) return sizeof(void *); lua_createtable(L, 0, 1); lua_pushstring(L, argv[1]); lua_rawseti(L, -2, 0); lua_setglobal(L, "arg"); if (luaL_loadfile(L, argv[1])) goto err; for (i = 2; i < argc; i++) lua_pushstring(L, argv[i]); if (lua_pcall(L, argc - 2, 0, 0)) { err: fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); return 1; } lua_close(L); return 0; } ]] local function read_sources() local t = {} for i, name in ipairs(LUA_FILES) do local fp = assert(io.open(LUA_SOURCE..name, "r")) t[i] = fp:read("*a") assert(fp:close()) end t[#t+1] = CUSTOM_MAIN return table.concat(t) end local includes = {} local function merge_includes(src) return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name) if includes[name] then return "" end includes[name] = true local fp = assert(io.open(LUA_SOURCE..name, "r")) local src = fp:read("*a") assert(fp:close()) src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "") src = gsub(src, "#endif%s*$", "") return merge_includes(src) end) end local function get_license(src) return match(src, "/%*+\n%* Copyright %(.-%*/\n") end local function fold_lines(src) return gsub(src, "\\\n", " ") end local strings = {} local function save_str(str) local n = #strings+1 strings[n] = str return "\1"..n.."\2" end local function save_strings(src) src = gsub(src, '"[^"\n]*"', save_str) return gsub(src, "'[^'\n]*'", save_str) end local function restore_strings(src) return gsub(src, "\1(%d+)\2", function(numstr) return strings[tonumber(numstr)] end) end local function def_istrue(def) return def == "INT_MAX > 2147483640L" or def == "LUAI_BITSINT >= 32" or def == "SIZE_Bx < LUAI_BITSINT-1" or def == "cast" or def == "defined(LUA_CORE)" or def == "MINSTRTABSIZE" or def == "LUA_MINBUFFER" or def == "HARDSTACKTESTS" or def == "UNUSED" end local head, defs = {[[ #ifdef _MSC_VER typedef unsigned __int64 U64; #else typedef unsigned long long U64; #endif ]]}, {} local function preprocess(src) local t = { match(src, "^(.-)#") } local lvl, on, oldon = 0, true, {} for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do if pp == "if" or pp == "ifdef" or pp == "ifndef" then lvl = lvl + 1 oldon[lvl] = on on = def_istrue(def) elseif pp == "else" then if oldon[lvl] then if on == false then on = true else on = false end end elseif pp == "elif" then if oldon[lvl] then on = def_istrue(def) end elseif pp == "endif" then on = oldon[lvl] lvl = lvl - 1 elseif on then if pp == "include" then if not head[def] and not REMOVE_EXTINC[def] then head[def] = true head[#head+1] = "#include "..def.."\n" end elseif pp == "define" then local k, sp, v = match(def, "([%w_]+)(%s*)(.*)") if k and not (sp == "" and sub(v, 1, 1) == "(") then defs[k] = gsub(v, "%a[%w_]*", function(tok) return defs[tok] or tok end) else t[#t+1] = "#define "..def.."\n" end elseif pp ~= "undef" then error("unexpected directive: "..pp.." "..def) end end if on then t[#t+1] = txt end end return gsub(table.concat(t), "%a[%w_]*", function(tok) return defs[tok] or tok end) end local function merge_header(src, license) local hdr = string.format([[ /* This is a heavily customized and minimized copy of Lua %s. */ /* It's only used to build LuaJIT. It does NOT have all standard functions! */ ]], LUA_VERSION) return hdr..license..table.concat(head)..src end local function strip_unused1(src) return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func) return REMOVE_LIB[func] and "" or line end) end local function strip_unused2(src) return gsub(src, "Symbolic Execution.-}=", "") end local function strip_unused3(src) src = gsub(src, "extern", "static") src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(") src = gsub(src, "#define lua_assert[^\n]*\n", "") src = gsub(src, "lua_assert%b();?", "") src = gsub(src, "default:\n}", "default:;\n}") src = gsub(src, "lua_lock%b();", "") src = gsub(src, "lua_unlock%b();", "") src = gsub(src, "luai_threadyield%b();", "") src = gsub(src, "luai_userstateopen%b();", "{}") src = gsub(src, "luai_userstate%w+%b();", "") src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser") src = gsub(src, "trydecpoint%(ls,seminfo%)", "luaX_lexerror(ls,\"malformed number\",TK_NUMBER)") src = gsub(src, "int c=luaZ_lookahead%b();", "") src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;", "return 1;") src = gsub(src, "getfuncname%b():", "NULL:") src = gsub(src, "getobjname%b():", "NULL:") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "") src = gsub(src, "(twoto%b()%()", "%1(size_t)") src = gsub(src, "i<sizenode", "i<(int)sizenode") return gsub(src, "\n\n+", "\n") end local function strip_comments(src) return gsub(src, "/%*.-%*/", " ") end local function strip_whitespace(src) src = gsub(src, "^%s+", "") src = gsub(src, "%s*\n%s*", "\n") src = gsub(src, "[ \t]+", " ") src = gsub(src, "(%W) ", "%1") return gsub(src, " (%W)", "%1") end local function rename_tokens1(src) src = gsub(src, "getline", "getline_") src = gsub(src, "struct ([%w_]+)", "ZX%1") return gsub(src, "union ([%w_]+)", "ZY%1") end local function rename_tokens2(src) src = gsub(src, "ZX([%w_]+)", "struct %1") return gsub(src, "ZY([%w_]+)", "union %1") end local function func_gather(src) local nodes, list = {}, {} local pos, len = 1, #src while pos < len do local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos) if d then local n = #list+1 list[n] = d nodes[w] = n else local s d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos) if not d then d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos) if not d then d = match(src, "^[^\n]*\n", pos) end end if s == "{" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) if sub(d, -2) == "{\n" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) end end local k, v = nil, d if w == "typedef" then if match(d, "^typedef enum") then head[#head+1] = d else k = match(d, "([%w_]+);\n$") if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end end elseif w == "enum" then head[#head+1] = v elseif w ~= nil then k = match(d, "^[^\n]-([%w_]+)[(%[=]") if k then if w ~= "static" and k ~= "main" then v = "static "..d end else k = w end end if w and k then local o = nodes[k] if o then nodes["*"..k] = o end local n = #list+1 list[n] = v nodes[k] = n end end pos = pos + #d end return nodes, list end local function func_visit(nodes, list, used, n) local i = nodes[n] for m in string.gmatch(list[i], "[%w_]+") do if nodes[m] then local j = used[m] if not j then used[m] = i func_visit(nodes, list, used, m) elseif i < j then used[m] = i end end end end local function func_collect(src) local nodes, list = func_gather(src) local used = {} func_visit(nodes, list, used, "main") for n,i in pairs(nodes) do local j = used[n] if j and j < i then used["*"..n] = j end end for n,i in pairs(nodes) do if not used[n] then list[i] = "" end end return table.concat(list) end find_sources() local src = read_sources() src = merge_includes(src) local license = get_license(src) src = fold_lines(src) src = strip_unused1(src) src = save_strings(src) src = strip_unused2(src) src = strip_comments(src) src = preprocess(src) src = strip_whitespace(src) src = strip_unused3(src) src = rename_tokens1(src) src = func_collect(src) src = rename_tokens2(src) src = restore_strings(src) src = merge_header(src, license) io.write(src)
gpl-2.0
webwlsong/ABTestingGateway
lib/abtesting/utils/utils.lua
22
1231
local modulename = "abtestingUtils" local _M = {} _M._VERSION = '0.0.1' local cjson = require('cjson.safe') --将doresp和dolog,与handler统一起来。handler将返回一个table,结构为: --[[ handler———errinfo————errcode————code | | | | | |————info | | | |————errdesc | | | |———errstack ]]-- _M.dolog = function(info, desc, data, errstack) local errlog = '' local code, err = info[1], info[2] local errcode = code local errinfo = desc and err..desc or err errlog = errlog .. ' errcode : '..errcode errlog = errlog .. ', errinfo : '..errinfo if data then errlog = errlog .. ', extrainfo : '..data end if errstack then errlog = errlog .. ', errstack : '..errstack end ngx.log(ngx.ERR, errlog) end _M.doresp = function(info, desc, data) local response = {} local code = info[1] local err = info[2] response.errcode = code response.errinfo = desc and err..desc or err if data then response.data = data end return cjson.encode(response) end return _M
mit
gameloses/cocos2dx_lua_skynet_client
src/cocos/cocos2d/DrawPrimitives.lua
98
12024
local dp_initialized = false local dp_shader = nil local dp_colorLocation = -1 local dp_color = { 1.0, 1.0, 1.0, 1.0 } local dp_pointSizeLocation = -1 local dp_pointSize = 1.0 local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor" local targetPlatform = cc.Application:getInstance():getTargetPlatform() local function lazy_init() if not dp_initialized then dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR) --dp_shader:retain() if nil ~= dp_shader then dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color") dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize") dp_Initialized = true end end if nil == dp_shader then print("Error:dp_shader is nil!") return false end return true end local function setDrawProperty() gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION ) dp_shader:use() dp_shader:setUniformsForBuiltins() dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1) end function ccDrawInit() lazy_init() end function ccDrawFree() dp_initialized = false end function ccDrawColor4f(r,g,b,a) dp_color[1] = r dp_color[2] = g dp_color[3] = b dp_color[4] = a end function ccPointSize(pointSize) dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor() end function ccDrawColor4B(r,g,b,a) dp_color[1] = r / 255.0 dp_color[2] = g / 255.0 dp_color[3] = b / 255.0 dp_color[4] = a / 255.0 end function ccDrawPoint(point) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) local vertices = { point.x,point.y} gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.POINTS,0,1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawPoints(points,numOfPoint) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoint do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.POINTS,0,numOfPoint) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawLine(origin,destination) if not lazy_init() then return end local vertexBuffer = {} local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = { origin.x, origin.y, destination.x, destination.y} gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINES ,0,2) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawPoly(points,numOfPoints,closePolygon) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoints do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) if closePolygon then gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints) else gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints) end gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawSolidPoly(points,numOfPoints,color) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoints do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION ) dp_shader:use() dp_shader:setUniformsForBuiltins() dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawRect(origin,destination) ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y)) ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y)) ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y)) ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y)) end function ccDrawSolidRect( origin,destination,color ) local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) } ccDrawSolidPoly(vertices,4,color) end function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY) if not lazy_init() then return end local additionalSegment = 1 if drawLineToCenter then additionalSegment = additionalSegment + 1 end local vertexBuffer = { } local function initBuffer() local coef = 2.0 * math.pi / segments local i = 1 local vertices = {} vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) for i = 1, segments + 1 do local rads = (i - 1) * coef local j = radius * math.cos(rads + angle) * scaleX + center.x local k = radius * math.sin(rads + angle) * scaleY + center.y vertices[i * 2 - 1] = j vertices[i * 2] = k end vertices[(segments + 2) * 2 - 1] = center.x vertices[(segments + 2) * 2] = center.y gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawCircle(center, radius, angle, segments, drawLineToCenter) ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0) end function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() local coef = 2.0 * math.pi / segments local i = 1 local vertices = {} vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) for i = 1, segments + 1 do local rads = (i - 1) * coef local j = radius * math.cos(rads + angle) * scaleX + center.x local k = radius * math.sin(rads + angle) * scaleY + center.y vertices[i * 2 - 1] = j vertices[i * 2] = k end vertices[(segments + 2) * 2 - 1] = center.x vertices[(segments + 2) * 2] = center.y gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawQuadBezier(origin, control, destination, segments) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() local vertices = { } local i = 1 local t = 0.0 for i = 1, segments do vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y t = t + 1.0 / segments end vertices[2 * (segments + 1) - 1] = destination.x vertices[2 * (segments + 1)] = destination.y vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawCubicBezier(origin, control1, control2, destination, segments) if not lazy_init then return end local vertexBuffer = { } local function initBuffer() local vertices = { } local t = 0 local i = 1 for i = 1, segments do vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y t = t + 1.0 / segments end vertices[2 * (segments + 1) - 1] = destination.x vertices[2 * (segments + 1)] = destination.y vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end
mit
focusworld/bbb
plugins/id.lua
50
4275
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] == "ایدی" 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 = { "ایدی: 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 = { "^ایدی$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (member) (@)(.+)", "^!id (members) (name) (.+)" }, run = run }
gpl-2.0
chewi/Aquaria
game_scripts/_mods/aquariaeditortutorial/scripts/node_sit.lua
12
1519
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) node_setCursorActivation(me, true) end function activate(me) local n = getNaija() avatar_fallOffWall() entity_idle(n) entity_setInvincible(n, true) entity_swimToNode(n, me) entity_watchForPath(n) entity_animate(n, "sitBack", LOOP_INF) overrideZoom(0.5, 2) watch(2) emote(EMOTE_NAIJASIGH) while (not isLeftMouse()) and (not isRightMouse()) do watch(FRAME_TIME) end entity_idle(n) entity_addVel(n, 0, -200) overrideZoom(1, 1) esetv(n, EV_NOINPUTNOVEL, 0) watch(1) esetv(n, EV_NOINPUTNOVEL, 1) overrideZoom(0) entity_setInvincible(n, false) end function update(me, dt) end
gpl-2.0
joehanchoi/hammerspoon
extensions/urlevent/init.lua
3
4377
--- === hs.urlevent === --- --- Allows Hammerspoon to respond to URLs --- Hammerspoon is configured to react to URLs that start with `hammerspoon://` when they are opened by OS X. --- This extension allows you to register callbacks for these URL events and their parameters, offering a flexible way to receive events from other applications. --- --- You can also choose to make Hammerspoon the default for `http://` and `https://` URLs, which lets you route the URLs in your Lua code --- --- Given a URL such as `hammerspoon://someEventToHandle?someParam=things&otherParam=stuff`, in the literal, RFC1808 sense of the URL, `someEventToHandle` is the hostname (or net_loc) of the URL, but given that these are not network resources, we consider `someEventToHandle` to be the name of the event. No path should be specified in the URL - it should consist purely of a hostname and, optionally, query parameters. --- --- See also `hs.ipc` for a command line IPC mechanism that is likely more appropriate for shell scripts or command line use. Unlike `hs.ipc`, `hs.urlevent` is not able to return any data to its caller. --- --- NOTE: If Hammerspoon is not running when a `hammerspoon://` URL is opened, Hammerspoon will be launched, but it will not react to the URL event. Nor will it react to any events until this extension is loaded and event callbacks have been bound. --- NOTE: Any event which is received, for which no callback has been bound, will be logged to the Hammerspoon Console --- NOTE: When you trigger a URL from another application, it is usually best to have the URL open in the background, if that option is available. Otherwise, OS X will activate Hammerspoon (i.e. give it focus), which makes URL events difficult to use for things like window management. local urlevent = require "hs.urlevent.internal" local callbacks = {} --- hs.urlevent.httpCallback --- Variable --- A function that should handle http:// and https:// URL events --- --- Notes: --- * The function should handle four arguments: --- * scheme - A string containing the URL scheme (i.e. "http") --- * host - A string containing the host requested (e.g. "www.hammerspoon.org") --- * params - A table containing the key/value pairs of all the URL parameters --- * fullURL - A string containing the full, original URL urlevent.httpCallback = nil -- Set up our top-level callback and register it with the Objective C part of the extension local function urlEventCallback(scheme, event, params, fullURL) if (scheme == "http" or scheme == "https" or scheme == "file") then if not urlevent.httpCallback then hs.showError("Hammerspoon is configured for http(s):// URLs, but no http callback has been set") else local ok, err = xpcall(function() return urlevent.httpCallback(scheme, event, params, fullURL) end, debug.traceback) if not ok then hs.showError(err) end end elseif (scheme == "hammerspoon") then if not callbacks[event] then print("Received hs.urlevent event with no registered callback:"..event) else local ok, err = xpcall(function() return callbacks[event](event, params) end, debug.traceback) if not ok then hs.showError(err) end end else hs.showError(string.format("ERROR: Hammerspoon has been passed a %s URL, but does not know how to handle it", scheme)) end end urlevent.setCallback(urlEventCallback) --- hs.urlevent.bind(eventName, callback) --- Function --- Registers a callback for a hammerspoon:// URL event --- --- Parameters: --- * eventName - A string containing the name of an event --- * callback - A function that will be called when the specified event is received, or nil to remove an existing callback --- --- Returns: --- * None --- --- Notes: --- * The callback function should accept two parameters: --- * eventName - A string containing the name of the event --- * params - A table containing key/value string pairs containing any URL parameters that were specified in the URL --- * Given the URL `hammerspoon://doThingA?value=1` The event name is `doThingA` and the callback's `params` argument will be a table containing `{["value"] = "1"}` function urlevent.bind(eventName, callback) callbacks[eventName] = callback end return urlevent
mit
RyanSquared/lua-http
http/request.lua
1
19056
local lpeg = require "lpeg" local http_patts = require "lpeg_patterns.http" local uri_patts = require "lpeg_patterns.uri" local basexx = require "basexx" local client = require "http.client" local new_headers = require "http.headers".new local http_hsts = require "http.hsts" local http_socks = require "http.socks" local http_proxies = require "http.proxies" local http_util = require "http.util" local http_version = require "http.version" local monotime = require "cqueues".monotime local ce = require "cqueues.errno" local default_user_agent = string.format("%s/%s", http_version.name, http_version.version) local default_hsts_store = http_hsts.new_store() local default_proxies = http_proxies.new():update() local default_h2_settings = { ENABLE_PUSH = false; } local request_methods = { hsts = default_hsts_store; proxies = default_proxies; expect_100_timeout = 1; follow_redirects = true; max_redirects = 5; post301 = false; post302 = false; } local request_mt = { __name = "http.request"; __index = request_methods; } local EOF = lpeg.P(-1) local sts_patt = lpeg.Cf(lpeg.Ct(true) * http_patts.Strict_Transport_Security, rawset) * EOF local uri_patt = uri_patts.uri * EOF local uri_ref = uri_patts.uri_reference * EOF local function new_from_uri(uri_t, headers) if type(uri_t) == "string" then uri_t = assert(uri_patt:match(uri_t), "invalid URI") else assert(type(uri_t) == "table") end local scheme = assert(uri_t.scheme, "URI missing scheme") assert(scheme == "https" or scheme == "http" or scheme == "ws" or scheme == "wss", "scheme not valid") local host = tostring(assert(uri_t.host, "URI must include a host")) -- tostring required to e.g. convert lpeg_patterns IPv6 objects local port = uri_t.port or http_util.scheme_to_port[scheme] local is_connect -- CONNECT requests are a bit special, see http2 spec section 8.3 if headers == nil then headers = new_headers() headers:append(":method", "GET") is_connect = false else is_connect = headers:get(":method") == "CONNECT" end if is_connect then assert(uri_t.path == nil or uri_t.path == "", "CONNECT requests cannot have a path") assert(uri_t.query == nil, "CONNECT requests cannot have a query") assert(headers:has(":authority"), ":authority required for CONNECT requests") else headers:upsert(":authority", http_util.to_authority(host, port, scheme)) local path = uri_t.path if path == nil or path == "" then path = "/" end if uri_t.query then path = path .. "?" .. uri_t.query end headers:upsert(":path", path) headers:upsert(":scheme", scheme) end if uri_t.userinfo then local field if is_connect then field = "proxy-authorization" else field = "authorization" end local userinfo = http_util.decodeURIComponent(uri_t.userinfo) -- XXX: this doesn't seem right, but it's same behaviour as curl headers:upsert(field, "basic " .. basexx.to_base64(userinfo), true) end if not headers:has("user-agent") then headers:append("user-agent", default_user_agent) end return setmetatable({ host = host; port = port; tls = (scheme == "https" or scheme == "wss"); headers = headers; body = nil; }, request_mt) end local function new_connect(uri, connect_authority) local headers = new_headers() headers:append(":authority", connect_authority) headers:append(":method", "CONNECT") return new_from_uri(uri, headers) end function request_methods:clone() return setmetatable({ host = self.host; port = self.port; bind = self.bind; tls = self.tls; ctx = self.ctx; sendname = self.sendname; version = self.version; proxy = self.proxy; headers = self.headers:clone(); body = self.body; hsts = rawget(self, "hsts"); proxies = rawget(self, "proxies"); expect_100_timeout = rawget(self, "expect_100_timeout"); follow_redirects = rawget(self, "follow_redirects"); max_redirects = rawget(self, "max_redirects"); post301 = rawget(self, "post301"); post302 = rawget(self, "post302"); }, request_mt) end function request_methods:to_uri(with_userinfo) local scheme = self.headers:get(":scheme") local method = self.headers:get(":method") local path if scheme == nil then scheme = self.tls and "https" or "http" end local authority local authorization_field if method == "CONNECT" then authorization_field = "proxy-authorization" path = "" else path = self.headers:get(":path") local path_t if method == "OPTIONS" and path == "*" then path = "" else path_t = uri_ref:match(path) assert(path_t, "path not a valid uri reference") end if path_t and path_t.host then -- path was a full URI. This is used for proxied requests. scheme = path_t.scheme or scheme path = path_t.path or "" if path_t.query then path = path .. "?" .. path_t.query end authority = http_util.to_authority(path_t.host, path_t.port, scheme) else authority = self.headers:get(":authority") -- TODO: validate authority can fit in a url end authorization_field = "authorization" end if authority == nil then authority = http_util.to_authority(self.host, self.port, scheme) end if with_userinfo and self.headers:has(authorization_field) then local authorization = self.headers:get(authorization_field) local auth_type, userinfo = authorization:match("^%s*(%S+)%s+(%S+)%s*$") if auth_type and auth_type:lower() == "basic" then userinfo = basexx.from_base64(userinfo) userinfo = http_util.encodeURI(userinfo) authority = userinfo .. "@" .. authority else error("authorization cannot be converted to uri") end end return scheme .. "://" .. authority .. path end function request_methods:handle_redirect(orig_headers) local max_redirects = self.max_redirects if max_redirects <= 0 then return nil, "maximum redirects exceeded", ce.ELOOP end local location = orig_headers:get("location") if not location then return nil, "missing location header for redirect", ce.EINVAL end local uri_t = uri_ref:match(location) if not uri_t then return nil, "invalid URI in location header", ce.EINVAL end local new_req = self:clone() new_req.max_redirects = max_redirects - 1 local method = new_req.headers:get(":method") local is_connect = method == "CONNECT" local new_scheme = uri_t.scheme if new_scheme then if not is_connect then new_req.headers:upsert(":scheme", new_scheme) end if new_scheme == "https" or new_scheme == "wss" then new_req.tls = true elseif new_scheme == "http" or new_scheme == "ws" then new_req.tls = false else return nil, "unknown scheme", ce.EINVAL end else if not is_connect then new_scheme = new_req.headers:get(":scheme") end if new_scheme == nil then new_scheme = self.tls and "https" or "http" end end local orig_target local target_authority if not is_connect then orig_target = self.headers:get(":path") orig_target = uri_ref:match(orig_target) if orig_target and orig_target.host then -- was originally a proxied request local new_authority if uri_t.host then -- we have a new host new_authority = http_util.to_authority(uri_t.host, uri_t.port, new_scheme) new_req.headers:upsert(":authority", new_authority) else new_authority = self.headers:get(":authority") end if new_authority == nil then new_authority = http_util.to_authority(self.host, self.port, new_scheme) end -- prefix for new target target_authority = new_scheme .. "://" .. new_authority end end if target_authority == nil and uri_t.host then -- we have a new host and it wasn't placed into :authority new_req.host = uri_t.host if not is_connect then new_req.headers:upsert(":authority", http_util.to_authority(uri_t.host, uri_t.port, new_scheme)) end new_req.port = uri_t.port or http_util.scheme_to_port[new_scheme] new_req.sendname = nil end -- otherwise same host as original request; don't need change anything if is_connect then if uri_t.path ~= nil and uri_t.path ~= "" then return nil, "CONNECT requests cannot have a path", ce.EINVAL elseif uri_t.query ~= nil then return nil, "CONNECT requests cannot have a query", ce.EINVAL end else local new_path if uri_t.path == nil or uri_t.path == "" then new_path = "/" else new_path = uri_t.path if new_path:sub(1, 1) ~= "/" then -- relative path if not orig_target then return nil, "base path not valid for relative redirect", ce.EINVAL end local orig_path = orig_target.path or "/" new_path = http_util.resolve_relative_path(orig_path, new_path) end end if uri_t.query then new_path = new_path .. "?" .. uri_t.query end if target_authority then new_path = target_authority .. new_path end new_req.headers:upsert(":path", new_path) end if uri_t.userinfo then local field if is_connect then field = "proxy-authorization" else field = "authorization" end new_req.headers:upsert(field, "basic " .. basexx.to_base64(uri_t.userinfo), true) end if not new_req.tls and self.tls then --[[ RFC 7231 5.5.2: A user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring page was received with a secure protocol.]] new_req.headers:delete("referer") else new_req.headers:upsert("referer", self:to_uri(false)) end -- Change POST requests to a body-less GET on redirect? local orig_status = orig_headers:get(":status") if (orig_status == "303" or (orig_status == "301" and not self.post301) or (orig_status == "302" and not self.post302) ) and method == "POST" then new_req.headers:upsert(":method", "GET") -- Remove headers that don't make sense without a body -- Headers that require a body new_req.headers:delete("transfer-encoding") new_req.headers:delete("content-length") -- Representation Metadata from RFC 7231 Section 3.1 new_req.headers:delete("content-encoding") new_req.headers:delete("content-language") new_req.headers:delete("content-location") new_req.headers:delete("content-type") -- Other... local expect = new_req.headers:get("expect") if expect and expect:lower() == "100-continue" then new_req.headers:delete("expect") end new_req.body = nil end return new_req end function request_methods:set_body(body) self.body = body local length if type(self.body) == "string" then length = #body end if length then self.headers:upsert("content-length", string.format("%d", #body)) end if not length or length > 1024 then self.headers:append("expect", "100-continue") end return true end local function non_final_status(status) return status:sub(1, 1) == "1" and status ~= "101" end function request_methods:go(timeout) local deadline = timeout and (monotime()+timeout) local cloned_headers = false -- only clone headers when we need to local request_headers = self.headers local host = self.host local port = self.port local tls = self.tls -- RFC 6797 Section 8.3 if not tls and self.hsts and self.hsts:check(host) then tls = true if request_headers:get(":scheme") == "http" then -- The UA MUST replace the URI scheme with "https" if not cloned_headers then request_headers = request_headers:clone() cloned_headers = true end request_headers:upsert(":scheme", "https") end -- if the URI contains an explicit port component of "80", then -- the UA MUST convert the port component to be "443", or -- if the URI contains an explicit port component that is not -- equal to "80", the port component value MUST be preserved if port == 80 then port = 443 end end local connection local proxy = self.proxy if proxy == nil and self.proxies then assert(getmetatable(self.proxies) == http_proxies.mt, "proxies property should be an http.proxies object") local scheme = tls and "https" or "http" -- rather than :scheme proxy = self.proxies:choose(scheme, host) end if proxy then if type(proxy) == "string" then proxy = assert(uri_patt:match(proxy), "invalid proxy URI") else assert(type(proxy) == "table" and getmetatable(proxy) == nil and proxy.scheme, "invalid proxy URI") end if proxy.scheme == "http" or proxy.scheme == "https" then if tls then -- Proxy via a CONNECT request local authority = http_util.to_authority(host, port, nil) local connect_request = new_connect(proxy, authority) connect_request.proxy = false connect_request.version = 1.1 -- TODO: CONNECT over HTTP/2 if tls then if connect_request.tls then error("NYI: TLS over TLS") end end -- Perform CONNECT request local headers, stream, errno = connect_request:go(deadline and deadline-monotime()) if not headers then return nil, stream, errno end -- RFC 7231 Section 4.3.6: -- Any 2xx (Successful) response indicates that the sender (and all -- inbound proxies) will switch to tunnel mode local status_reply = headers:get(":status") if status_reply:sub(1, 1) ~= "2" then stream:shutdown() return nil, ce.strerror(ce.ECONNREFUSED), ce.ECONNREFUSED end local sock = stream.connection:take_socket() local err, errno2 connection, err, errno2 = client.negotiate(sock, { tls = tls; ctx = self.ctx; sendname = self.sendname ~= nil and self.sendname or host; version = self.version; h2_settings = default_h2_settings; }, deadline and deadline-monotime()) if connection == nil then sock:close() return nil, err, errno2 end else if request_headers:get(":method") == "CONNECT" then error("cannot use HTTP Proxy with CONNECT method") end if proxy.path ~= nil and proxy.path ~= "" then error("an HTTP proxy cannot have a path component") end -- TODO: Check if :path already has authority? local old_url = self:to_uri(false) host = assert(proxy.host, "proxy is missing host") port = proxy.port or http_util.scheme_to_port[proxy.scheme] -- proxy requests get a uri that includes host as their path if not cloned_headers then request_headers = request_headers:clone() cloned_headers = true -- luacheck: ignore 311 end request_headers:upsert(":path", old_url) if proxy.userinfo then request_headers:upsert("proxy-authorization", "basic " .. basexx.to_base64(proxy.userinfo), true) end end elseif proxy.scheme:match "^socks" then local socks = http_socks.connect(proxy) local ok, err, errno = socks:negotiate(host, port, deadline and deadline-monotime()) if not ok then return nil, err, errno end local sock = socks:take_socket() connection, err, errno = client.negotiate(sock, { tls = tls; ctx = self.ctx; sendname = self.sendname ~= nil and self.sendname or host; version = self.version; h2_settings = default_h2_settings; }, deadline and deadline-monotime()) if connection == nil then sock:close() return nil, err, errno end else error(string.format("unsupported proxy type (%s)", proxy.scheme)) end end if not connection then local err, errno connection, err, errno = client.connect({ host = host; port = port; bind = self.bind; tls = tls; ctx = self.ctx; sendname = self.sendname; version = self.version; h2_settings = default_h2_settings; }, deadline and deadline-monotime()) if connection == nil then return nil, err, errno end -- Close the connection (and free resources) when done connection:onidle(connection.close) end local stream do local err, errno stream, err, errno = connection:new_stream() if stream == nil then return nil, err, errno end end local body = self.body do -- Write outgoing headers local ok, err, errno = stream:write_headers(request_headers, body == nil, deadline and deadline-monotime()) if not ok then stream:shutdown() return nil, err, errno end end local headers if body then local expect = request_headers:get("expect") if expect and expect:lower() == "100-continue" then -- Try to wait for 100-continue before proceeding if deadline then local err, errno headers, err, errno = stream:get_headers(math.min(self.expect_100_timeout, deadline-monotime())) if headers == nil and (errno ~= ce.ETIMEDOUT or monotime() > deadline) then stream:shutdown() if err == nil then return nil, ce.strerror(ce.EPIPE), ce.EPIPE end return nil, err, errno end else local err, errno headers, err, errno = stream:get_headers(self.expect_100_timeout) if headers == nil and errno ~= ce.ETIMEDOUT then stream:shutdown() if err == nil then return nil, ce.strerror(ce.EPIPE), ce.EPIPE end return nil, err, errno end end if headers and headers:get(":status") ~= "100" then -- Don't send body body = nil end end if body then local ok, err, errno if type(body) == "string" then ok, err, errno = stream:write_body_from_string(body, deadline and deadline-monotime()) elseif io.type(body) == "file" then ok, err, errno = body:seek("set") if ok then ok, err, errno = stream:write_body_from_file(body, deadline and deadline-monotime()) end elseif type(body) == "function" then -- call function to get body segments while true do local chunk = body() if chunk then ok, err, errno = stream:write_chunk(chunk, false, deadline and deadline-monotime()) if not ok then break end else ok, err, errno = stream:write_chunk("", true, deadline and deadline-monotime()) break end end end if not ok then stream:shutdown() return nil, err, errno end end end if not headers or non_final_status(headers:get(":status")) then -- Skip through 1xx informational headers. -- From RFC 7231 Section 6.2: "A user agent MAY ignore unexpected 1xx responses" repeat local err, errno headers, err, errno = stream:get_headers(deadline and (deadline-monotime())) if headers == nil then stream:shutdown() if err == nil then return nil, ce.strerror(ce.EPIPE), ce.EPIPE end return nil, err, errno end until not non_final_status(headers:get(":status")) end -- RFC 6797 Section 8.1 if tls and self.hsts and headers:has("strict-transport-security") then -- If a UA receives more than one STS header field in an HTTP -- response message over secure transport, then the UA MUST process -- only the first such header field. local sts = headers:get("strict-transport-security") sts = sts_patt:match(sts) -- The UA MUST ignore any STS header fields not conforming to the grammar specified. if sts then self.hsts:store(self.host, sts) end end if self.follow_redirects and headers:get(":status"):sub(1,1) == "3" then stream:shutdown() local new_req, err2, errno2 = self:handle_redirect(headers) if not new_req then return nil, err2, errno2 end return new_req:go(deadline and (deadline-monotime())) end return headers, stream end return { new_from_uri = new_from_uri; new_connect = new_connect; methods = request_methods; mt = request_mt; }
mit
RyanSquared/lua-http
spec/stream_common_spec.lua
2
3843
describe("http.stream_common", function() local h1_connection = require "http.h1_connection" local new_headers = require "http.headers".new local cqueues = require "cqueues" local ca = require "cqueues.auxlib" local cs = require "cqueues.socket" local function new_pair(version) local s, c = ca.assert(cs.pair()) s = h1_connection.new(s, "server", version) c = h1_connection.new(c, "client", version) return s, c end it("Can read a number of characters", function() local server, client = new_pair(1.1) local cq = cqueues.new() cq:wrap(function() local stream = client:new_stream() local headers = new_headers() headers:append(":authority", "myauthority") headers:append(":method", "GET") headers:append(":path", "/") assert(stream:write_headers(headers, false)) assert(stream:write_chunk("foo", false)) assert(stream:write_chunk("\nb", false)) assert(stream:write_chunk("ar\n", true)) end) cq:wrap(function() local stream = server:get_next_incoming_stream() -- same size as next chunk assert.same("foo", stream:get_body_chars(3)) -- less than chunk assert.same("\n", stream:get_body_chars(1)) -- crossing chunks assert.same("bar", stream:get_body_chars(3)) -- more than available assert.same("\n", stream:get_body_chars(8)) -- when none available assert.same(nil, stream:get_body_chars(8)) end) assert_loop(cq, TEST_TIMEOUT) assert.truthy(cq:empty()) client:close() server:close() end) it("Can read a line", function() local server, client = new_pair(1.1) local cq = cqueues.new() cq:wrap(function() local stream = client:new_stream() local headers = new_headers() headers:append(":authority", "myauthority") headers:append(":method", "GET") headers:append(":path", "/") assert(stream:write_headers(headers, false)) assert(stream:write_chunk("foo", false)) assert(stream:write_chunk("\nb", false)) assert(stream:write_chunk("ar\n", true)) end) cq:wrap(function() local stream = server:get_next_incoming_stream() assert.same("foo", stream:get_body_until("\n", true, false)) assert.same("bar", stream:get_body_until("\n", true, false)) assert.same(nil, stream:get_body_until("\n", true, false)) end) assert_loop(cq, TEST_TIMEOUT) assert.truthy(cq:empty()) client:close() server:close() end) it("can read into a temporary file", function() local server, client = new_pair(1.1) local cq = cqueues.new() cq:wrap(function() local stream = client:new_stream() local headers = new_headers() headers:append(":authority", "myauthority") headers:append(":method", "GET") headers:append(":path", "/") assert(stream:write_headers(headers, false)) assert(stream:write_chunk("hello world!", true)) end) cq:wrap(function() local stream = assert(server:get_next_incoming_stream()) local file = assert(stream:get_body_as_file()) assert.same("hello world!", file:read"*a") end) assert_loop(cq, TEST_TIMEOUT) assert.truthy(cq:empty()) client:close() server:close() end) it("can write body from temporary file", function() local server, client = new_pair(1.1) local cq = cqueues.new() cq:wrap(function() local file = io.tmpfile() assert(file:write("hello world!")) assert(file:seek("set")) local stream = client:new_stream() local headers = new_headers() headers:append(":authority", "myauthority") headers:append(":method", "GET") headers:append(":path", "/") assert(stream:write_headers(headers, false)) assert(stream:write_body_from_file(file)) end) cq:wrap(function() local stream = assert(server:get_next_incoming_stream()) assert.same("hello world!", assert(stream:get_body_as_string())) end) assert_loop(cq, TEST_TIMEOUT) assert.truthy(cq:empty()) client:close() server:close() end) end)
mit
chewi/Aquaria
files/scripts/entities/seaturtle.lua
6
5770
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- S E A T U R T L E (beta) -- ================================================================================================ -- ================================================================================================ -- S T A T E S -- ================================================================================================ local STATE_GLIDING = 1001 local STATE_TO_THRUST = 1002 local STATE_THRUSTING = 1003 local STATE_TO_GLIDE = 1004 -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.maxSpeed = 890 v.angle = 90 -- ================================================================================================ -- F U N C T I O N S -- ================================================================================================ function init(me) v.sz = 1.56 + (math.random(234)*0.001) v.swimTime = 0.34 + (math.random(42)*0.01) setupBasicEntity( me, "SeaTurtle/Head", -- texture 8, -- health 1, -- manaballamount 1, -- exp 1, -- money 64, -- collideRadius (only used if hit entities is on) STATE_GLIDING, -- initState 128, -- sprite width 128, -- sprite height 1, -- particle "explosion" type, maps to particleEffects.txt -1 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 1800 -- updateCull -1: disabled, default: 4000 ) entity_setDeathParticleEffect(me, "Explode") entity_setDropChance(me, 21) entity_initSkeletal(me, "SeaTurtle") entity_generateCollisionMask(me) v.shell = entity_getBoneByName(me, "Shell") entity_scale(me, v.sz, v.sz) entity_setEntityType(me, ET_NEUTRAL) entity_setState(me, STATE_GLIDING) entity_rotateTo(me, 360, 0.1) entity_setMaxSpeed(me, v.maxSpeed) end function postInit(me) -- FLIP HORIZONTALLY IF THERE'S A FLIP NODE local node = entity_getNearestNode(me, "FLIP") if node ~=0 then if node_isEntityIn(node, me) then entity_fh(me) end end end function update(me, dt) -- SWIM ANGLE if entity_getState(me) == STATE_GLIDING then v.swimTime = v.swimTime - dt if v.swimTime < 0 then v.swimTime = 1.23 + (math.random(234)*0.01) -- Point based on Flip if not entity_isfh(me) then v.angle = 58 + math.random(64) entity_rotateTo(me, v.angle + 270, 2) else v.angle = 238 + math.random(64) entity_rotateTo(me, v.angle + 90, 2) end entity_setState(me, STATE_TO_THRUST) end end -- SUBTLE GLIDE if entity_getState(me) == STATE_TO_THRUST then if not entity_isfh(me) then entity_moveTowardsAngle(me, entity_getRotation(me) - 270, 1, 2.48) else entity_moveTowardsAngle(me, entity_getRotation(me) - 90, 1, 2.48) end end -- FLIP L/R local flipThresh = 50 if entity_velx(me) < -flipThresh and not entity_isfh(me) then entity_fh(me) v.angle = v.angle + 180 elseif entity_velx(me) > flipThresh and entity_isfh(me) then entity_fh(me) v.angle = v.angle - 180 end -- NAIJA ATTACHING TO SHELL local rideBone = entity_collideSkeletalVsCircle(me, getNaija()) if rideBone == v.shell and avatar_isBursting() and entity_setBoneLock(getNaija(), me, rideBone) then elseif rideBone ~=0 then local nX, nY = entity_getPosition(getNaija()) local bX, bY = bone_getWorldPosition(rideBone) nX = nX - bX nY = nY - bY nX, nY = vector_setLength(nX, nY, 600) entity_addVel(getNaija(), nX, nY) end -- AVOIDANCE entity_doEntityAvoidance(me, dt, 43, 0.12) entity_doCollisionAvoidance(me, dt, 5, 0.36) -- MOVEMENT entity_doFriction(me, dt, 48) entity_updateMovement(me, dt) -- COLLISIONS entity_handleShotCollisionsSkeletal(me) end function enterState(me) if entity_getState(me) == STATE_GLIDING then entity_animate(me, "glide", LOOP_INF) elseif entity_getState(me) == STATE_TO_THRUST then entity_setStateTime(me, entity_animate(me, "tothrust"), -1) elseif entity_getState(me) == STATE_THRUSTING then entity_setStateTime(me, entity_animate(me, "thrust"), -1) elseif entity_getState(me) == STATE_TO_GLIDE then entity_setStateTime(me, entity_animate(me, "toglide"), -1) end end function exitState(me) if entity_getState(me) == STATE_GLIDING then elseif entity_getState(me) == STATE_TO_THRUST then entity_setState(me, STATE_THRUSTING) elseif entity_getState(me) == STATE_THRUSTING then -- THRUST entity_moveTowardsAngle(me, v.angle, 1, 124 + math.random(124)) entity_setState(me, STATE_TO_GLIDE) elseif entity_getState(me) == STATE_TO_GLIDE then entity_setState(me, STATE_GLIDING) end end function damage(me, attacker, bone, damageType, dmg) return true end
gpl-2.0
NOVAR1/DEV_NOVAR
plugins/locksexe.lua
4
1418
local function iq_100k(msg, matches) if not is_owner(msg) or not is_sudo(msg) then delete_msg(msg.id, ok_cb, true) local xxx = "لك لتفشر لا اجي اهينك 😼🌚 \n"..msg.from.first_name.."\n" return xxx -- by @iq_100k end end return { patterns = { "^(كس)", "^(عير)", "^(ديس)", "^(ديوس)", "^(عيوره)", "^(عيورة)", "^(صرم)", "^(جبه)", "^(لحس)", "^(رضع)", "^(جبة)", "^(فرخ)", "^(فروخ)", "^(كحاب)", "^(كحبه)", "^(كحبة)", "^(كواد)", "^(كوادة)", "^(كواده)", "^(تنيج)", "^(بعص)", "^(اختصب)", "^(انيج)", "^(pussy)", "^(cock)", "^(مصه)", "^(مصة)", "^(مصيه)", "^(اغتصب)", "^(اختصب)", "^(ناج)", "^(نايج)", "^(باعص)", "^(مبعوص)", "^(منيوج)", "^(تنح)", "^(ك س)", "^(ع ي ر)", "^(د ي س)", "^(د ي و س)", "^(ع ي و ر ه)", "^(ع ي و ر ة)", "^(ص ر م)", "^(ج ب ه)", "^(ل ح س)", "^(ر ض ع)", "^(ج ب ة)", "^(ف ر خ)", "^(ف ر و خ)", "^(ك ح ا ب)", "^(ك ح ب ه)", "^(ك ح ب ة)", "^(ك و ا د)", "^(ك و ا د ة)", "^(ك و ا د ه)", "^(ت ن ي ج)", "^(ب ع ص)", "^(ا خ ت ص ب)", "^(ا ن ي ج)", "^(p u s s y)", "^(c o c k)", "^(م ص ه)", "^(م ص ة)", "^(م ص ي ه)", "^(ا غ ت ص ب)", "^(ا خ ت ص ب)", "^(ن ا ج)", "^(ن ا ي ج)", "^(ب ا ع ص)", "^(م ب ع و ص)", "^(م ن ي و ج)", }, run = iq_100k, }
gpl-2.0
cgvarela/slurm
contribs/lua/job_submit.lua
3
3372
--[[ Example lua script demonstrating the SLURM job_submit/lua interface. This is only an example, not meant for use in its current form. Leave the function names, arguments, local varialbes and setmetatable set up logic in each function unchanged. Change only the logic after the line containing "*** YOUR LOGIC GOES BELOW ***". For use, this script should be copied into a file name job_"submit.lua" in the same directory as the SLURM configuration file, slurm.conf. --]] function _build_part_table ( part_list ) local part_rec = {} for i in ipairs(part_list) do part_rec[i] = { part_rec_ptr=part_list[i] } setmetatable (part_rec[i], part_rec_meta) end return part_rec end --########################################################################-- -- -- SLURM job_submit/lua interface: -- --########################################################################-- function slurm_job_submit ( job_desc, part_list ) setmetatable (job_desc, job_req_meta) local part_rec = _build_part_table (part_list) -- *** YOUR LOGIC GOES BELOW *** if job_desc.account == nil then local account = "***TEST_ACCOUNT***" log_info("slurm_job_submit: job from uid %d, setting default account value: %s", job_desc.user_id, account) job_desc.account = account end -- If no default partition, set the partition to the highest -- priority partition this user has access to if job_desc.partition == nil then local new_partition = nil local top_priority = -1 local last_priority = -1 for i in ipairs(part_rec) do -- log_info("part name[%d]:%s", i, part_rec[i].name) if part_rec[i].flag_default ~= 0 then top_priority = -1 break end last_priority = part_rec[i].priority if last_priority > top_priority then top_priority = last_priority new_partition = part_rec[i].name end end if top_priority >= 0 then log_info("slurm_job_submit: job from uid %d, setting default partition value: %s", job_desc.user_id, new_partition) job_desc.partition = new_partition end end return 0 end function slurm_job_modify ( job_desc, job_rec, part_list ) setmetatable (job_desc, job_req_meta) setmetatable (job_rec, job_rec_meta) local part_rec = _build_part_table (part_list) -- *** YOUR LOGIC GOES BELOW *** if job_desc.comment == nil then local comment = "***TEST_COMMENT***" log_info("slurm_job_modify: for job %u, setting default comment value: %s", job_rec.job_id, comment) job_desc.comment = comment end return 0 end --########################################################################-- -- -- Initialization code: -- -- Define functions for logging and accessing slurmctld structures -- --########################################################################-- log_info = slurm.log_info log_verbose = slurm.log_verbose log_debug = slurm.log_debug log_err = slurm.error job_rec_meta = { __index = function (table, key) return _get_job_rec_field(table.job_rec_ptr, key) end } job_req_meta = { __index = function (table, key) return _get_job_req_field(table.job_desc_ptr, key) end, __newindex = function (table, key, value) return _set_job_req_field(table.job_desc_ptr, key, value or "") end } part_rec_meta = { __index = function (table, key) return _get_part_rec_field(table.part_rec_ptr, key) end } log_info("initialized") return slurm.SUCCESS
gpl-2.0
resistor58/deaths-gmod-server
Nuke Pack 4/lua/effects/nuke_blastwave/old 1.lua
3
1854
function EFFECT:Init( data ) self.Position = data:GetOrigin() self.Yield = data:GetMagnitude() self.YieldSlow = self.Yield^0.75 self.YieldSlowest = self.Yield^0.3 self.TimeLeft = CurTime() + self.Yield*6 self.SplodeDist = 3100 self.BlastSpeed = 4000 self.WaveResolution = 0.05 self.lastThink = CurTime() + 0.75 self.Emitter = ParticleEmitter(self.Position) end --THINK -- Returning false makes the entity die function EFFECT:Think( ) if self.TimeLeft > CurTime() then if self.lastThink < CurTime() then self.lastThink = CurTime() + self.WaveResolution self.SplodeDist = self.SplodeDist + self.BlastSpeed*(self.WaveResolution + FrameTime()) local Intensity = -8.2e-5*self.SplodeDist + 3.5 -- big dust wave for i=1, math.ceil(70/Intensity) do local vecang = Vector(math.Rand(-32,32),math.Rand(-32,32),0):GetNormalized() local startpos = self.Position + vecang*math.Rand(0.97*self.SplodeDist,1.03*self.SplodeDist) startpos.z = startpos.z - self.YieldSlowest*650 local particle = self.Emitter:Add( "particles/smokey", startpos ) particle:SetVelocity(math.Rand(600,640)*Intensity*vecang + Vector(0,0,math.Rand(30,40)*((4 - Intensity)^2 + 15))) particle:SetDieTime( self.YieldSlowest*Intensity ) particle:SetStartAlpha( 110 ) particle:SetEndAlpha( 0 ) particle:SetStartSize( self.YieldSlowest*math.Rand( 500, 600 ) ) particle:SetEndSize( self.YieldSlowest*math.Rand( 700, 800 ) ) particle:SetRoll( math.Rand( 480, 540 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(160,152,120) particle:VelocityDecay( true ) end end return true else self.Emitter:Finish() return false end end -- Draw the effect function EFFECT:Render() end
gpl-3.0
vividos/RemotePhotoTool
scripts/BulbShutterRelease.lua
1
4090
-- -- RemotePhotoTool - remote camera control software -- Copyright (C) 2008-2016 Michael Fink -- file BulbShutterRelease.lua - Demo script: Shutter release using Bulb release control -- -- The App object is a global object, and its run() function is called by the Lua -- scripting engine when starting the script. App = { -- entry point function run = function(self) print("BulbShutterRelease.lua - Demo script: Shutter release using Bulb release control\n\n"); local instance = Sys:getInstance(); local allSourceInfos = instance:enumerateDevices(); -- The enumerateDevices() function returns nil when no device is -- connected, so check before using if (allSourceInfos ~= nil and allSourceInfos.length > 0) then local remoteReleaseControl = self:openCamera(allSourceInfos[1]); self:checkBulbMode(remoteReleaseControl); remoteReleaseControl:close(); print("Finished.\n\n"); else print("No cameras connected. Exiting.\n"); end; end; -- opens the camera to take images openCamera = function(self, sourceInfo) print("Opening camera " .. sourceInfo.name .. "\n"); local sourceDevice = sourceInfo:open(); local capRemoteReleaseControl = sourceDevice:getDeviceCapability(Constants.SourceDevice.capRemoteReleaseControl); if (not capRemoteReleaseControl) then print("Camera can't be remote controlled!"); return nil; end; local remoteReleaseControl = sourceDevice:enterReleaseControl(); return remoteReleaseControl; end; -- checks bulb mode functions checkBulbMode = function(self, remoteReleaseControl) local capBulbMode = remoteReleaseControl:getCapability(Constants.RemoteReleaseControl.capBulbMode); if (not capBulbMode) then print("Bulb mode not supported by this camera."); return; end; if (self:checkManualShootingMode(remoteReleaseControl)) then self:setBulbShutterSpeed(remoteReleaseControl); self:takeBulbModeImage(remoteReleaseControl); end; end; -- checks if the connected camera has the "Manual" shooting mode checkManualShootingMode = function(self, remoteReleaseControl) local capChangeShootingMode = remoteReleaseControl:getCapability(Constants.RemoteReleaseControl.capChangeShootingMode); local manualShootingMode = remoteReleaseControl:getShootingModeImageProperty(Constants.ShootingMode.shootingModeM); if (capChangeShootingMode) then -- we can change the shooting mode ourselves print("Set Shooting mode M...\n"); remoteReleaseControl:setImageProperty(manualShootingMode); else -- we can't change the shooting mode, so just check local shootingMode = remoteReleaseControl:getImagePropertyByType(Constants.ImageProperty.shootingMode); if (shootingMode.asString == manualShootingMode.asString) then print("Shooting mode M correctly set.\n"); else print("Wrong shooting mode set! Please set your camera to Manual mode " .. "(current mode is " .. shootingMode.asString .. ").\n"); return false; end; end; return true; end; -- sets Bulb shutter speed, in Manual mode, if necessary setBulbShutterSpeed = function(self, remoteReleaseControl) local shutterSpeed = remoteReleaseControl:getImagePropertyByType(Constants.ImageProperty.Tv); if (shutterSpeed.asString ~= "Bulb") then print("Set shutter speed \"Bulb\"...\n"); -- in Canon EDSDK (for Canon DSLRs such as the 40D), shutter -- speed "Bulb" has the value hex 0x0C, decimal 12 shutterSpeed.value = 12; remoteReleaseControl:setImageProperty(shutterSpeed); -- wait some time so that image property has been set Sys:createEvent():wait(0.5); end; end; -- takes an image using bulb mode of camera, if supported takeBulbModeImage = function(self, remoteReleaseControl) print("Start taking image...\n"); local bulbReleaseControl = remoteReleaseControl:startBulb() -- wait for some seconds, then stop bulb mode local event = Sys:createEvent(); event:wait(5.0); bulbReleaseControl:stop(); local elapsed = bulbReleaseControl:elapsedTime(); print("Elapsed time: " .. elapsed .. " seconds.\n"); end; }
bsd-2-clause
zchengquan/nn
SpatialDeconvolution.lua
1
4374
local SpatialDeconvolution, parent = torch.class('nn.SpatialDeconvolution', 'nn.Module') function SpatialDeconvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialDeconvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil else self.padW = self.padW or 0 self.padH = self.padH or 0 end if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end function SpatialDeconvolution:updateOutput(input) -- backward compatibility if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil end input = makeContiguous(self, input) return input.nn.SpatialDeconvolution_updateOutput(self, input) end function SpatialDeconvolution:updateGradInput(input, gradOutput) if self.gradInput then input, gradOutput = makeContiguous(self, input, gradOutput) return input.nn.SpatialDeconvolution_updateGradInput(self, input, gradOutput) end end function SpatialDeconvolution:accGradParameters(input, gradOutput, scale) --backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) return input.nn.SpatialDeconvolution_accGradParameters(self, input, gradOutput, scale) end function SpatialDeconvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end function SpatialDeconvolution:__tostring__() local s = string.format('%s(%d -> %d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end return s .. ')' end
bsd-3-clause
sunxfancy/LR_Parser
test/c-1/init_pcode.lua
2
2230
-- kind 定义 func_kind = 1 var_kind = 2 param_kind = 3 const_kind = 4 -- 下面是type定义 int_type = 1 real_type = 2 struct_type = 3 class_type = 4 -- 指令定义 LIT = 1 OPR = 2 LOD = 3 STO = 4 CAL = 5 INT = 6 JMP = 7 JPC = 8 RED = 9 WRT = 10 RET = 11 REV = 12 -- 一些杂七杂八的定义 isconstdef = false --用于const标签的属性传递 paramsum = 0 iflist = nil --这个是用于if语句的拉链 make_code( JMP, 0 ) --提前写入占位的跳转动作 function vardef( idname , data ) if isconstdef then save_id(idname,const_kind,int_type,data) else paramsum = paramsum + 1 save_id(idname,var_kind,int_type,paramsum) if data ~= 0 then make_code(LIT,data) else make_code(INT,1) end end end -- id 在 运算时,首先看是否静态的 function varload( idname ) local t = find_id(idname); local data = 0 if t == nil then print("Error: the ID is invaild") exit() end print(idname, t.address); if t.kind == const_kind then data = t.address; return data; else print("t.level",t.level,"t.address",t.address) return nil, t.level, t.address; end end function varload_address( idname ) local t = find_id(idname); if t == nil then print("Error: the ID is invaild") exit() end print(idname, t.address); if t.kind == var_kind then print("t.level",t.level,"t.address",t.address) return t.level, t.address; end end function trytoCalculate( a, b, opt) --[[if a.data ~= nil and b.data ~= nil then if opt == "+" then return a.data + b.data elseif opt=="-" then return a.data - b.data elseif opt=="*" then return a.data * b.data elseif opt=="/" then return a.data / b.data end end --]] if a.data ~= nil then make_code(LIT, a.data) else print(LOD, a.level, a.address) make_code(LOD, a.level, a.address) end if b.data ~= nil then make_code(LIT, b.data) else print(LOD, b.level, b.address) make_code(LOD, b.level, b.address) end if opt == "+" then make_code(OPR, 1) elseif opt=="-" then make_code(OPR, 2) elseif opt=="*" then make_code(OPR, 3) elseif opt=="/" then make_code(OPR, 4) end return nil end
mit
ruvolof/telegram-bot
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
Nottinghster/OTServ_SVN-0.6.4
src/data/talkactions/scripts/createitembynamefront.lua
1
1406
function onSay( cid, words, param ) local playerPos = getPlayerPosition( cid ) local parameters = serializeParam( param ) local itemname = interpretStringAsWordParam(parameters[1]) if ( itemname == nil )then doPlayerSendTextMessage( cid, MESSAGE_STATUS_CONSOLE_BLUE, "You need to type the name of the item!" ) doSendMagicEffect( playerPos, CONST_ME_POFF ) return false end local itemcount = interpretStringAsWordParam(parameters[2], true) if itemcount == nil or itemcount < 1 then itemcount = 1 else itemcount = math.min(math.floor(itemcount), 100 ) end local itemid = getItemIdByName(itemname) if( itemid == false )then doPlayerSendTextMessage( cid, MESSAGE_STATUS_CONSOLE_BLUE, "There isn't any item named " .. '"' .. itemname .. '".' ) doSendMagicEffect( playerPos, CONST_ME_POFF ) return false end local posItem = getPosByDir(playerPos, getCreatureLookDir(cid)) local item = doCreateItem( itemid, itemcount, posItem ) if( item ~= false )then local actionId = interpretStringAsWordParam(parameters[3], true) if actionId ~= nil and itemcount == 1 then doSetItemActionId(item, actionId) end doDecayItem( item ) doSendMagicEffect( playerPos, CONST_ME_MAGIC_GREEN ) return true else doPlayerSendTextMessage( cid, MESSAGE_STATUS_CONSOLE_BLUE, "Item could not be summoned." ) doSendMagicEffect( playerPos, CONST_ME_POFF ) return false end end
gpl-2.0
resistor58/deaths-gmod-server
Mad Cows Weapons/lua/weapons/weapon_mad_m249/shared.lua
1
1618
// Variables that are used on both client and server SWEP.Base = "weapon_mad_base" SWEP.ViewModel = "models/weapons/v_mach_m249para.mdl" SWEP.WorldModel = "models/weapons/w_mach_m249para.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = false SWEP.Primary.Sound = Sound("Weapon_M249.Single") SWEP.Primary.Recoil = 1 SWEP.Primary.Damage = 30 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.03 SWEP.Primary.Delay = 0.08 SWEP.Primary.ClipSize = 100 // Size of a clip SWEP.Primary.DefaultClip = 100 // Default number of bullets in a clip SWEP.Primary.Automatic = true // Automatic/Semi Auto SWEP.Primary.Ammo = "AirboatGun" SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none" SWEP.ShellEffect = "effect_mad_shell_rifle" // "effect_mad_shell_pistol" or "effect_mad_shell_rifle" or "effect_mad_shell_shotgun" SWEP.Pistol = false SWEP.Rifle = true SWEP.Shotgun = false SWEP.Sniper = false SWEP.IronSightsPos = Vector (-4.4153, 0, 2.1305) SWEP.IronSightsAng = Vector (0, 0, 0) SWEP.RunArmOffset = Vector (2.2344, -2.2257, 1.7539) SWEP.RunArmAngle = Vector (-19.3086, 29.9962, 0) /*--------------------------------------------------------- Name: SWEP:Precache() Desc: Use this function to precache stuff. ---------------------------------------------------------*/ function SWEP:Precache() util.PrecacheSound("weapons/m249/m249-1.wav") end
gpl-3.0
ld-test/loverocks
loverocks/util.lua
1
4917
local lfs = require 'lfs' local datafile = require 'datafile' local T = require 'loverocks.schema' local log = require 'loverocks.log' local util = {} local function slurp_file(fname) local file, err = io.open(fname, 'r') assert(file, err) local s = file:read('*a') file:close() return s end local function slurp_dir(dir) local t = {} for f in lfs.dir(dir) do if f ~= "." and f ~= ".." then t[f] = assert(util.slurp(dir .. "/" .. f)) end end return t end function util.is_dir(path) T(path, 'string') return lfs.attributes(path, 'mode') == 'directory' end function util.is_file(path) T(path, 'string') return lfs.attributes(path, 'mode') == 'file' end function util.slurp(path) T(path, 'string') local ftype, err = lfs.attributes(path, 'mode') if ftype == 'directory' then return slurp_dir(path) elseif ftype then return slurp_file(path) else return nil, err end end local function spit_file(str, dest) local file, ok, err log:fs("spit %s", dest) file, err = io.open(dest, "w") if not file then return nil, err end ok, err = file:write(str) if not ok then return nil, err end ok, err = file:close() if not ok then return nil, err end return true end local function spit_dir(tbl, dest) log:fs("mkdir %s", dest) if not util.is_dir(dest) then local ok, err = lfs.mkdir(dest) if not ok then return nil, err end end for f, s in pairs(tbl) do if f ~= "." and f ~= ".." then local ok, err = util.spit(s, dest .. "/" .. f) if not ok then return nil, err end end end return true end -- Keep getting the argument order mixed up function util.spit(o, dest) T(o, T.sum('table', 'string')) T(dest, 'string') if type(o) == 'table' then return spit_dir(o, dest) else return assert(spit_file(o, dest)) end end local function ls_dir(dir) local t = {} for entry in lfs.dir(dir) do if entry ~= "." and entry ~= ".." then local file_or_dir = util.files(dir .. "/" .. entry) if type(file_or_dir) == 'table' then for _, file in ipairs(file_or_dir) do table.insert(t, file) end else table.insert(t, file_or_dir) end end end return t end local function ls_file(path) return path end function util.files(path) T(path, 'string') local ftype, err = lfs.attributes(path, 'mode') if ftype == 'directory' then return ls_dir(path) elseif ftype then return ls_file(path) else return nil, err end end function util.get_home() return (os.getenv("HOME") or os.getenv("USERPROFILE")) end function util.clean_path(path) T(path, 'string') if path:match("^%~/") then path = path:gsub("^%~/", util.get_home() .. "/") end if not path:match("^/") and not path:match("%./") then path = lfs.currentdir() .. "/" .. path end return path end function util.rm(path) T(path, 'string') local ftype, ok, err log:fs("rm -r %s", path) ftype, err = lfs.attributes(path, 'mode') if not ftype then return nil, err end if ftype == 'directory' then for f in lfs.dir(path) do if f ~= "." and f ~= ".." then local fp = path .. "/" .. f ok, err = util.rm(fp) if not ok then return nil, err end end end end return os.remove(path) end function util.exists(path) T(path, 'string') local f, err = io.open(path, 'r') if f then f:close() return true end return nil, err end -- a replacement datafile.path() function util.dpath(resource) T(resource, 'string') -- for some reason datafile.path doesn't work local tmpfile, path = datafile.open(resource, 'r') local err = path if not tmpfile then return nil, err end tmpfile:close() return path end -- get first file matching pat function util.get_first(path, pat) T(path, 'string') T(pat, 'string') local ftype = lfs.attributes(path, 'mode') assert(ftype == 'directory', tostring(path) .. " is not a directory") for f in lfs.dir(path) do if f:match(pat) then return f end end return nil, "Not found" end -- like io.popen, but returns a string instead of a file function util.stropen(cli) T(cli, 'string') local f = io.popen(cli, 'r') local s = f:read('*a') f:close() return s end -- produce str with magic characters escaped, for pattern-building function util.escape_str(s) return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')) end function util.mkdir_p(directory) T(directory, 'string') directory = util.clean_path(directory) local path = nil if directory:sub(2, 2) == ":" then path = directory:sub(1, 2) directory = directory:sub(4) else if directory:match("^/") then path = "" end end for d in directory:gmatch("([^".."/".."]+)".."/".."*") do path = path and path .. "/" .. d or d local mode = lfs.attributes(path, "mode") if not mode then local ok, err = lfs.mkdir(path) if not ok then return false, err end elseif mode ~= "directory" then return false, path.." is not a directory" end end return true end return util
mit
tehran980/tele_HSN
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
tkdrob/Battle-Tag
Packages/TheWolf/Data/Script/Lua/UATheWolf.lua
1
5739
--[[-------------------------------------------------------------------------- -- -- File: UAThewolf.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: August 29, 2010 -- ------------------------------------------------------------------------------ -- -- Description: test activity -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "UTActivity" --[[ Class -----------------------------------------------------------------]] UTClass.UATheWolf(UTActivity) -- state dependencies UATheWolf.State = {} require "UATheWolf.State.RoundLoop" -- default UATheWolf.bitmap = "base:texture/ui/loading_thewolf.tga" UATheWolf.minNumberOfPlayer = 3 -- __ctor -------------------------------------------------------------------- function UATheWolf:__ctor(...) -- activity name self.name = l"title015" self.category = UTActivity.categories.closed self.nodual = true self.textScoring = l"score009" self.Ui.Title.textScoring.rectangle = { 20, 50, 640, 210 } self.textRules = l"rules011" self.iconBanner = "base:texture/ui/Ranking_Bg_TheWolf.tga" -- scoringField self.scoringField = { {"score", nil, nil, 280, quartz.system.drawing.justification.right, UIComponent.fonts.header, UIComponent.colors.orange}, } -- settings self.settings = { [1] = { title = l"titlemen006", options = { [1] = { displayMode = nil, label = l"goption001", tip = l"tip027", choices = { { value = 2 }, { value = 5 }, { value = 6 }, { value = 7 }, { value = 8 }, { value = 10 }, { value = 15 }, { value = 20 }, { value = 30 } }, index = "playtime", }, [2] = { displayMode = nil, label = l"goption029", tip = l"tip142", choices = { { value = 1 }, { value = 2 }, { value = 3 }, { value = 4 }, { value = 5 } }, index = "nbwolves", }, }, }, -- keyed settings playtime = 5, nbwolves = 1, -- no team numberOfTeams = 0, } -- playground -- !! TABLE FORMAT : { [numberofplayer] = { ["ITEM_BITMAP"] = { category = "string", priority = number, size = number, positions = { { number, number }, ... }, title = "string", text = "string", condition = function() }, ... } self.playground = { [1] = { RF03 = { priority = 1, title = l"oth056" .. " (" .. l"oth027" .. ")", text = string.format(l"psexp034"), positions = { { 50, 150 }, }, }, RF04 = { priority = 2, title = l"oth057" .. " (" .. l"oth028" .. ")", text = string.format(l"psexp034"), positions = { { 480, 150 }, }, }, RF05 = { priority = 3, title = l"oth058" .. " (" .. l"oth029" .. ")", text = string.format(l"psexp034"), positions = { { 265, 30 }, }, }, RF06 = { priority = 4, title = l"oth059" .. " (" .. l"oth030" .. ")", text = string.format(l"psexp034"), positions = { { 265, 270 }, }, }, RF09 = { priority = 4, title = l"oth055", text = string.format(l"psexp033"), positions = { { 265, 150 }, }, }, }, } -- ?? CONFIG DATA SEND WITH RF self.configData = { "id", } -- details columms descriptor self.detailsDescriptor = nil -- overriden states self.states["roundloop"] = UATheWolf.State.RoundLoop:New(self) -- ?? LES SETTINGS SONT RENSEIGN�S DANS LE CONSTRUCTEUR DE L'ACTIVIT� -- ?? LES PARAM�TRES (DISPLAYMODE, TEXTE, ICONE...) DES COLONES DE GRID SONT RENSEIGN�S DANS LE COMPOSANT D�DI� DU LEADERBOARD -- ?? LES ATTRIBUTS - HEAP, BAKED - DES ENTIT�S SONT RENSEIGN�S PAR 2 APPELS DE FONCTION D�DI�S DANS L'ACTIVIT� (� SURCHARGER) -- ?? POUR LES DONN�ES DE CONFIGURATION DE BYTECODE, CE SERA SUREMENT PAREIL QUE POUR LES ATTRIBUTS = FONCTION D�DI� (� SURCHARGER) -- ?? POUR LE LEADERBOARD: -- ?? - SURCHARGER LA PAGE QUI UTILISE LE LEADERBOARD STANDARD, -- ?? - RAJOUTER DES PARAM�TRES (DISPLAYMODE, TEXTE, ICONE...) DES COLONES DE GRID SI N�CESSAIRE EN + DE CEUX PAR D�FAUT (LIFE, HIT, AMMO...) -- ?? - RENSEIGNER QUELS ATTRIBUTS ON SOUHAITE REPR�SENTER PARMIS CEUX EXISTANT EN HEAP end -- __dtor -------------------------------------------------------------------- function UATheWolf:__dtor() end -- InitEntityBakedData ------------------------------------------------------ function UATheWolf:InitEntityBakedData(entity, ranking) entity.data.baked.score = 0 entity.data.baked.ranking = ranking UTActivity:InitEntityBakedData(entity, ranking) end -- InitEntityHeapData ----------------------------------------------------- function UATheWolf:InitEntityHeapData(entity, ranking) -- !! INITIALIZE ALL HEAP DATA (RELEVANT DURING ONE MATCH ONLY) entity.data.heap.wolfTimer = 0 if (not game.gameMaster.ingame) then entity.gameplayData = { 0x00, 0x00 } entity.data.heap.score = 0 entity.data.heap.ranking = ranking entity.data.heap.nbHit = 0 entity.data.heap.nbHitbackup = 0 if (entity.rfGunDevice) then entity.data.heap.id = entity.rfGunDevice.classId else entity.data.heap.id = ranking end entity.data.heap.last_rfid = 0 end UTActivity:InitEntityHeapData(entity, ranking) end -- UpdateEntityBakedData --------------------------------------------- function UATheWolf:UpdateEntityBakedData(entity, ranking) entity.data.baked.score = entity.data.baked.score + entity.data.heap.score end
mit
tehran980/https-github.com-uziins-uzzbot
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id 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 get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
amirik22/uzzbot
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id 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 get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
chewi/Aquaria
files/scripts/maps/node_hint_licombat.lua
6
1144
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if hasLi() and isFlag(FLAG_HINT_LICOMBAT, 0) then if node_isEntityIn(me, getNaija()) then setControlHint(getStringBank(7), 0, 0, 0, 8, "", SONG_LI) setFlag(FLAG_HINT_LICOMBAT, 1) end end end
gpl-2.0
tgclonerteam/goodday
plugins/ingroup.lua
1
57213
do -- Check Member local function check_member_autorealm(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)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_adds = 'yes', lock_abuse = 'yes', welcome_stat = 'yes', sticker = 'ok', antitag = 'no', lock_join = 'no', welcome = 'chat', -- silent = 'no', } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(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)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_adds = 'yes', lock_abuse = 'yes', welcome_stat = 'yes', sticker = 'ok', antitag = 'no', lock_join = 'no', -- silent = 'no', welcome = 'chat', } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(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)] = { group_type = 'Group', 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', lock_adds = 'yes', lock_abuse = 'yes', welcome_stat = 'yes', sticker = 'ok', antitag = 'no', lock_join = 'no', -- silent = 'no', welcome = 'chat', } } 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)] = { group_type = 'Group', 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', lock_adds = 'yes', lock_abuse = 'yes', welcome_stat = 'yes', sticker = 'ok', antitag = 'no', lock_join = 'no', -- silent = 'no', welcome = 'chat', } } 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, 'Group 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_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(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 -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end 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 --End Check Member 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 leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] 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🤘: f."..NUM_MSG_MAX.."\nBot protection👾: "..bots_protection.."\nAdds protection☠: "..settings.lock_adds.."\nLock Tag🆔: "..settings.antitag.."\nSticker Policy👻: "..settings.sticker--.."\nWelcome👤➕:"..settings.welcome 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 set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['antitag'] if group_tag_lock == 'yes' then return 'tag is already locked' else data[tostring(target)]['settings']['antitag'] = 'yes' save_data(_config.moderation.data, data) return 'tag has been locked' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['antitag'] if group_tag_lock == 'no' then return 'tag is already unlocked' else data[tostring(target)]['settings']['antitag'] = 'no' save_data(_config.moderation.data, data) return 'tag has been unlocked' end end local function lock_group_join(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_join_lock = data[tostring(target)]['settings']['lock_join'] if group_join_lock == 'yes' then return ' joining Link is already locked' else data[tostring(target)]['settings']['lock_join'] = 'yes' save_data(_config.moderation.data, data) return 'Link has been locked' end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_join_lock = data[tostring(target)]['settings']['lock_join'] if group_join_lock == 'no' then return ' joining Link is already unlocked' else data[tostring(target)]['settings']['lock_join'] = 'no' save_data(_config.moderation.data, data) return ' joining Link has been unlocked' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' 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 lock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_adds_lock = data[tostring(target)]['settings']['lock_adds'] if group_adds_lock == 'yes' then return 'Adds protection is already enabled' else data[tostring(target)]['settings']['lock_adds'] = 'yes' save_data(_config.moderation.data, data) return 'Adds protection has been enabled' end end local function unlock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_adds_lock = data[tostring(target)]['settings']['lock_adds'] if group_adds_lock == 'no' then return 'Adds protection is already disabled' else data[tostring(target)]['settings']['lock_adds'] = 'no' save_data(_config.moderation.data, data) return 'Adds protection has been disabled' end local function silent(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local silent = data[tostring(target)]['settings']['silent'] if silent == 'yes' then return 'Group silent is already enabled' else data[tostring(target)]['settings']['silent'] = 'yes' save_data(_config.moderation.data, data) return 'Group silent has been enabled' end end end local function unlock_silent(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_silent = data[tostring(target)]['settings']['silent'] if group_silent == 'no' then return 'Group silent is already disabled' else data[tostring(target)]['settings']['silent'] = 'no' save_data(_config.moderation.data, data) return 'Group silent has been disabled' end local function lock_group_fosh(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_fosh_lock = data[tostring(target)]['settings']['antifosh'] if group_fosh_lock == 'yes' then return 'fosh is already locked' else data[tostring(target)]['settings']['antifosh'] = 'yes' save_data(_config.moderation.data, data) return 'fosh has been locked' end end local function unlock_group_fosh(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_fosh_lock = data[tostring(target)]['settings']['antifosh'] if group_fosh_lock == 'no' then return 'fosh is already unlocked' else data[tostring(target)]['settings']['antifosh'] = 'no' save_data(_config.moderation.data, data) return 'fosh has been unlocked' end end local function welcome_yes(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local welcome_yes = data[tostring(target)]['settings']['welcome_yes'] if welcome_yes == 'yes' then return 'Welcome is already enabled' else data[tostring(target)]['settings']['welcome_yes'] = 'yes' save_data(_config.moderation.data, data) return 'Welcome has been enabled' end end end local function welcome_no(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local welcome_no = data[tostring(target)]['settings']['welcome_no'] if group_adds_lock == 'no' then return 'Welcome is already disabled' else data[tostring(target)]['settings']['welcome_no'] = 'no' save_data(_config.moderation.data, data) return 'Welcome has been disabled' 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 is_group(msg) 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 realmadd(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 is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions 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 is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(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 is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{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 promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end 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 demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_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 local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][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 i = 1 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 ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message 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 -- if msg.text == 'helpen' then -- local help_text = tostring(_config.help_text) --return help_text --end --end -- if msg.text == 'helpfa' then -- local helpfa_text = " لیست دستورات :\n\n!kick [username|id]\nمیتوانید از ریپلای هم استفاده کنید\n〰〰〰〰〰〰\n!ban [ username|id]\nمیتوانید از ریپلای هم استفاده کنید\n〰〰〰〰〰〰\n!unban [id]\nمیتوانید از ریپلای هم استفاده کنید\n〰〰〰〰〰〰\n!who\nلیست اعضا\n〰〰〰〰〰〰\n!modlist\nلیست مدیران\n〰〰〰〰〰〰\n!promote [username]\nمقام دادن به شخص\nمیتوانید از ریپلای هم استفاده کنید\n〰〰〰〰〰〰\n!demote [username]\nگرفتن مقام از شخص\nمیتوانید از ریپلای هم استفاده کنید\n〰〰〰〰〰〰\n!kickme\nلفت از گروه با قابلیت برگشت\n〰〰〰〰〰〰\n!about\nتوضیحات گروه\n〰〰〰〰〰〰\n!setphoto\nتنظیم و قفل عکس گروه\n〰〰〰〰〰〰\n!setname [name]\nتنظیم اسم گروه ( بدون قفل )\n〰〰〰〰〰〰\n!rules\nقوانین\n〰〰〰〰〰〰\n!id\nآیدی گروه زیاد به کار نمیاد\n〰〰〰〰〰〰\n!help\nهمین متن\n〰〰〰〰〰〰\n!lock [member|name|bots|leave|arabic|tag|adds] \nقفل [اعضا|اسم|ربات|لفت|فارسی|تگ|تبلیغات] \n〰〰〰〰〰〰\n!unlock [member|name|bots|leave|arabic|tag|adds]\nبرداشتن قفل [اعضا|اسم|ربات|لفت|فارسی|تگ|تبلیغات] \n〰〰〰〰〰〰\n!set rules <text>\nتنظیم قوانین\n〰〰〰〰〰〰\n!set about <text>\nتنظیم توضیحات\n〰〰〰〰〰〰\n!settings\nتنظیمات گروه\n〰〰〰〰〰〰\n!newlink\nساخت / تغییر لینک\n〰〰〰〰〰〰\n!link\nلینک گروه\n〰〰〰〰〰〰\n!owner\nمدیر اصلی گروه\n〰〰〰〰〰〰\n!setowner [id]\nتنظیم مدیر اصلی گروه\n〰〰〰〰〰〰\n!setflood [value]\nتنظیم مقدار حساسیت اسپم\n〰〰〰〰〰〰\n!stats\nدیدن تعداد پیام های فرستاده شده\n〰〰〰〰〰〰\n!save [value] <text>\nتنظیم یک متن در گروه\n〰〰〰〰〰〰\n!get [value]\nگرفتن متن تنظیم شده\n〰〰〰〰〰〰\n!clean [modlist|rules|about]\nپاک کردن [لیست مدیرها | قوانین | توضیحات]\n〰〰〰〰〰〰\n!res [username]\nگرفتن اطلاعات یک نفر\n〰〰〰〰〰〰\n!log\nلیست دستورات استفاده شده در گروه\n〰〰〰〰〰〰\n!sticker [warn|kick|ok]\nwarn : اخطار دادن موقع فرستادن استیکر\nkick : کیک کردن موقع فرستادن استیکر\nok : کاری نکردن موفع فرستادن استیکر\n〰〰〰〰〰〰\n!tagall [text]\nتگ کردن همه با آیدی + پیام شما\n〰〰〰〰〰〰\n!about us\nاطلاعات درباره ربات\n〰〰〰〰〰〰\n!persiangulf\nفرستادن لوگو خلیج فارس در قالب استیکر\n〰〰〰〰〰〰\n!all\nدیدن همه اطلاعات گروه\n〰〰〰〰〰〰\n!block (user-id)\n!unblock (user-id)\nبلاک کردن شخص\nآنبلاک کردن شخص\nبرای ادمین های ربات\n〰〰〰〰〰〰\n!kickinactive\nکیک کردن اعضایی که فعال نیستند\n〰〰〰〰〰〰\n!calc [expression]\nماشین حساب\n〰〰〰〰〰〰\n!qr [text]\nبارکد ساز\n〰〰〰〰〰〰\n!webshot [url]\nگرفتن عکس از یک سایت\n!banlist\nلیست بن شدگان\n〰〰〰〰〰〰\n**شما میتوانید از ! و / و . برای علامت دستورها استفاده کنید\n〰〰〰〰〰〰\n**ربات در پیوی به هیچ کس جواب نمیدهد\n" -- return helpfa_text --end --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 for k,v in pairs(result.members) do kick_user(v.id, result.id) 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 user_msgs(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 = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) 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' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(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_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 not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) 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] == 'silent' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] turned on silent ") return silent(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] turned off silent ") return unlock_silent(msg, data, target) 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 if matches[2] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked adds ") return lock_group_adds(msg, data, target) end if matches[2] == 'fosh' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh ") return lock_group_fosh(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english ") return lock_group_english(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked joining link ") return lock_group_join(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 if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked English ") return unlock_group_english(msg, data, target) end if matches[2] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked adds ") return unlock_group_adds(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag ") return unlock_group_tag(msg, data, target) end if matches[2] == 'fosh' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh ") return unlock_group_fosh(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked joining link ") return unlock_group_join(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] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'newlink' and not is_realm(msg) 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 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' and matches[2] 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] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end 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] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end -- if matches[1] == 'help' then -- if not is_momod(msg) or is_realm(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 if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/.]([Aa]dd)$", "^[!/.]([Aa]dd) (realm)$", "^[!/.]([Rr]em)$", "^[!/.]([Rr]em) (realm)$", "^[!/.]([Rr]ules)$", "^[!/.]([Aa]bout)$", "^[!/.]([Ss]etname) (.*)$", "^[!/.]([Ss]etphoto)$", "^[!/.]([Pp]romote) (.*)$", "^[!/.]([Pp]romote)", --"^[!/.]([Hh]elp)$", --"^[!/.]([Hh]elpfa)$", "^[!/.]([Cc]lean) (.*)$", "^[!/.]([Kk]ill) (chat)$", "^[!/.]([Kk]ill) (realm)$", "^[!/.]([Dd]emote) (.*)$", "^[!/.]([Dd]emote)", "^[!/.]([Ss]et) ([^%s]+) (.*)$", "^[!/.]([Ww]elcome) (.*)$", "^[!/.]([Ss]ilent) (.*)$", "^[!/.]([Ll]ock) (.*)$", "^[!/.]([Ss]etowner) (%d+)$", "^[!/.]([Ss]etowner)", "^[!/.]([Oo]wner)$", "^[!/.]([Rr]es) (.*)$", "^[!/.]([Ss]etgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/.]([Uu]nlock) (.*)$", "^[!/.]([Ss]etflood) (%d+)$", "^[!/.]([Ss]ettings)$", "^[!/.]([Pp]ublic) (.*)$", "^[!/.]([Mm]odlist)$", "^[!/.]([Nn]ewlink)$", "^[!/.]([Ll]ink)$", "^[!/.]([Kk]ickinactive)$", "^[!/.]([Kk]ickinactive) (%d+)$", "^([Aa]dd)$", "^([Aa]dd) (realm)$", "^([Rr]em)$", "^([Rr]em) (realm)$", "^([Rr]ules)$", "^([Aa]bout)$", "^([Ss]etname) (.*)$", "^([Ss]etphoto)$", "^([Pp]romote) (.*)$", "^([Pp]romote)", -- "^([Hh]elpen)$", -- "^([Hh]elpfa)$", "^([Cc]lean) (.*)$", "^([Kk]ill) (chat)$", "^([Kk]ill) (realm)$", "^([Dd]emote) (.*)$", "^([Dd]emote)", "^([Ss]et) ([^%s]+) (.*)$", "^([Ss]ilent) (.*)$", "^([Ll]ock) (.*)$", "^([Ww]elcome) (.*)$", "^([Ss]etowner) (%d+)$", "^([Ss]etowner)", "^([Oo]wner)$", "^([Rr]es) (.*)$", "^([Ss]etgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^([Uu]nlock) (.*)$", "^([Ss]etflood) (%d+)$", "^([Ss]ettings)$", "^([Pp]ublic) (.*)$", "^([Mm]odlist)$", "^([Nn]ewlink)$", "^([Ll]ink)$", "^([Kk]ickinactive)$", "^([Kk]ickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
petrkr/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
chewi/Aquaria
files/scripts/maps/map_forestvision.lua
6
3437
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init() setCutscene(1,1) toggleDamageSprite(false) fade2(0, 1, 1, 1, 1) --return setOverrideVoiceFader(0.6) entity_setPosition(getNaija(), 0, 0) local camDummy = createEntity("Empty") local cam1 = getNode("CAM1") local cam2 = getNode("CAM2") local cam3 = getNode("CAM3") local campan1 = getNode("CAMPAN1") local campan2 = getNode("CAMPAN2") local campan3 = getNode("CAMPAN3") local camdestroy1 = getNode("CAMDESTROY1") local camdestroy2 = getNode("CAMDESTROY2") -- 1 overrideZoom(1) entity_warpToNode(camDummy, cam1) cam_toEntity(camDummy) watch(0.5) fade2(0, 0, 1, 1, 1) fadeIn(1) watch(1) local n = getNaija() entity_setPosition(n, 0, 0) playMusicOnce("DruniadDance") entity_setPosition(camDummy, node_x(cam2), node_y(cam2), 10, 0, 0, 1) overrideZoom(0.8, 10.1) watch(4) while entity_isInterpolating(camDummy) do watch(FRAME_TIME) end entity_setPosition(camDummy, node_x(cam3), node_y(cam3), 5, 0, 0, 1) overrideZoom(0.5, 11) while entity_isInterpolating(camDummy) do watch(FRAME_TIME) end fade2(1, 1, 1, 1, 1) watch(1) --2 overrideZoom(1) entity_warpToNode(camDummy, campan1) cam_toEntity(camDummy) watch(0.5) entity_setPosition(camDummy, node_x(campan2), node_y(campan2), 16, 0, 0, 1) overrideZoom(0.5, 21) fade2(0, 1, 1, 1, 1) watch(1) watch(7) voice("Naija_Vision_Forest") watch(8) entity_setPosition(camDummy, node_x(campan3), node_y(campan3), 11, 0, 0, 1) watch(10) fade2(1, 1) watch(1) --3 overrideZoom(1) entity_warpToNode(camDummy, camdestroy1) cam_toEntity(camDummy) watch(0.5) entity_setPosition(camDummy, node_x(camdestroy2), node_y(camdestroy2), 10, 0, 0, 0) overrideZoom(0.5, 8) fade2(0, 1) watch(1) shakeCamera(20, 10) for i = 1,(8/FRAME_TIME) do local x, y = getScreenCenter() local node = getNode("DESTROY") local ent = getFirstEntity() while ent ~= 0 do if not entity_isState(ent, STATE_DONE) and node_isEntityIn(node, ent) and entity_x(ent) < x+200 then entity_setState(ent, STATE_DONE) end ent = getNextEntity() end watch(FRAME_TIME) end fade2(1, 4) watch(4) fade2(0, 0.1) toggleBlackBars(1) showImage("Visions/Forest/00") --[[ voice("") watchForVoice() ]]-- watch(10) hideImage() overrideZoom(1, 7) watch(4) changeForm(FORM_NATURE) watch(3) setOverrideVoiceFader(-1) setCutscene(0) voice("Naija_Song_NatureForm") loadMap("Tree02", "NAIJADONE") --[[ fade2(0, 0.5, 1, 1, 1) cam_toEntity(n) ]]-- end
gpl-2.0
resistor58/deaths-gmod-server
Explosives And Nukes/lua/entities/sent_nuke_missile/init.lua
2
2690
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( 'shared.lua' ) local sndThrustLoop = Sound("Missile.Accelerate") local sndStop = Sound("ambient/_period.wav") local Arm = function(EntTable) EntTable.Armed = true EntTable.Entity:SetNWBool("armed",true) EntTable.PhysObj:EnableGravity(false) EntTable:SpawnTrail() EntTable:StartSounds() end function ENT:Initialize() self.Entity:SetModel( "models/Weapons/W_missile_closed.mdl" ) self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.PhysObj = self.Entity:GetPhysicsObject() if (self.PhysObj:IsValid()) then self.PhysObj:Wake() end self.Owner = self.Entity:GetVar("owner",Entity(1)) self.EmittingSound = false self.NextUse = 0 self.Armed = false self.Entity:SetNWBool("armed",false) timer.Simple(0.5,Arm,self) end function ENT:PhysicsCollide( data, physobj ) if self.Armed and data.Speed > 50 and data.DeltaTime > 0.15 then local nuke = ents.Create("sent_nuke") nuke:SetPos( self.Entity:GetPos() ) nuke:SetVar("owner",self.Owner) nuke:Spawn() nuke:Activate() self:StopSounds() self.Entity:Remove() end end function ENT:OnTakeDamage( dmginfo ) self.Entity:TakePhysicsDamage( dmginfo ) end function ENT:Use( activator, caller ) if self.NextUse > CurTime() then return end if self.Armed then self.Armed = false self.PhysObj:EnableGravity(true) self.Entity:SetNWBool("armed",false) self.Trail:Remove() self:StopSounds() else Arm(self) self.Owner = activator end self.NextUse = CurTime() + 0.3 end function ENT:Think() if self.Armed then self.PhysObj:SetVelocity(self.Entity:GetForward()*900) if self.Trail and self.Trail:IsValid() then self.Trail:SetPos(self.Entity:GetPos() - 16*self.Entity:GetForward()) self.Trail:SetLocalAngles(Vector(0,0,0)) else self:SpawnTrail() end self:StartSounds() end end function ENT:OnRemove() self:StopSounds() end function ENT:StartSounds() if not self.EmittingSound then self.Entity:EmitSound(sndThrustLoop) self.EmittingSound = true end end function ENT:StopSounds() if self.EmittingSound then self.Entity:StopSound(sndThrustLoop) self.Entity:EmitSound(sndStop) self.EmittingSound = false end end function ENT:SpawnTrail() self.Trail = ents.Create("env_rockettrail") self.Trail:SetPos(self.Entity:GetPos() - 16*self.Entity:GetForward()) self.Trail:SetParent(self.Entity) self.Trail:SetLocalAngles(Vector(0,0,0)) self.Trail:Spawn() end
gpl-3.0
zeta0134/LuaGB
love/panels/oam.lua
1
3357
local bit32 = require("bit") local oam = {} oam.width = 320 oam.init = function(gameboy) oam.canvas = love.graphics.newCanvas(160, 400) oam.gameboy = gameboy oam.sprite_imagedata = love.image.newImageData(8, 16) oam.sprite_image = love.graphics.newImage(oam.sprite_imagedata) oam.background_8x8_image = love.graphics.newImage("images/debug_oam_8x8_background.png") oam.background_8x16_image = love.graphics.newImage("images/debug_oam_8x16_background.png") end oam.draw_sprite = function(sprite_address, sx, sy, sprite_size) local graphics = oam.gameboy.graphics local io = oam.gameboy.io local ports = oam.gameboy.io.ports local sprite = graphics.cache.oam[(sprite_address - 0xFE00) / 4] local sprite_flags = graphics.oam[sprite_address + 3] for y = 0, (sprite_size - 1) do for x = 0, 7 do local color if y < 8 then if sprite_size == 8 then color = sprite.palette[sprite.tile[x][y]] else color = sprite.palette[sprite.upper_tile[x][y]] end else color = sprite.palette[sprite.lower_tile[x][y - 8]] end oam.sprite_imagedata:setPixel(sx + x, sy + y, color[1] / 255, color[2] / 255, color[3] / 255, 1) end end return sprite_tile, sprite.x, sprite.y, sprite_flags end oam.draw_sprites = function() -- Clear out the sprite buffer before we start oam.sprite_imagedata:mapPixel(function() return 0, 0, 0, 0 end) local cell_width = 40 local cell_height = 24 local sprites_per_row = 4 local sprite_scaling = 2 local sprite_size = 8 if oam.gameboy.graphics.registers.large_sprites then sprite_size = 16 sprite_scaling = 1 end love.graphics.setColor(1, 1, 1) if sprite_size == 8 then love.graphics.draw(oam.background_8x8_image, 0, 0) else love.graphics.draw(oam.background_8x16_image, 0, 0) end local x = 0 local y = 0 for i = 0, 39 do -- draw the sprite local tile, sprite_x, sprite_y, flags = oam.draw_sprite(0xFE00 + (i * 4), 0, 0, sprite_size) love.graphics.setCanvas(oam.canvas) love.graphics.push() love.graphics.scale(sprite_scaling, sprite_scaling) love.graphics.setColor(1, 1, 1) oam.sprite_image:replacePixels(oam.sprite_imagedata) love.graphics.draw(oam.sprite_image, ((3 + x * cell_width) / sprite_scaling), ((10 + y * cell_height) / sprite_scaling)) love.graphics.pop() -- draw info about this sprite love.graphics.setColor(0, 0, 0) love.graphics.print(string.format("X:%02X", bit32.band(sprite_x, 0xFF)), x * cell_width + cell_width - 17, y * cell_height + 9) love.graphics.print(string.format("Y:%02X", bit32.band(sprite_y, 0xFF)), x * cell_width + cell_width - 17, y * cell_height + 16) love.graphics.print(string.format("F:%02X", flags ), x * cell_width + cell_width - 17, y * cell_height + 23) x = x + 1 if x >= sprites_per_row then x = 0 y = y + 1 end end end oam.draw = function(x, y) love.graphics.setCanvas(oam.canvas) love.graphics.clear() love.graphics.setColor(0.75, 0.75, 0.75) love.graphics.rectangle("fill", 0, 0, 160, 400) oam.draw_sprites() love.graphics.setCanvas() -- reset to main FB love.graphics.setColor(1, 1, 1) love.graphics.push() love.graphics.scale(2, 2) love.graphics.draw(oam.canvas, x / 2, y / 2) love.graphics.pop() end return oam
bsd-3-clause
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/control/ComponentOrder.lua
3
3000
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/control/ComponentOrder.lua,v 1.3 2013/05/23 20:01:25 tantau Exp $ local declare = require "pgf.gd.interface.InterfaceToAlgorithms".declare --- -- @section subsubsection {Ordering the Components} -- -- The different connected components of the graph are collected in a -- list. The ordering of the nodes in this list can be configured using -- the following key. -- -- @end --- declare { key = "component order", type = "string", initial = "by first specified node", summary = [[" Selects a ``strategy'' for ordering the components. By default, they are ordered in the way they appear in the input. "]], documentation = [[" The following values are permissible for \meta{strategy} \begin{itemize} \item \declare{|by first specified node|} The components are ordered ``in the way they appear in the input specification of the graph''. More precisely, for each component consider the node that is first encountered in the description of the graph. Order the components in the same way as these nodes appear in the graph description. \item \declare{|increasing node number|} The components are ordered by increasing number of nodes. For components with the same number of nodes, the first node in each component is considered and they are ordered according to the sequence in which these nodes appear in the input. \item \declare{|decreasing node number|} As above, but in decreasing order. \end{itemize} "]], examples = { [[" \tikz \graph [tree layout, nodes={inner sep=1pt,draw,circle}, component order=by first specified node] { a, b, c, f -- g, c -- d -- e }; "]], [[" \tikz \graph [tree layout, nodes={inner sep=1pt,draw,circle}, component order=increasing node number] { a, b, c -- d -- e, f -- g }; "]] } } --- declare { key = "small components first", use = { { key = "component order", value = "increasing node number" } }, summary = [[" A shorthand for |component order=increasing node number|. "]] } --- declare { key = "large components first", use = { { key = "component order", value = "decreasing node number" }, }, summary = [[" A shorthand for |component order=decreasing node number|. "]], examples = [[" \tikz \graph [tree layout, nodes={inner sep=1pt,draw,circle}, large components first] { a, b, c -- d -- e, f -- g }; "]] } return Components
mit
tkdrob/Battle-Tag
Packages/TagThenShoot/Data/Script/Lua/UATagThenShoot.Ui.RoundLoop.lua
1
11087
--[[-------------------------------------------------------------------------- -- -- File: UATagThenShoot.Ui.RoundLoop.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: September 23, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "Ui/UIAFP" require "Ui/UILeaderboard" require "Ui/UIPlayerSlot" --[[ Class -----------------------------------------------------------------]] UATagThenShoot.Ui = UATagThenShoot.Ui or {} UATagThenShoot.Ui.RoundLoop = UTClass(UIMenuPage) -- __ctor ------------------------------------------------------------------- function UATagThenShoot.Ui.RoundLoop:__ctor(...) -- label self.uiLabel = self:AddComponent(UILabel:New(), "uiLabel") self.uiLabel.fontColor = UIComponent.colors.black self.uiLabel.rectangle = { 300, 0, 700, 80 } -- self.uiLabel.text = "Default game loop for " .. activity.name ------------------------------------------------ -- AFP TEST ------------------------------------------------ activity.uiAFP = self:AddComponent(UIAFP:New(), "uiAFP") activity.uiAFP:MoveTo(50, 40) -- current player self.player = activity.match.challengers[1] -- best score self.uiBestScorePanel = self:AddComponent(UIPanel:New(), "uiBestScorePanel") self.uiBestScorePanel.background = "base:texture/ui/components/uipanel05.tga" self.uiBestScorePanel.rectangle = { 520, 460, 920, 660 } self.uiBestScorePanel.uiTitlePanel = self.uiBestScorePanel:AddComponent(UIPanel:New(), "uiTitlePanel") self.uiBestScorePanel.uiTitlePanel.background = "base:texture/ui/components/uipanel08.tga" self.uiBestScorePanel.uiTitlePanel.rectangle = { 0, 0, 400, 30 } self.uiBestScorePanel.uiTitlePanel.color = UIComponent.colors.white self.uiBestScorePanel.uiTitleLabel = self.uiBestScorePanel:AddComponent(UILabel:New(), "uiTitleLabel") self.uiBestScorePanel.uiTitleLabel.fontColor = UIComponent.colors.orange self.uiBestScorePanel.uiTitleLabel.font = UIComponent.fonts.header self.uiBestScorePanel.uiTitleLabel.text = l"oth060" self.uiBestScorePanel.uiTitleLabel.rectangle = { 20, 2 } -- a list of 3 best players !! local index = 1 for i, player in ipairs(activity.players) do if (index <= 3 and player.data.baked.score > 0) then local slot = self.uiBestScorePanel:AddComponent(UIPlayerSlot:New(), "uiPlayerSlot" .. index) slot:SetPlayer(player) slot:MoveTo(70, 50 * index) -- draw text local label = slot:AddComponent(UILabel:New(), "uiLabel" .. index) label.fontColor = UIComponent.colors.black label.fontJustification = quartz.system.drawing.justification.center label.rectangle = { 255, 8, 295, 45 } label.text = player.data.baked.score index = index + 1 end end -- player slot self.uiPlayerPanel = self:AddComponent(UIPanel:New(), "uiPlayerPanel") self.uiPlayerPanel.background = "base:texture/ui/components/uipanel05.tga" self.uiPlayerPanel.rectangle = { 520, 50, 920, 170 } self.uiPlayerPanel.uiTitlePanel = self.uiPlayerPanel:AddComponent(UIPanel:New(), "uiTitlePanel") self.uiPlayerPanel.uiTitlePanel.background = "base:texture/ui/components/uipanel08.tga" self.uiPlayerPanel.uiTitlePanel.rectangle = { 0, 0, 400, 30 } self.uiPlayerPanel.uiTitleLabel = self.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel") self.uiPlayerPanel.uiTitleLabel.fontColor = UIComponent.colors.orange self.uiPlayerPanel.uiTitleLabel.font = UIComponent.fonts.header self.uiPlayerPanel.uiTitleLabel.text = l"oth066" self.uiPlayerPanel.uiTitleLabel.rectangle = { 20, 2 } self.uiPlayerPanel.uiPlayerPanel = self.uiPlayerPanel:AddComponent(UIPanel:New(), "uiPlayerPanel") self.uiPlayerPanel.uiPlayerPanel.background = "base:texture/ui/components/UIGridLine_Background01.tga" self.uiPlayerPanel.uiPlayerPanel.rectangle = { 80, 60, 380, 84 } self.uiPlayerPanel.uiPlayerHud = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiPlayerHud") self.uiPlayerPanel.uiPlayerHud.texture = "base:texture/ui/icons/32x/gunhud.tga" self.uiPlayerPanel.uiPlayerHud.rectangle = { 50, -5, 82, 27 } if (self.player.rfGunDevice) then self.uiPlayerPanel.uiPlayerClassId = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiPlayerClassId") self.uiPlayerPanel.uiPlayerClassId.fontJustification = quartz.system.drawing.justification.center + quartz.system.drawing.justification.singlelineverticalcenter self.uiPlayerPanel.uiPlayerClassId.rectangle = { 50, -5, 82, 27 } self.uiPlayerPanel.uiPlayerClassId.font = UIComponent.fonts.default self.uiPlayerPanel.uiPlayerClassId.fontColor = UIComponent.colors.orange self.uiPlayerPanel.uiPlayerClassId.text = self.player.rfGunDevice.classId end self.uiPlayerPanel.uiPlayerLabel = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel") self.uiPlayerPanel.uiPlayerLabel.fontColor = UIComponent.colors.darkgray self.uiPlayerPanel.uiPlayerLabel.font = UIComponent.fonts.header self.uiPlayerPanel.uiPlayerLabel.text = self.player.profile.name self.uiPlayerPanel.uiPlayerLabel.rectangle = { 100, 0 } if (game.settings.UiSettings.teamribbon == 2 and self.player.profile.team > 0) then self.uiPlayerPanel.uiPlayerPanelbackground = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiTitleLabel") self.uiPlayerPanel.uiPlayerPanelbackground.texture = "base:texture/ui/pictograms/48x/Team_" .. self.player.profile.team .. "_Circle.tga" self.uiPlayerPanel.uiPlayerPanelbackground.rectangle = { -49, -39, 49, 59 } end self.uiPlayerPanel.uiPlayerIcon = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiTitleLabel") self.uiPlayerPanel.uiPlayerIcon.texture = "base:texture/Avatars/256x/" .. self.player.profile.icon self.uiPlayerPanel.uiPlayerIcon.rectangle = { -64, -54, 64, 74 } self.uiPlayerPanel.uiPlayerScore = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel") self.uiPlayerPanel.uiPlayerScore.fontColor = UIComponent.colors.orange self.uiPlayerPanel.uiPlayerScore.font = UIComponent.fonts.header self.uiPlayerPanel.uiPlayerScore.text = activity.match.challengers[1].data.heap.score self.uiPlayerPanel.uiPlayerScore.rectangle = { 255, 0 } -- bases self.uiBasePanel = {} if (4 == activity.settings.numberOfBase) then self.baseRectangle = { { 520, 180, 710, 260 }, { 730, 180, 920, 260 }, { 520, 360, 710, 440 }, { 730, 360, 920, 440 }, } self.ubiconnectRectangle = { { 520, 270, 920, 350 }, } else self.baseRectangle = { { 520, 220, 710, 300 }, { 730, 220, 920, 300 }, } self.ubiconnectRectangle = { { 520, 330, 920, 410 }, } end for i = 1, activity.settings.numberOfBase do self.uiBasePanel[i] = self:AddComponent(UIPanel:New(), "uiBasePanel" .. "1") self.uiBasePanel[i].background = "base:texture/ui/components/uipanel05.tga" self.uiBasePanel[i].rectangle = self.baseRectangle[i] self.uiBasePanel[i].uiTitlePanel = self.uiBasePanel[i]:AddComponent(UIPanel:New(), "uiTitlePanel") self.uiBasePanel[i].uiTitlePanel.background = "base:texture/ui/components/uipanel07.tga" self.uiBasePanel[i].uiTitlePanel.rectangle = { 0, 30, 190, 50 } self.uiBasePanel[i].uiBaseName = self.uiBasePanel[i]:AddComponent(UILabel:New(), "uiTitleLabel") self.uiBasePanel[i].uiBaseName.fontColor = UIComponent.colors.darkgray self.uiBasePanel[i].uiBaseName.font = UIComponent.fonts.header self.uiBasePanel[i].uiBaseName.text = l("oth05" .. (5 + i)) self.uiBasePanel[i].uiBaseName.rectangle = { 5, 30 } self.uiBasePanel[i].uiBaseIcon = self.uiBasePanel[i]:AddComponent(UIPicture:New(), "uiTitleLabel") self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. "_White.tga" self.uiBasePanel[i].uiBaseIcon.rectangle = { 100, -5, 200, 85 } end -- UbiConnect self.uiUbiConnectPanel = self:AddComponent(UIPanel:New(), "uiBasePanel" .. "1") self.uiUbiConnectPanel.background = "base:texture/ui/components/uipanel05.tga" self.uiUbiConnectPanel.rectangle = self.ubiconnectRectangle[1] self.uiUbiConnectPanel.uiTitlePanel = self.uiUbiConnectPanel:AddComponent(UIPanel:New(), "uiTitlePanel") self.uiUbiConnectPanel.uiTitlePanel.background = "base:texture/ui/components/uipanel07.tga" self.uiUbiConnectPanel.uiTitlePanel.rectangle = { 0, 30, 400, 50 } self.uiUbiConnectPanel.uiBaseName = self.uiUbiConnectPanel:AddComponent(UILabel:New(), "uiTitleLabel") self.uiUbiConnectPanel.uiBaseName.fontColor = UIComponent.colors.darkgray self.uiUbiConnectPanel.uiBaseName.font = UIComponent.fonts.header self.uiUbiConnectPanel.uiBaseName.text = l"bas011" self.uiUbiConnectPanel.uiBaseName.rectangle = { 45, 30 } self.uiUbiConnectPanel.uiBaseIcon = self.uiUbiConnectPanel:AddComponent(UIPicture:New(), "uiTitleLabel") self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09_White.tga" self.uiUbiConnectPanel.uiBaseIcon.rectangle = { 220, -5, 320, 85 } end -- __dtor ------------------------------------------------------------------- function UATagThenShoot.Ui.RoundLoop:__dtor() end -- Onclose -------------------------------------------------------------------- function UATagThenShoot.Ui.RoundLoop:OnClose() self.player._DataChanged:Remove(self, self.OnDataChanged) end -- OnOpen -------------------------------------------------------------------- function UATagThenShoot.Ui.RoundLoop:OnOpen() self.player._DataChanged:Add(self, self.OnDataChanged) self.uiBasePanel[1].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF03.tga" end -- OnDataChanged ------------------------------------------------------------- function UATagThenShoot.Ui.RoundLoop:OnDataChanged(_entity, _key, _value) if ("state" == _key) then for i = 1, activity.settings.numberOfBase do if (_value and self.player.data.heap.state == i - 1) then self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. ".tga" else self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. "_White.tga" end end if (not _value) then self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09.tga" else self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09_White.tga" end elseif ("score" == _key) then self.uiPlayerPanel.uiPlayerScore.text = self.player.data.heap.score end end
mit
chewi/Aquaria
files/scripts/entities/creatorshadow.lua
6
1740
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 function init(me) setupEntity(me) entity_setEntityLayer(me, 1) entity_setTexture(me, "creator-shadow") entity_setEntityType(me, ET_NEUTRAL) entity_setAllDamageTargets(me, false) entity_setSegs(me, 2, 32, 0.3, 0.3, -0.018, 0, 6, 1) entity_setState(me, STATE_IDLE) entity_scale(me, 3, 3) entity_alpha(me, 0) entity_alpha(me, 1, 1) end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) end function update(me, dt) entity_handleShotCollisionsSkeletal(me) entity_updateMovement(me, dt) end function enterState(me) end function exitState(me) end function damage(me, attacker, bone, damageType, dmg) return false end function animationKey(me, key) end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
resistor58/deaths-gmod-server
wire/lua/entities/base_wire_entity/cl_init.lua
1
1469
include("shared.lua") ENT.RenderGroup = RENDERGROUP_OPAQUE//RENDERGROUP_TRANSLUCENT//RENDERGROUP_BOTH local wire_drawoutline = CreateClientConVar("wire_drawoutline", 1, true, false) local wire_drawoutline_bool = wire_drawoutline:GetBool() cvars.AddChangeCallback("wire_drawoutline", function(...) return wire_changey(...) end) function wire_changey(cvar, prev, new) if prev == new then return end wire_drawoutline_bool = wire_drawoutline:GetBool() end function ENT:Draw() self:DoNormalDraw() Wire_Render(self.Entity) end function ENT:DoNormalDraw() local trace = LocalPlayer():GetEyeTrace() local looked_at = trace.Entity == self.Entity and trace.Fraction*16384 < 256 if wire_drawoutline_bool and looked_at then if self.RenderGroup == RENDERGROUP_OPAQUE then self.OldRenderGroup = self.RenderGroup self.RenderGroup = RENDERGROUP_TRANSLUCENT end self:DrawEntityOutline(1.0) self:DrawModel() else if self.OldRenderGroup then self.RenderGroup = self.OldRenderGroup self.OldRenderGroup = nil end self:DrawModel() end if looked_at then if self:GetOverlayText() ~= "" then AddWorldTip(self:EntIndex(),self:GetOverlayText(),0.5,self:GetPos(),e) end end end function ENT:Think() if (CurTime() >= (self.NextRBUpdate or 0)) then self.NextRBUpdate = CurTime() + math.random(30,100)/10 --update renderbounds every 3 to 10 seconds Wire_UpdateRenderBounds(self.Entity) end end
gpl-3.0
oratory/wago.io
backend/api/lua/wa2json.lua
1
2778
dofile( "./wago.lua" ) local JSON = (loadfile "./json.lua")() function table.show(t, name, indent) local cart -- a container local autoref -- for self references --[[ counts the number of elements in a table local function tablecount(t) local n = 0 for _, _ in pairs(t) do n = n+1 end return n end ]] -- (RiciLake) returns true if the table is empty local function isemptytable(t) return next(t) == nil end local function basicSerialize (o) local so = tostring(o) if type(o) == "function" then local info = debug.getinfo(o, "S") -- info.name is nil because o is not a calling level if info.what == "C" then return string.format("%q", so .. ", C function") else -- the information is defined through lines return string.format("%q", so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source) end elseif type(o) == "number" or type(o) == "boolean" then return so else return string.format("%q", so) end end local function addtocart (value, name, indent, saved, field) indent = indent or "" saved = saved or {} field = field or name cart = cart .. indent .. field if type(value) ~= "table" then cart = cart .. " = " .. basicSerialize(value) .. ";\n" else if saved[value] then cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n" autoref = autoref .. name .. " = " .. saved[value] .. ";\n" else saved[value] = name --if tablecount(value) == 0 then if isemptytable(value) then cart = cart .. " = {};\n" else cart = cart .. " = {\n" for k, v in pairs(value) do k = basicSerialize(k) local fname = string.format("%s[%s]", name, k) field = string.format("[%s]", k) -- three spaces between levels addtocart(v, fname, indent .. " ", saved, field) end cart = cart .. indent .. "};\n" end end end end name = name or "__AURA__" if type(t) ~= "table" then return name .. " = " .. basicSerialize(t) end cart, autoref = "", "" addtocart(t, name, indent) return cart .. autoref end local t if string.find(arg[1], "/tmp/") == nil then t = StringToTable(arg[1], false) else local f = io.open(arg[1], "r") t = f:read() f:close() t = StringToTable(t, false) end --print(t) if (t) then print(JSON:encode(t)) end
mit
lsmoura/dtb
inc/LibSharedMedia-3.0/LibSharedMedia-3.0.lua
1
8990
--[[ Name: LibSharedMedia-3.0 Revision: $Revision: 62 $ Author: Elkano (elkano@gmx.de) Inspired By: SurfaceLib by Haste/Otravi (troeks@gmail.com) Website: http://www.wowace.com/projects/libsharedmedia-3-0/ Description: Shared handling of media data (fonts, sounds, textures, ...) between addons. Dependencies: LibStub, CallbackHandler-1.0 License: LGPL v2.1 ]] local MAJOR, MINOR = "LibSharedMedia-3.0", 100001 -- increase manualy on changes local lib = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end local _G = getfenv(0) local pairs = _G.pairs local type = _G.type local band = _G.bit.band local table_insert = _G.table.insert local table_sort = _G.table.sort local locale = GetLocale() local locale_is_western local LOCALE_MASK = 0 lib.LOCALE_BIT_koKR = 1 lib.LOCALE_BIT_ruRU = 2 lib.LOCALE_BIT_zhCN = 4 lib.LOCALE_BIT_zhTW = 8 lib.LOCALE_BIT_western = 128 local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") lib.callbacks = lib.callbacks or CallbackHandler:New(lib) lib.DefaultMedia = lib.DefaultMedia or {} lib.MediaList = lib.MediaList or {} lib.MediaTable = lib.MediaTable or {} lib.MediaType = lib.MediaType or {} lib.OverrideMedia = lib.OverrideMedia or {} local defaultMedia = lib.DefaultMedia local mediaList = lib.MediaList local mediaTable = lib.MediaTable local overrideMedia = lib.OverrideMedia -- create mediatype constants lib.MediaType.BACKGROUND = "background" -- background textures lib.MediaType.BORDER = "border" -- border textures lib.MediaType.FONT = "font" -- fonts lib.MediaType.STATUSBAR = "statusbar" -- statusbar textures lib.MediaType.SOUND = "sound" -- sound files -- populate lib with default Blizzard data -- BACKGROUND if not lib.MediaTable.background then lib.MediaTable.background = {} end lib.MediaTable.background["Blizzard Dialog Background"] = [[Interface\DialogFrame\UI-DialogBox-Background]] lib.MediaTable.background["Blizzard Dialog Background Dark"] = [[Interface\DialogFrame\UI-DialogBox-Background-Dark]] lib.MediaTable.background["Blizzard Dialog Background Gold"] = [[Interface\DialogFrame\UI-DialogBox-Gold-Background]] lib.MediaTable.background["Blizzard Low Health"] = [[Interface\FullScreenTextures\LowHealth]] lib.MediaTable.background["Blizzard Marble"] = [[Interface\FrameGeneral\UI-Background-Marble]] lib.MediaTable.background["Blizzard Out of Control"] = [[Interface\FullScreenTextures\OutOfControl]] lib.MediaTable.background["Blizzard Parchment"] = [[Interface\AchievementFrame\UI-Achievement-Parchment-Horizontal]] lib.MediaTable.background["Blizzard Parchment 2"] = [[Interface\AchievementFrame\UI-GuildAchievement-Parchment-Horizontal]] lib.MediaTable.background["Blizzard Rock"] = [[Interface\FrameGeneral\UI-Background-Rock]] lib.MediaTable.background["Blizzard Tabard Background"] = [[Interface\TabardFrame\TabardFrameBackground]] lib.MediaTable.background["Blizzard Tooltip"] = [[Interface\Tooltips\UI-Tooltip-Background]] lib.MediaTable.background["Solid"] = [[Interface\Buttons\WHITE8X8]] -- BORDER if not lib.MediaTable.border then lib.MediaTable.border = {} end lib.MediaTable.border["None"] = [[Interface\None]] lib.MediaTable.border["Blizzard Achievement Wood"] = [[Interface\AchievementFrame\UI-Achievement-WoodBorder]] lib.MediaTable.border["Blizzard Chat Bubble"] = [[Interface\Tooltips\ChatBubble-Backdrop]] lib.MediaTable.border["Blizzard Dialog"] = [[Interface\DialogFrame\UI-DialogBox-Border]] lib.MediaTable.border["Blizzard Dialog Gold"] = [[Interface\DialogFrame\UI-DialogBox-Gold-Border]] lib.MediaTable.border["Blizzard Party"] = [[Interface\CHARACTERFRAME\UI-Party-Border]] lib.MediaTable.border["Blizzard Tooltip"] = [[Interface\Tooltips\UI-Tooltip-Border]] -- FONT if not lib.MediaTable.font then lib.MediaTable.font = {} end local SML_MT_font = lib.MediaTable.font if locale == "koKR" then LOCALE_MASK = lib.LOCALE_BIT_koKR -- SML_MT_font["굵은 글꼴"] = [[Fonts\2002B.TTF]] SML_MT_font["기본 글꼴"] = [[Fonts\2002.TTF]] SML_MT_font["데미지 글꼴"] = [[Fonts\K_Damage.TTF]] SML_MT_font["퀘스트 글꼴"] = [[Fonts\K_Pagetext.TTF]] -- lib.DefaultMedia["font"] = "기본 글꼴" -- someone from koKR please adjust if needed -- elseif locale == "zhCN" then LOCALE_MASK = lib.LOCALE_BIT_zhCN -- SML_MT_font["伤害数字"] = [[Fonts\ZYKai_C.ttf]] SML_MT_font["默认"] = [[Fonts\ZYKai_T.ttf]] SML_MT_font["聊天"] = [[Fonts\ZYHei.ttf]] -- lib.DefaultMedia["font"] = "默认" -- someone from zhCN please adjust if needed -- elseif locale == "zhTW" then LOCALE_MASK = lib.LOCALE_BIT_zhTW -- SML_MT_font["提示訊息"] = [[Fonts\bHEI00M.ttf]] SML_MT_font["聊天"] = [[Fonts\bHEI01B.ttf]] SML_MT_font["傷害數字"] = [[Fonts\bKAI00M.ttf]] SML_MT_font["預設"] = [[Fonts\bLEI00D.ttf]] -- lib.DefaultMedia["font"] = "預設" -- someone from zhTW please adjust if needed elseif locale == "ruRU" then LOCALE_MASK = lib.LOCALE_BIT_ruRU -- SML_MT_font["Arial Narrow"] = [[Fonts\ARIALN.TTF]] SML_MT_font["Friz Quadrata TT"] = [[Fonts\FRIZQT__.TTF]] SML_MT_font["Morpheus"] = [[Fonts\MORPHEUS.TTF]] SML_MT_font["Nimrod MT"] = [[Fonts\NIM_____.ttf]] SML_MT_font["Skurri"] = [[Fonts\SKURRI.TTF]] -- lib.DefaultMedia.font = "Friz Quadrata TT" -- else LOCALE_MASK = lib.LOCALE_BIT_western locale_is_western = true -- SML_MT_font["Arial Narrow"] = [[Fonts\ARIALN.TTF]] SML_MT_font["Friz Quadrata TT"] = [[Fonts\FRIZQT__.TTF]] SML_MT_font["Morpheus"] = [[Fonts\MORPHEUS.TTF]] SML_MT_font["Skurri"] = [[Fonts\SKURRI.TTF]] -- lib.DefaultMedia.font = "Friz Quadrata TT" -- end -- STATUSBAR if not lib.MediaTable.statusbar then lib.MediaTable.statusbar = {} end lib.MediaTable.statusbar["Blizzard"] = [[Interface\TargetingFrame\UI-StatusBar]] lib.MediaTable.statusbar["Blizzard Character Skills Bar"] = [[Interface\PaperDollInfoFrame\UI-Character-Skills-Bar]] lib.DefaultMedia.statusbar = "Blizzard" -- SOUND if not lib.MediaTable.sound then lib.MediaTable.sound = {} end lib.MediaTable.sound["None"] = [[Interface\Quiet.ogg]] -- Relies on the fact that PlaySound[File] doesn't error on non-existing input. lib.DefaultMedia.sound = "None" local function rebuildMediaList(mediatype) local mtable = mediaTable[mediatype] if not mtable then return end if not mediaList[mediatype] then mediaList[mediatype] = {} end local mlist = mediaList[mediatype] -- list can only get larger, so simply overwrite it local i = 0 for k in pairs(mtable) do i = i + 1 mlist[i] = k end table_sort(mlist) end function lib:Register(mediatype, key, data, langmask) if type(mediatype) ~= "string" then error(MAJOR..":Register(mediatype, key, data, langmask) - mediatype must be string, got "..type(mediatype)) end if type(key) ~= "string" then error(MAJOR..":Register(mediatype, key, data, langmask) - key must be string, got "..type(key)) end mediatype = mediatype:lower() if mediatype == lib.MediaType.FONT and ((langmask and band(langmask, LOCALE_MASK) == 0) or not (langmask or locale_is_western)) then return false end if not mediaTable[mediatype] then mediaTable[mediatype] = {} end local mtable = mediaTable[mediatype] if mtable[key] then return false end mtable[key] = data rebuildMediaList(mediatype) self.callbacks:Fire("LibSharedMedia_Registered", mediatype, key) return true end function lib:Fetch(mediatype, key, noDefault) local mtt = mediaTable[mediatype] local overridekey = overrideMedia[mediatype] local result = mtt and ((overridekey and mtt[overridekey] or mtt[key]) or (not noDefault and defaultMedia[mediatype] and mtt[defaultMedia[mediatype]])) or nil return result end function lib:IsValid(mediatype, key) return mediaTable[mediatype] and (not key or mediaTable[mediatype][key]) and true or false end function lib:HashTable(mediatype) return mediaTable[mediatype] end function lib:List(mediatype) if not mediaTable[mediatype] then return nil end if not mediaList[mediatype] then rebuildMediaList(mediatype) end return mediaList[mediatype] end function lib:GetGlobal(mediatype) return overrideMedia[mediatype] end function lib:SetGlobal(mediatype, key) if not mediaTable[mediatype] then return false end overrideMedia[mediatype] = (key and mediaTable[mediatype][key]) and key or nil self.callbacks:Fire("LibSharedMedia_SetGlobal", mediatype, overrideMedia[mediatype]) return true end function lib:GetDefault(mediatype) return defaultMedia[mediatype] end function lib:SetDefault(mediatype, key) if mediaTable[mediatype] and mediaTable[mediatype][key] and not defaultMedia[mediatype] then defaultMedia[mediatype] = key return true else return false end end
unlicense
mSenyor/sl4a
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
bestroidd/advan
bot/WaderTGbot.lua
1
15203
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") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) print(receiver) --vardump(msg) --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) -- See plugins/isup.lua as an example for cron _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 < os.time() - 5 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 --send_large_msg(*group id*, msg.text) *login code will be sent to GroupID* return false 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("Sudo 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 = { "admin", "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "invite", "all", "me", "leave_ban", "supergroup", "whitelist", "msg_checks", "plugins", "badword", "bot-lock", "clash_of_clan", "cleaner", "infull", "instagram", "linkpv", "lock-forward", "photo2sticker", "sticker2photo", "text2photo", "text2sticker", "server", "voice", "wai" }, sudo_users = {204876190},--Sudo users moderation = {data = 'data/moderation.json'}, about_text = [[ Sudo: @Advan_sudo ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [group|sgroup] [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !settings [group|sgroup] [GroupID] Set settings for GroupID !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] 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 !support Promote user to support !-support Demote user from support !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] **You can use "#", "!", or "/" to begin all commands *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands sudo: @Advan_sudo ]], 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 Returns help text !lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] Lock group settings *rtl: Kick user if Right To Left Char. is in name* !unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] Unlock group settings *rtl: Kick user if Right To Left Char. is in name* !mute [all|audio|gifs|photo|video] mute group message types *If "muted" message type: user is kicked if message type is posted !unmute [all|audio|gifs|photo|video] Unmute group message types *If "unmuted" message type: user is not kicked if message type is posted !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !muteslist Returns mutes for chat !muteuser [username] Mute a user in chat *user is kicked if they talk *only owners can mute | mods and owners can unmute !mutelist Returns list of muted users in chat !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 "!res @username" !log Returns group logs !banlist will return group ban list **You can use "#", "!", or "/" to begin all commands *Only owner and mods 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 sudo: @Advan_sudo ]], help_text_super =[[ #Help: ========================= #info About the SuperGroup info ========================= #infull About the you infull ========================= #admins SuperGroup admins list ========================= #setadmin Set SuperGroup admins ========================= #owner Show owner of SuperGroup ========================= #setowner Set the SuperGroup owner ========================= #modlist Show moderators list ========================= #bots List bots in SuperGroup ========================= #bot[lock,unlock] Bot[lock,unlock] the SuperGroup ========================= #who List all users in SuperGroup ========================= #block kick a user from SuperGroup +Added user to blocked list+ ========================= #ban Ban user from the SuperGroup +Only with[id+user]+ ========================= #unban Unban user from the SuperGroup +Only with[id+user]+ ========================= #id SuperGroup ID or user ID +For user ID:#id @username or reply by: #id+ ========================= #id from Get ID of user massage is forwarded from ========================= #kickme Kick you from SuperGroup ========================= #promote[@username+id] Promote a SuperGroup moderator ========================= #demote[@username+id] Demote a SuperGroup moderator ========================= #setname [group name] Set the chat name ========================= #setphoto Set the chat photo +Then photo and send the+ ========================= #setrules[rules] Set the chat rules ========================= #setabout Set the chat about ========================= #save [value] <text> Set extra info for chat ========================= #get[value] Retrieves extra info for chat by value ========================= #newlink Create group link ========================= #link Group the link ========================= #linkpv Send SuperGroup link private ========================= #rules Chat the rules ========================= #lock[links+flood+spam+arabic+member+rtl+sticker+contacts+strict+tgservice+forward] Lock SuperGroup settings ========================= #unlock[links+flood+spam+arabic+member+rtl+sticker+contacts+strict+tgservice+forward] Unlock SuperGroup settings ========================= #mute[all+audio+gifs+photo+video+text+service] Mute SuperGroup massage types ========================= #unmute[all+audio+gifs+photo+video+text+service] Unmute SuperGroup massage types ========================= #setflood[value] Set[value] as flood sensitivity ========================= #settins SuperGroup settings ========================= #muteslist SuperGroup mutes ========================= #muteuser[@username+id] Mute a user in SuperGroup +#muteuser[@username+id]remove mutelist+ ========================= #mutelist SuperGroup muted user list ========================= #banlist SuperGroup ban list ========================= #clean[rules+about+modlist+mutelist] Cleaned ========================= #del Deletes a massage by reply ========================= #public[yes+no] Set SuperGroup visibility in pm #chats or #chatlist commands ========================= #res[@username] Returns user name and id by @username ========================= #log Returns SuperGroup logs ========================= #addword[text] Added the badword +If the desired word is cleared+ ========================= #badwords SuperGroup badword list ========================= #rw[text] clear[text]from list badword ========================= #clearbadwords Cleaned badword list ========================= #clantag[tag] Specifications clan a door clsh of clan ========================= #music[truk name] Find songs to ========================= #me Returns your specifications ========================= #tophoto Become stickers to photos ========================= #tosticker Turn photos into stikers ========================= #conv[text] Text to photos ========================= #sticker[text] Text-to-stickers ========================= #wai To show office user ========================= #voice[text] Text-to-voice ========================= *Only from markes "!" , "/" , "#" use* Sudo: @Advan_sudo ]], } 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) --vardump (chat) 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
chewi/Aquaria
files/scripts/maps/_unused/node_spikes.lua
6
1273
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 function init(me) end function update(me, dt) if v.n == 0 then v.n = getNaija() end if node_isEntityIn(me, v.n) then entity_damage(v.n, 0, 0.5) local nx, ny = getWallNormal(node_x(me), node_y(me)) if not(nx == 0 and ny == 0) then nx, ny = vector_setLength(nx, ny, 800) --entity_push(v.n, nx, ny, 0.25) entity_addVel(v.n, nx, ny) end end end
gpl-2.0
joehanchoi/hammerspoon
extensions/http/init.lua
8
23616
-- Simple loader for the Objective C code local http = require("hs.http.internal") local utf8 = require("hs.utf8") local fnutils = require("hs.fnutils") --- === hs.http === --- --- Perform HTTP requests --- hs.http.get(url, headers) -> int, string, table --- Function --- Sends an HTTP GET request to a URL --- --- Parameters --- * url - A string containing the URL to retrieve --- * headers - A table containing string keys and values representing the request headers, or nil to add no headers --- --- Returns: --- * A number containing the HTTP response status --- * A string containing the response body --- * A table containing the response headers --- --- Notes: --- * This function is synchronous and will therefore block all other Lua execution while the request is in progress, you are encouraged to use the asynchronous functions http.get = function(url, headers) return http.doRequest(url, "GET", nil, headers) end --- hs.http.post(url, data, headers) -> int, string, table --- Function --- Sends an HTTP POST request to a URL --- --- Parameters --- * url - A string containing the URL to submit to --- * data - A string containing the request body, or nil to send no body --- * headers - A table containing string keys and values representing the request headers, or nil to add no headers --- --- Returns: --- * A number containing the HTTP response status --- * A string containing the response body --- * A table containing the response headers --- --- Notes: --- * This function is synchronous and will therefore block all other Lua execution while the request is in progress, you are encouraged to use the asynchronous functions http.post = function(url, data, headers) return http.doRequest(url, "POST", data,headers) end --- hs.http.asyncGet(url, headers, callback) --- Function --- Sends an HTTP GET request asynchronously --- --- Parameters: --- * url - A string containing the URL to retrieve --- * headers - A table containing string keys and values representing the request headers, or nil to add no headers --- * callback - A function to be called when the request succeeds or fails. The function will be passed three parameters: --- * A number containing the HTTP response status --- * A string containing the response body --- * A table containing the response headers --- --- Notes: --- * If the request fails, the callback function's first parameter will be negative and the second parameter will contain an error message. The third parameter will be nil http.asyncGet = function(url, headers, callback) http.doAsyncRequest(url, "GET", nil, headers, callback) end --- hs.http.asyncPost(url, data, headers, callback) --- Function --- Sends an HTTP POST request asynchronously --- --- Parameters: --- * url - A string containing the URL to submit to --- * data - A string containing the request body, or nil to send no body --- * headers - A table containing string keys and values representing the request headers, or nil to add no headers --- * callback - A function to be called when the request succeeds or fails. The function will be passed three parameters: --- * A number containing the HTTP response status --- * A string containing the response body --- * A table containing the response headers --- --- Notes: --- * If the request fails, the callback function's first parameter will be negative and the second parameter will contain an error message. The third parameter will be nil http.asyncPost = function(url, data, headers, callback) http.doAsyncRequest(url, "POST", data, headers, callback) end --- hs.http.htmlEntities[] --- Variable --- A collection of common HTML Entities (&whatever;) and their UTF8 equivalents. To retrieve the UTF8 sequence for a given entity, reference the table as `hs.http.htmlEntities["&key;"]` where `key` is the text of the entity's name or a numeric reference like `#number`. --- --- Notes: --- * This list is likely not complete. It is based on the list of common entities described at http://www.freeformatter.com/html-entities.html. --- * Additional entities can be temporarily added via the `hs.http.registerEntity(...)` function. If you feel you have a more official list of entities which contains items which are currently not included by default, please open up an issue at https://github.com/Hammerspoon/hammerspoon and your link will be considered. --- * To see a list of the currently defined entities, a __tostring meta-method is included so that referencing the table directly as a string will return the current definitions. --- * For reference, this meta-method is essentially the following: --- --- for i,v in hs.fnutils.sortByKeys(hs.http.htmlEntities) do print(string.format("%-10s %-10s %s\n", i, "&#"..tostring(hs.utf8.codepoint(v))..";", v)) end --- --- * Note that this list will not include the numeric conversion of entities (e.g. &#65;), as this is handled by an __index metamethod to allow for all possible numeric values. http.htmlEntities = setmetatable({}, { __index = function(object, key) if type(key) == "string" then local num = key:match("^&#(%d+);$") if num and tonumber(num) then return utf8.codepointToUTF8(tonumber(num)) else return nil end else return nil end end, __tostring = function(object) local output = "" for i,v in fnutils.sortByKeys(object) do output = output..string.format("%-10s %-10s %s\n", i, "&#"..tostring(utf8.codepoint(v))..";", v) end return output end }) http.htmlEntities["&Aacute;"] = utf8.codepointToUTF8(193) http.htmlEntities["&aacute;"] = utf8.codepointToUTF8(225) http.htmlEntities["&Acirc;"] = utf8.codepointToUTF8(194) http.htmlEntities["&acirc;"] = utf8.codepointToUTF8(226) http.htmlEntities["&acute;"] = utf8.codepointToUTF8(180) http.htmlEntities["&AElig;"] = utf8.codepointToUTF8(198) http.htmlEntities["&aelig;"] = utf8.codepointToUTF8(230) http.htmlEntities["&Agrave;"] = utf8.codepointToUTF8(192) http.htmlEntities["&agrave;"] = utf8.codepointToUTF8(224) http.htmlEntities["&Alpha;"] = utf8.codepointToUTF8(913) http.htmlEntities["&alpha;"] = utf8.codepointToUTF8(945) http.htmlEntities["&amp;"] = utf8.codepointToUTF8(38) http.htmlEntities["&and;"] = utf8.codepointToUTF8(8743) http.htmlEntities["&ang;"] = utf8.codepointToUTF8(8736) http.htmlEntities["&Aring;"] = utf8.codepointToUTF8(197) http.htmlEntities["&aring;"] = utf8.codepointToUTF8(229) http.htmlEntities["&asymp;"] = utf8.codepointToUTF8(8776) http.htmlEntities["&Atilde;"] = utf8.codepointToUTF8(195) http.htmlEntities["&atilde;"] = utf8.codepointToUTF8(227) http.htmlEntities["&Auml;"] = utf8.codepointToUTF8(196) http.htmlEntities["&auml;"] = utf8.codepointToUTF8(228) http.htmlEntities["&bdquo;"] = utf8.codepointToUTF8(8222) http.htmlEntities["&Beta;"] = utf8.codepointToUTF8(914) http.htmlEntities["&beta;"] = utf8.codepointToUTF8(946) http.htmlEntities["&brvbar;"] = utf8.codepointToUTF8(166) http.htmlEntities["&bull;"] = utf8.codepointToUTF8(8226) http.htmlEntities["&cap;"] = utf8.codepointToUTF8(8745) http.htmlEntities["&Ccedil;"] = utf8.codepointToUTF8(199) http.htmlEntities["&ccedil;"] = utf8.codepointToUTF8(231) http.htmlEntities["&cedil;"] = utf8.codepointToUTF8(184) http.htmlEntities["&cent;"] = utf8.codepointToUTF8(162) http.htmlEntities["&Chi;"] = utf8.codepointToUTF8(935) http.htmlEntities["&chi;"] = utf8.codepointToUTF8(967) http.htmlEntities["&circ;"] = utf8.codepointToUTF8(710) http.htmlEntities["&clubs;"] = utf8.codepointToUTF8(9827) http.htmlEntities["&cong;"] = utf8.codepointToUTF8(8773) http.htmlEntities["&copy;"] = utf8.codepointToUTF8(169) http.htmlEntities["&crarr;"] = utf8.codepointToUTF8(8629) http.htmlEntities["&cup;"] = utf8.codepointToUTF8(8746) http.htmlEntities["&curren;"] = utf8.codepointToUTF8(164) http.htmlEntities["&dagger;"] = utf8.codepointToUTF8(8224) http.htmlEntities["&Dagger;"] = utf8.codepointToUTF8(8225) http.htmlEntities["&darr;"] = utf8.codepointToUTF8(8595) http.htmlEntities["&deg;"] = utf8.codepointToUTF8(176) http.htmlEntities["&Delta;"] = utf8.codepointToUTF8(916) http.htmlEntities["&delta;"] = utf8.codepointToUTF8(948) http.htmlEntities["&diams;"] = utf8.codepointToUTF8(9830) http.htmlEntities["&divide;"] = utf8.codepointToUTF8(247) http.htmlEntities["&Eacute;"] = utf8.codepointToUTF8(201) http.htmlEntities["&eacute;"] = utf8.codepointToUTF8(233) http.htmlEntities["&Ecirc;"] = utf8.codepointToUTF8(202) http.htmlEntities["&ecirc;"] = utf8.codepointToUTF8(234) http.htmlEntities["&Egrave;"] = utf8.codepointToUTF8(200) http.htmlEntities["&egrave;"] = utf8.codepointToUTF8(232) http.htmlEntities["&empty;"] = utf8.codepointToUTF8(8709) http.htmlEntities["&emsp;"] = utf8.codepointToUTF8(8195) http.htmlEntities["&ensp;"] = utf8.codepointToUTF8(8194) http.htmlEntities["&Epsilon;"] = utf8.codepointToUTF8(917) http.htmlEntities["&epsilon;"] = utf8.codepointToUTF8(949) http.htmlEntities["&equiv;"] = utf8.codepointToUTF8(8801) http.htmlEntities["&Eta;"] = utf8.codepointToUTF8(919) http.htmlEntities["&eta;"] = utf8.codepointToUTF8(951) http.htmlEntities["&ETH;"] = utf8.codepointToUTF8(208) http.htmlEntities["&eth;"] = utf8.codepointToUTF8(240) http.htmlEntities["&Euml;"] = utf8.codepointToUTF8(203) http.htmlEntities["&euml;"] = utf8.codepointToUTF8(235) http.htmlEntities["&euro;"] = utf8.codepointToUTF8(8364) http.htmlEntities["&exist;"] = utf8.codepointToUTF8(8707) http.htmlEntities["&fnof;"] = utf8.codepointToUTF8(402) http.htmlEntities["&forall;"] = utf8.codepointToUTF8(8704) http.htmlEntities["&frac12;"] = utf8.codepointToUTF8(189) http.htmlEntities["&frac14;"] = utf8.codepointToUTF8(188) http.htmlEntities["&frac34;"] = utf8.codepointToUTF8(190) http.htmlEntities["&Gamma;"] = utf8.codepointToUTF8(915) http.htmlEntities["&gamma;"] = utf8.codepointToUTF8(947) http.htmlEntities["&ge;"] = utf8.codepointToUTF8(8805) http.htmlEntities["&gt;"] = utf8.codepointToUTF8(62) http.htmlEntities["&harr;"] = utf8.codepointToUTF8(8596) http.htmlEntities["&hearts;"] = utf8.codepointToUTF8(9829) http.htmlEntities["&hellip;"] = utf8.codepointToUTF8(8230) http.htmlEntities["&Iacute;"] = utf8.codepointToUTF8(205) http.htmlEntities["&iacute;"] = utf8.codepointToUTF8(237) http.htmlEntities["&Icirc;"] = utf8.codepointToUTF8(206) http.htmlEntities["&icirc;"] = utf8.codepointToUTF8(238) http.htmlEntities["&iexcl;"] = utf8.codepointToUTF8(161) http.htmlEntities["&Igrave;"] = utf8.codepointToUTF8(204) http.htmlEntities["&igrave;"] = utf8.codepointToUTF8(236) http.htmlEntities["&infin;"] = utf8.codepointToUTF8(8734) http.htmlEntities["&int;"] = utf8.codepointToUTF8(8747) http.htmlEntities["&Iota;"] = utf8.codepointToUTF8(921) http.htmlEntities["&iota;"] = utf8.codepointToUTF8(953) http.htmlEntities["&iquest;"] = utf8.codepointToUTF8(191) http.htmlEntities["&isin;"] = utf8.codepointToUTF8(8712) http.htmlEntities["&Iuml;"] = utf8.codepointToUTF8(207) http.htmlEntities["&iuml;"] = utf8.codepointToUTF8(239) http.htmlEntities["&Kappa;"] = utf8.codepointToUTF8(922) http.htmlEntities["&kappa;"] = utf8.codepointToUTF8(954) http.htmlEntities["&Lambda;"] = utf8.codepointToUTF8(923) http.htmlEntities["&lambda;"] = utf8.codepointToUTF8(955) http.htmlEntities["&laquo;"] = utf8.codepointToUTF8(171) http.htmlEntities["&larr;"] = utf8.codepointToUTF8(8592) http.htmlEntities["&lceil;"] = utf8.codepointToUTF8(8968) http.htmlEntities["&ldquo;"] = utf8.codepointToUTF8(8220) http.htmlEntities["&le;"] = utf8.codepointToUTF8(8804) http.htmlEntities["&lfloor;"] = utf8.codepointToUTF8(8970) http.htmlEntities["&lowast;"] = utf8.codepointToUTF8(8727) http.htmlEntities["&loz;"] = utf8.codepointToUTF8(9674) http.htmlEntities["&lrm;"] = utf8.codepointToUTF8(8206) http.htmlEntities["&lsaquo;"] = utf8.codepointToUTF8(8249) http.htmlEntities["&lsquo;"] = utf8.codepointToUTF8(8216) http.htmlEntities["&lt;"] = utf8.codepointToUTF8(60) http.htmlEntities["&macr;"] = utf8.codepointToUTF8(175) http.htmlEntities["&mdash;"] = utf8.codepointToUTF8(8212) http.htmlEntities["&micro;"] = utf8.codepointToUTF8(181) http.htmlEntities["&middot;"] = utf8.codepointToUTF8(183) http.htmlEntities["&minus;"] = utf8.codepointToUTF8(8722) http.htmlEntities["&Mu;"] = utf8.codepointToUTF8(924) http.htmlEntities["&mu;"] = utf8.codepointToUTF8(956) http.htmlEntities["&nabla;"] = utf8.codepointToUTF8(8711) http.htmlEntities["&nbsp;"] = utf8.codepointToUTF8(160) http.htmlEntities["&ndash;"] = utf8.codepointToUTF8(8211) http.htmlEntities["&ne;"] = utf8.codepointToUTF8(8800) http.htmlEntities["&ni;"] = utf8.codepointToUTF8(8715) http.htmlEntities["&not;"] = utf8.codepointToUTF8(172) http.htmlEntities["&notin;"] = utf8.codepointToUTF8(8713) http.htmlEntities["&nsub;"] = utf8.codepointToUTF8(8836) http.htmlEntities["&Ntilde;"] = utf8.codepointToUTF8(209) http.htmlEntities["&ntilde;"] = utf8.codepointToUTF8(241) http.htmlEntities["&Nu;"] = utf8.codepointToUTF8(925) http.htmlEntities["&nu;"] = utf8.codepointToUTF8(957) http.htmlEntities["&Oacute;"] = utf8.codepointToUTF8(211) http.htmlEntities["&oacute;"] = utf8.codepointToUTF8(243) http.htmlEntities["&Ocirc;"] = utf8.codepointToUTF8(212) http.htmlEntities["&ocirc;"] = utf8.codepointToUTF8(244) http.htmlEntities["&OElig;"] = utf8.codepointToUTF8(338) http.htmlEntities["&oelig;"] = utf8.codepointToUTF8(339) http.htmlEntities["&Ograve;"] = utf8.codepointToUTF8(210) http.htmlEntities["&ograve;"] = utf8.codepointToUTF8(242) http.htmlEntities["&oline;"] = utf8.codepointToUTF8(8254) http.htmlEntities["&Omega;"] = utf8.codepointToUTF8(937) http.htmlEntities["&omega;"] = utf8.codepointToUTF8(969) http.htmlEntities["&Omicron;"] = utf8.codepointToUTF8(927) http.htmlEntities["&omicron;"] = utf8.codepointToUTF8(959) http.htmlEntities["&oplus;"] = utf8.codepointToUTF8(8853) http.htmlEntities["&or;"] = utf8.codepointToUTF8(8744) http.htmlEntities["&ordf;"] = utf8.codepointToUTF8(170) http.htmlEntities["&ordm;"] = utf8.codepointToUTF8(186) http.htmlEntities["&Oslash;"] = utf8.codepointToUTF8(216) http.htmlEntities["&oslash;"] = utf8.codepointToUTF8(248) http.htmlEntities["&Otilde;"] = utf8.codepointToUTF8(213) http.htmlEntities["&otilde;"] = utf8.codepointToUTF8(245) http.htmlEntities["&otimes;"] = utf8.codepointToUTF8(8855) http.htmlEntities["&Ouml;"] = utf8.codepointToUTF8(214) http.htmlEntities["&ouml;"] = utf8.codepointToUTF8(246) http.htmlEntities["&para;"] = utf8.codepointToUTF8(182) http.htmlEntities["&part;"] = utf8.codepointToUTF8(8706) http.htmlEntities["&permil;"] = utf8.codepointToUTF8(8240) http.htmlEntities["&perp;"] = utf8.codepointToUTF8(8869) http.htmlEntities["&Phi;"] = utf8.codepointToUTF8(934) http.htmlEntities["&phi;"] = utf8.codepointToUTF8(966) http.htmlEntities["&Pi;"] = utf8.codepointToUTF8(928) http.htmlEntities["&pi;"] = utf8.codepointToUTF8(960) http.htmlEntities["&piv;"] = utf8.codepointToUTF8(982) http.htmlEntities["&plusmn;"] = utf8.codepointToUTF8(177) http.htmlEntities["&pound;"] = utf8.codepointToUTF8(163) http.htmlEntities["&prime;"] = utf8.codepointToUTF8(8242) http.htmlEntities["&Prime;"] = utf8.codepointToUTF8(8243) http.htmlEntities["&prod;"] = utf8.codepointToUTF8(8719) http.htmlEntities["&prop;"] = utf8.codepointToUTF8(8733) http.htmlEntities["&Psi;"] = utf8.codepointToUTF8(936) http.htmlEntities["&psi;"] = utf8.codepointToUTF8(968) http.htmlEntities["&radic;"] = utf8.codepointToUTF8(8730) http.htmlEntities["&raquo;"] = utf8.codepointToUTF8(187) http.htmlEntities["&rarr;"] = utf8.codepointToUTF8(8594) http.htmlEntities["&rceil;"] = utf8.codepointToUTF8(8969) http.htmlEntities["&rdquo;"] = utf8.codepointToUTF8(8221) http.htmlEntities["&reg;"] = utf8.codepointToUTF8(174) http.htmlEntities["&rfloor;"] = utf8.codepointToUTF8(8971) http.htmlEntities["&Rho;"] = utf8.codepointToUTF8(929) http.htmlEntities["&rho;"] = utf8.codepointToUTF8(961) http.htmlEntities["&rlm;"] = utf8.codepointToUTF8(8207) http.htmlEntities["&rsaquo;"] = utf8.codepointToUTF8(8249) http.htmlEntities["&rsquo;"] = utf8.codepointToUTF8(8217) http.htmlEntities["&sbquo;"] = utf8.codepointToUTF8(8218) http.htmlEntities["&Scaron;"] = utf8.codepointToUTF8(352) http.htmlEntities["&scaron;"] = utf8.codepointToUTF8(353) http.htmlEntities["&sdot;"] = utf8.codepointToUTF8(8901) http.htmlEntities["&sect;"] = utf8.codepointToUTF8(167) http.htmlEntities["&shy;"] = utf8.codepointToUTF8(173) http.htmlEntities["&Sigma;"] = utf8.codepointToUTF8(931) http.htmlEntities["&sigma;"] = utf8.codepointToUTF8(963) http.htmlEntities["&sigma;"] = utf8.codepointToUTF8(963) http.htmlEntities["&sigmaf;"] = utf8.codepointToUTF8(962) http.htmlEntities["&sim;"] = utf8.codepointToUTF8(8764) http.htmlEntities["&spades;"] = utf8.codepointToUTF8(9824) http.htmlEntities["&sub;"] = utf8.codepointToUTF8(8834) http.htmlEntities["&sube;"] = utf8.codepointToUTF8(8838) http.htmlEntities["&sum;"] = utf8.codepointToUTF8(8721) http.htmlEntities["&sup;"] = utf8.codepointToUTF8(8835) http.htmlEntities["&sup1;"] = utf8.codepointToUTF8(185) http.htmlEntities["&sup2;"] = utf8.codepointToUTF8(178) http.htmlEntities["&sup3;"] = utf8.codepointToUTF8(179) http.htmlEntities["&supe;"] = utf8.codepointToUTF8(8839) http.htmlEntities["&szlig;"] = utf8.codepointToUTF8(223) http.htmlEntities["&Tau;"] = utf8.codepointToUTF8(932) http.htmlEntities["&tau;"] = utf8.codepointToUTF8(964) http.htmlEntities["&there4;"] = utf8.codepointToUTF8(8756) http.htmlEntities["&Theta;"] = utf8.codepointToUTF8(920) http.htmlEntities["&theta;"] = utf8.codepointToUTF8(952) http.htmlEntities["&thetasym;"] = utf8.codepointToUTF8(977) http.htmlEntities["&thinsp;"] = utf8.codepointToUTF8(8201) http.htmlEntities["&THORN;"] = utf8.codepointToUTF8(222) http.htmlEntities["&thorn;"] = utf8.codepointToUTF8(254) http.htmlEntities["&tilde;"] = utf8.codepointToUTF8(732) http.htmlEntities["&times;"] = utf8.codepointToUTF8(215) http.htmlEntities["&trade;"] = utf8.codepointToUTF8(8482) http.htmlEntities["&Uacute;"] = utf8.codepointToUTF8(218) http.htmlEntities["&uacute;"] = utf8.codepointToUTF8(250) http.htmlEntities["&uarr;"] = utf8.codepointToUTF8(8593) http.htmlEntities["&Ucirc;"] = utf8.codepointToUTF8(219) http.htmlEntities["&ucirc;"] = utf8.codepointToUTF8(251) http.htmlEntities["&Ugrave;"] = utf8.codepointToUTF8(217) http.htmlEntities["&ugrave;"] = utf8.codepointToUTF8(249) http.htmlEntities["&uml;"] = utf8.codepointToUTF8(168) http.htmlEntities["&upsih;"] = utf8.codepointToUTF8(978) http.htmlEntities["&Upsilon;"] = utf8.codepointToUTF8(933) http.htmlEntities["&upsilon;"] = utf8.codepointToUTF8(965) http.htmlEntities["&Uuml;"] = utf8.codepointToUTF8(220) http.htmlEntities["&uuml;"] = utf8.codepointToUTF8(252) http.htmlEntities["&Xi;"] = utf8.codepointToUTF8(926) http.htmlEntities["&xi;"] = utf8.codepointToUTF8(958) http.htmlEntities["&Yacute;"] = utf8.codepointToUTF8(221) http.htmlEntities["&yacute;"] = utf8.codepointToUTF8(253) http.htmlEntities["&yen;"] = utf8.codepointToUTF8(165) http.htmlEntities["&yuml;"] = utf8.codepointToUTF8(255) http.htmlEntities["&Yuml;"] = utf8.codepointToUTF8(376) http.htmlEntities["&Zeta;"] = utf8.codepointToUTF8(918) http.htmlEntities["&zeta;"] = utf8.codepointToUTF8(950) http.htmlEntities["&zwj;"] = utf8.codepointToUTF8(8205) http.htmlEntities["&zwnj;"] = utf8.codepointToUTF8(8204) --- hs.http.registerEntity(entity, codepoint) -> string --- Function --- Registers an HTML Entity with the specified Unicode codepoint which can later referenced in your code as `hs.http.htmlEntity[entity]` for convenience and readability. --- --- Parameters: --- * entity -- The full text of the HTML Entity as it appears in HTML encoded documents. A proper entity starts with & and ends with ; and entity labels which do not meet this will have them added -- future dereferences to get the corresponding UTF8 *must* include this initiator and terminator or they will not be recognized. --- * codepoint -- a Unicode codepoint in numeric or `U+xxxx` format to register with as the given entity. --- --- Returns: --- * Returns the UTF8 byte sequence for the entity registered. --- --- Notes: --- * If an entity label was previously registered, this will overwrite the previous value with a new one. --- * The return value is merely syntactic sugar and you do not need to save it locally; it can be safely ignored -- future access to the pre-converted entity should be retrieved as `hs.http.htmlEntities[entity]` in your code. It looks good when invoked from the console, though ☺. http.registerEntity = function(label, codepoint) local entity = label:match("^&?([^&;]+);?$") if not entity then return error("Invalid label '"..label.."' provided to hs.http.registerEntity", 2) else label = "&"..entity..";" http.htmlEntities[label] = utf8.codepointToUTF8(codepoint) return http.htmlEntities[label] end end --- hs.http.convertHtmlEntities(inString) -> outString --- Function --- Convert all recognized HTML Entities in the `inString` to appropriate UTF8 byte sequences and returns the converted text. --- --- Parameters: --- * inString -- A string containing any number of HTML Entities (&whatever;) in the text. --- --- Returns: --- * outString -- the input string with all recognized HTML Entity sequences converted to UTF8 byte sequences. --- --- Notes: --- * Recognized HTML Entities are those registered in `hs.http.htmlEntities` or numeric entity sequences: &#n; where `n` can be any integer number. --- * This function is especially useful as a post-filter to data retrieved by the `hs.http.get` and `hs.http.asyncGet` functions. http.convertHtmlEntities = function(input) return input:gsub("&[^;]+;", function(c) return http.htmlEntities[c] or c end) end --- hs.http.encodeForQuery(string) -> string --- Function --- Returns a copy of the provided string in which characters that are not valid within an HTTP query key or value are escaped with their %## equivalent. --- --- Parameters: --- * originalString - the string to make safe as a key or value for a query --- --- Returns: --- * the converted string --- --- Notes: --- * The intent of this function is to provide a valid key or a valid value for a query string, not to validate the entire query string. For this reason, ?, =, +, and & are included in the converted characters. local encodeForQuery = http.encodeForQuery http.encodeForQuery = function(...) return (encodeForQuery(...):gsub("[%?=&+]", { ["?"] = "%3F", ["="] = "%3D", ["&"] = "%26", ["+"] = "%2B" } )) end return http
mit
eagle14/kia14
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
toxxin/packages
utils/luci-app-lxc/files/controller/lxc.lua
77
2909
--[[ LuCI LXC module Copyright (C) 2014, Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Author: Petar Koretic <petar.koretic@sartura.hr> ]]-- module("luci.controller.lxc", package.seeall) require "ubus" local conn = ubus.connect() if not conn then error("Failed to connect to ubus") end function fork_exec(command) local pid = nixio.fork() if pid > 0 then return elseif pid == 0 then -- change to root dir nixio.chdir("/") -- patch stdin, out, err to /dev/null local null = nixio.open("/dev/null", "w+") if null then nixio.dup(null, nixio.stderr) nixio.dup(null, nixio.stdout) nixio.dup(null, nixio.stdin) if null:fileno() > 2 then null:close() end end -- replace with target command nixio.exec("/bin/sh", "-c", command) end end function index() page = node("admin", "services", "lxc") page.target = cbi("lxc") page.title = _("LXC Containers") page.order = 70 page = entry({"admin", "services", "lxc_create"}, call("lxc_create"), nil) page.leaf = true page = entry({"admin", "services", "lxc_action"}, call("lxc_action"), nil) page.leaf = true page = entry({"admin", "services", "lxc_configuration_get"}, call("lxc_configuration_get"), nil) page.leaf = true page = entry({"admin", "services", "lxc_configuration_set"}, call("lxc_configuration_set"), nil) page.leaf = true end function lxc_create(lxc_name, lxc_template) luci.http.prepare_content("text/plain") local uci = require("uci").cursor() local url = uci:get("lxc", "lxc", "url") if not pcall(dofile, "/etc/openwrt_release") then return luci.http.write("1") end local target = _G.DISTRIB_TARGET:match('([^/]+)') local data = conn:call("lxc", "create", { name = lxc_name, template = "download", args = { "--server", url, "--no-validate", "--dist", lxc_template, "--release", "bb", "--arch", target } } ) luci.http.write(data) end function lxc_action(lxc_action, lxc_name) luci.http.prepare_content("application/json") local data, ec = conn:call("lxc", lxc_action, lxc_name and { name = lxc_name} or {} ) luci.http.write_json(ec and {} or data) end function lxc_configuration_get(lxc_name) luci.http.prepare_content("text/plain") local f = io.open("/lxc/" .. lxc_name .. "/config", "r") local content = f:read("*all") f:close() luci.http.write(content) end function lxc_configuration_set(lxc_name) luci.http.prepare_content("text/plain") local lxc_configuration = luci.http.formvalue("lxc_configuration") if lxc_configuration == nil then return luci.http.write("1") end local f, err = io.open("/lxc/" .. lxc_name .. "/config","w+") if not f then return luci.http.write("2") end f:write(lxc_configuration) f:close() luci.http.write("0") end
gpl-2.0
resistor58/deaths-gmod-server
wire/lua/weapons/gmod_tool/stools/wire_wirelink.lua
1
4228
TOOL.Category = "Wire - Tools" TOOL.Name = "Expression 2 - Wirelink" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if CLIENT then language.Add( "Tool_wire_wirelink_name", "Expression 2 Wirelink Tool (Wire)" ) language.Add( "Tool_wire_wirelink_desc", "Adds a wirelink output to any wire compatible device, for use with Expression 2" ) language.Add( "Tool_wire_wirelink_0", "Primary: Add wirelink, Secondary: Remove wirelink" ) end if SERVER then local _Wire_Link_End = WireLib.Link_End local _Wire_CreateSpecialOutputs = WireLib.CreateSpecialOutputs local _Wire_AdjustSpecialOutputs = WireLib.AdjustSpecialOutputs local _Wire_BuildDupeInfo = WireLib.BuildDupeInfo local _Wire_ApplyDupeInfo = WireLib.ApplyDupeInfo function RefreshSpecialOutputs(ent) local names = {} local types = {} local descs = {} if ent.Outputs then for _,output in pairs(ent.Outputs) do local index = output.Num names[index] = output.Name types[index] = output.Type descs[index] = output.Desc end ent.Outputs = WireLib.AdjustSpecialOutputs(ent, names, types, descs) else ent.Outputs = WireLib.CreateSpecialOutputs(ent, names, types, descs) end WireLib.TriggerOutput(ent, "link", ent) end function InfuseSpecialOutputs(func, ent, names, types, desc) if types == nil then types = {} for i,v in ipairs(names) do -- Allow to specify the type in square brackets, like "Name [TYPE]" local name, tp = v:match("^(.+) %[(.+)%]$") if not name then name = v tp = "NORMAL" end names[i] = name types[i] = tp end end if ent.extended == nil then return func(ent, names, types, desc) end table.insert(names, "link") table.insert(types, "WIRELINK") local outputs = func(ent, names, types, desc) table.remove(names) table.remove(types) return outputs end function WireLib.BuildDupeInfo(ent) local info = _Wire_BuildDupeInfo(ent) if ent.extended then if info == nil then info = {} end info.extended = true end return info end function WireLib.ApplyDupeInfo(ply, ent, info, GetEntByID) if info.extended and ent.extended == nil then ent.extended = true RefreshSpecialOutputs(ent) end return _Wire_ApplyDupeInfo(ply, ent, info, GetEntByID) end function WireLib.CreateSpecialOutputs(ent, names, types, desc) return InfuseSpecialOutputs(_Wire_CreateSpecialOutputs, ent, names, types, desc) end function WireLib.AdjustSpecialOutputs(ent, names, types, desc) return InfuseSpecialOutputs(_Wire_AdjustSpecialOutputs, ent, names, types, desc) end function WireLib.Link_End(idx, ent, pos, oname, pl) if oname == "link" and ent.extended == nil then ent.extended = true RefreshSpecialOutputs(ent) end return _Wire_Link_End(idx, ent, pos, oname, pl) end Wire_Link_End = WireLib.Link_End Wire_BuildDupeInfo = WireLib.BuildDupeInfo Wire_ApplyDupeInfo = WireLib.ApplyDupeInfo end function TOOL:LeftClick(trace) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end local ply = self:GetOwner() if ( trace.Entity:IsValid() && (trace.Entity.Base == "base_wire_entity" || trace.Entity.Inputs || trace.Entity.Outputs) && (trace.Entity.pl == ply || trace.Entity.pl == nil) ) then local ent = trace.Entity if ent.extended then return false end ent.extended = true RefreshSpecialOutputs(ent) return true end return false end function TOOL:RightClick(trace) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end local ply = self:GetOwner() if ( trace.Entity:IsValid() && (trace.Entity.pl == ply || trace.Entity.pl == nil) ) then local ent = trace.Entity if !ent.extended then return false end ent.extended = false RefreshSpecialOutputs(ent) return true end return false end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool_wire_wirelink_name", Description = "#Tool_wire_wirelink_desc" }) end
gpl-3.0
Chessnut/moderator
lua/moderator/libs/sh_commands.lua
3
9865
moderator.commands = moderator.commands or {} if (SERVER) then util.AddNetworkString("mod_Command") function moderator.GetArguments(text, noArrays, delimiter) delimiter = delimiter or " " local arguments = {} local curString = "" local inString = false local escaping = 0 local inArray = false for i = 1, #text do local char = text:sub(i, i) if (escaping > i) then continue end if (char == "\\") then escaping = i + 1 elseif (!noArrays and !inString and char == "[") then local match = text:sub(i):match("%b[]") if (match) then local exploded = moderator.GetArguments(match:sub(2, -2), nil, ",") for k, v in pairs(exploded) do if (type(v) == "string" and (v:sub(1, 1) == " " or v:sub(1, 1) == delimiter)) then exploded[k] = v:sub(2) end end arguments[#arguments + 1] = exploded curString = "" escaping = i + #match end elseif (char == "'" or char == "\"") then if (inString) then arguments[#arguments + 1] = curString curString = "" inString = false else inString = true end elseif (inString) then curString = curString..char elseif (char == delimiter and curString != "" and !inString) then arguments[#arguments + 1] = curString curString = "" elseif (char != " " and char != delimiter) then curString = curString..char end end if (curString != "") then arguments[#arguments + 1] = curString end return arguments end local targetPrefix = "#" local targets = {} targets["this"] = function(client) local target = client:GetEyeTraceNoCursor().Entity if (IsValid(target) and target:IsPlayer()) then return target end end targets["all"] = function(client) return player.GetAll() end targets["alive"] = function(client) local target = {} for k, v in pairs(player.GetAll()) do if (v:Alive()) then target[#target + 1] = v end end return target end targets["dead"] = function(client) local target = {} for k, v in pairs(player.GetAll()) do if (!v:Alive()) then target[#target + 1] = v end end return target end targets["rand"] = function(client) return table.Random(player.GetAll()) end targets["random"] = targets["rand"] targets["me"] = function(client) return client end targets["last"] = function(client) return client.modLastTarget end local function GetTargeter(client, info) if (info and info:sub(1, 1) == targetPrefix) then local targeter = info:lower():sub(2):match("([_%w]+)") local result = targets[targeter] if (result) then return result(client) elseif (targeter) then local players = {} for k, v in pairs(player.GetAll()) do if (moderator.StringMatches(v:GetNWString("usergroup", "user"), targeter)) then players[#players + 1] = v end end if (#players > 0) then return players end end end end function moderator.FindCommandTable(command) local commandTable = moderator.commands[command] local alias if (!commandTable) then local aliases = {} for k, v in pairs(moderator.commands) do if (v.aliases) then for k2, v2 in pairs(v.aliases) do aliases[v2] = k end end end if (aliases[command]) then alias = command end command = aliases[command] commandTable = moderator.commands[command] end return commandTable, command, alias end function moderator.ParseCommand(client, command, arguments) local commandTable, command, alias = moderator.FindCommandTable(command) if (commandTable) then if (!moderator.HasPermission(command, client)) then return false, "you are not allowed to use this command" end arguments = moderator.GetArguments(arguments, commandTable.noArrays) local target local targetIsArgument if (!commandTable.noTarget) then target = arguments[1] if (type(target) == "table") then for i = 1, #target do local name = target[i] if (type(name) != "string") then continue end local result = GetTargeter(client, name) if (result) then if (type(result) == "table") then target[i] = nil table.Add(target, result) continue else target[i] = result continue end end local found = moderator.FindPlayerByName(name, nil, commandTable.findLimit) if (IsValid(found) and moderator.HasInfluence(client, found, commandTable.strictTargetting)) then target[i] = found else target[i] = nil end end if (table.Count(target) == 0) then if (commandTable.targetIsOptional) then targetIsArgument = true else return false, "you are not allowed to target any of these players" end end elseif (target) then local result = GetTargeter(client, target) if (result) then target = result else target = moderator.FindPlayerByName(target, nil, commandTable.findLimit) end if (type(target) == "table") then for k, v in pairs(target) do if (!moderator.HasInfluence(client, v, commandTable.strictTargetting)) then target[k] = nil end end if (table.Count(target) == 0) then if (commandTable.targetIsOptional) then targetIsArgument = true else return false, "you are not allowed to target any of these players" end end else if (IsValid(target)) then if (!moderator.HasInfluence(client, target, commandTable.strictTargetting)) then return false, "you are not allowed to target this player" end elseif (!commandTable.targetIsOptional) then return false, "you provided an invalid player" end end elseif (!commandTable.targetIsOptional) then return false, "you provided an invalid player" end if (!targetIsArgument) then table.remove(arguments, 1) end end moderator.RunCommand(client, command, arguments, target, alias) else return false, "you have entered an invalid command" end return true end function moderator.RunCommand(client, command, arguments, target, alias) local commandTable = moderator.commands[command] if (commandTable) then if (!moderator.HasPermission(command, client)) then return moderator.Notify(client, "you are not allowed to do that.") end if (IsValid(client) and client:GetInfoNum("mod_clearoncommand", 1) > 0) then client:ConCommand("mod_clearselected") end local result, message = commandTable:OnRun(client, arguments, target, alias) if (IsValid(client)) then client.modLastTarget = target end if (result == false) then moderator.Notify(client, message) return result, message end else moderator.Notify(client, "you have entered an invalid command.") return "you have entered an invalid command" end end function moderator.Print(client, message) if (!IsValid(client)) then MsgN(message) else client:PrintMessage(2, message) end end net.Receive("mod_Command", function(length, client) local command = net.ReadString() local arguments = net.ReadTable() local target = net.ReadTable() if (#target == 1) then target = target[1] end moderator.RunCommand(client, command, arguments, target) end) concommand.Add("mod", function(client, command, arguments) if (IsValid(client) and arguments[1] == "menu") then return client:ConCommand("mod_menu") end local command = arguments[1] table.remove(arguments, 1) if (command and command != "help") then command = command:lower() local result, message = moderator.ParseCommand(client, command, table.concat(arguments, " ")) if (message) then moderator.Notify(client, message..".") end elseif ((client.modNextHelp or 0) < CurTime()) then client.modNextHelp = CurTime() + 5 local command = arguments[1] if (command) then local commandTable, command = moderator.FindCommandTable(command:lower()) if (commandTable) then local usage = commandTable.usage or "[none]" if (!commandTable.usage and !commandTable.noTarget) then usage = "<player> "..usage end moderator.Print(client, "\n\n [moderator] Command Help for: "..command) moderator.Print(client, " \t• Name: "..(commandTable.name or "No name available.")) moderator.Print(client, " \t• Description: "..(commandTable.tip or "No description available.")) moderator.Print(client, " \t• Usage: "..usage) if (commandTable.example) then moderator.Print(client, " \t• Example: "..commandTable.example) end if (commandTable.aliases) then moderator.Print(client, " \t• Alias"..(#commandTable.aliases > 0 and "es" or "")..": "..table.concat(commandTable.aliases, ", ")) end else moderator.Print(client, " [moderator] That command does not exist.") end return end moderator.Print(client, [[ __ __ ___ __ ___ __ __ |\/| / \ | \ |__ |__) /\ | / \ |__) | | \__/ |__/ |___ | \ /--\ | \__/ | \ Created by Chessnut - Version ]]..moderator.version..[[ ]]) moderator.Print(client, " Command Help:") for k, v in SortedPairsByMemberValue(moderator.commands, "name") do if (moderator.HasPermission(k, client)) then moderator.Print(client, " "..k.." "..(v.tip or "No help available.")) end end moderator.Print(client, "\n Type 'mod help <command>' to get help with a specific command.\n\n") end end) else function moderator.SendCommand(command, target, ...) if (type(target) != "table") then target = {target} end net.Start("mod_Command") net.WriteString(command) net.WriteTable({...}) net.WriteTable(target) net.SendToServer() end end
gpl-2.0
squilter/ardupilot
libraries/AP_Scripting/examples/plane-wind-failsafe.lua
26
1195
-- warn the user if wind speed exceeds a threshold, failsafe if a second threshold is exceeded -- note that this script is only intended to be run on ArduPlane -- tuning parameters local warn_speed = 10 -- metres/second local failsafe_speed = 15 -- metres/second local warning_interval_ms = uint32_t(15000) -- send user message every 15s local warning_last_sent_ms = uint32_t() -- time we last sent a warning message to the user function update() local wind = ahrs:wind_estimate() -- get the wind estimate if wind then -- make a 2D wind vector wind_xy = Vector2f() wind_xy:x(wind:x()) wind_xy:y(wind:y()) speed = wind_xy:length() -- compute the wind speed if speed > failsafe_speed then gcs:send_text(0, "Wind failsafe at " .. speed .. " metres/second") vehicle:set_mode(11) -- FIXME: should be an enum. 11 is RTL. return end if speed > warn_speed then if millis() - warning_last_sent_ms > warning_interval_ms then gcs:send_text(4, "Wind warning at " .. speed .. " metres/second") warning_last_sent_ms = millis() end end end return update, 1000 end return update, 1000
gpl-3.0
GabrielNicolasAvellaneda/boundary-plugin-apache-tomcat
init.lua
2
3793
-- Copyright 2015 Boundary, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local Plugin = framework.Plugin local WebRequestDataSource = framework.WebRequestDataSource local round = framework.util.round local auth = framework.util.auth local isHttpSuccess = framework.util.isHttpSuccess local megaBytesToBytes = framework.util.megaBytesToBytes local percentage = framework.util.percentage local compose = framework.functional.compose local notEmpty = framework.string.notEmpty local function parseMetric(data, pattern) local val = data:match(pattern) return tonumber(round(val, 2)) end local parsePercentage = compose(parseMetric, percentage) local parseBytes = compose(parseMetric, megaBytesToBytes) local function parse(data) local vals = {} vals['TOMCAT_JVM_FREE_MEMORY'] = parseBytes(data, 'Free memory: (%d+%.%d+) MB') vals['TOMCAT_JVM_TOTAL_MEMORY'] = parseBytes(data, 'Total memory: (%d+%.%d+) MB') vals['TOMCAT_HTTP_CURRENT_THREAD_COUNT'] = parseMetric(data, 'Current thread count: (%d+)') vals['TOMCAT_HTTP_CURRENT_THREAD_BUSY'] = parseMetric(data, 'Current thread busy: (%d+)') vals['TOMCAT_HTTP_MAX_PROCESSING_TIME'] = parseMetric(data, 'Max processing time: (%d+) ms') vals['TOMCAT_HTTP_REQUEST_COUNT'] = parseMetric(data, 'Request count: (%d+)') vals['TOMCAT_HTTP_ERROR_COUNT'] = parseMetric(data, 'Error count: (%d+)') vals['TOMCAT_HTTP_BYTES_SENT'] = parseBytes(data, 'Bytes sent: (%d+%.%d+) MB') vals['TOMCAT_HTTP_BYTES_RECEIVED'] = parseBytes(data, 'Bytes received: (%d+%.%d+) MB') vals['TOMCAT_MEMPOOL_HEAP_CMS_OLD_GEN'] = parsePercentage(data, 'CMS Old Gen</td><td>Heap memory</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB %((%d+)%%%)</td>') vals['TOMCAT_MEMPOOL_HEAP_EDEN_SPACE'] = parsePercentage(data, 'Eden Space</td><td>Heap memory</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB %((%d+)%%%)</td>') vals['TOMCAT_MEMPOOL_HEAP_SURVIVOR_SPACE'] = parsePercentage(data, 'Survivor Space</td><td>Heap memory</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB %((%d+)%%%)</td>') vals['TOMCAT_MEMPOOL_NONHEAP_CMS_PERM_GEN'] = parsePercentage(data, 'CMS Perm Gen</td><td>Non%-heap memory</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB %((%d+)%%%)</td>') vals['TOMCAT_MEMPOOL_NONHEAP_CODE_CACHE'] = parsePercentage(data, 'Code Cache</td><td>Non%-heap memory</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB</td><td>%d+%.%d+ MB %((%d+)%%%)</td>') return vals end local params = framework.params local options = {} options.host = notEmpty(params.host, '127.0.0.1') options.port = notEmpty(params.port, 80) options.path = params.path options.source = params.source options.auth = auth(params.username, params.password) local data_source = WebRequestDataSource:new(options) local plugin = Plugin:new(params, data_source) function plugin:onParseValues(data, extra) if not isHttpSuccess(extra.status_code) then self:emitEvent('error', plugin.source .. ' HTTP Error - ' .. extra.status_code, plugin.source, plugin.source, 'HTTP status code ' .. extra.status_code) return end local vals = parse(data) return vals end plugin:run()
apache-2.0
chewi/Aquaria
files/scripts/maps/node_naija_singing.lua
6
1163
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_NAIJA_SINGING, 0) then if node_isEntityIn(me, getNaija()) then setControlHint(getStringBank(35), 0, 0, 0, 8, "", SONG_SHIELD) voice("naija_singing") setFlag(FLAG_NAIJA_SINGING, 1) end end end
gpl-2.0