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
aqasaeed/zeus
plugins/Moderation.lua
35
10153
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You are moderator for group') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group have already moderator list' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'User @'..username..' set to moderator list' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You are NOT GLOBAL ADMIN" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group have already moderator list' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Moderator list added' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You are NOT GLOBAL ADMIN" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group have not moderator list' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Moderator list removed' 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, 'Moderator list added') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already moderator') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' set to moderator list') 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 have not moderator list') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is not moderator') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' remove from moderator list') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already GLOBAL ADMIN') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' set to GLOBAL ADMIN list') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is not GLOBAL ADMIN') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' remove from GLOBAL ADMIN list') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No @'..member..' in group' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'modset' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'moddem' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminset' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group have not moderator list' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in group' end local message = '' .. string.gsub(msg.to.print_name, '_', ' ') .. ' Moderator list:\n______________________________\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '> @'..v..' (' ..k.. ') \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No GLOBAL ADMIN available' end local message = 'Umbrella Bot GLOBAL ADMINS:\n______________________________\n' for k,v in pairs(data['admins']) do message = message .. '>> @'.. v ..' ('..k..') \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only work in group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'modset' and matches[2] then if not is_momod(msg) then return "GLOBAL ADMIN and moderator can set moderator" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'moddem' and matches[2] then if not is_momod(msg) then return "GLOBAL ADMIN and moderator can demote moderator" end if string.gsub(matches[2], "@", "") == msg.from.username then return "can not demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminset' then if not is_admin(msg) then return "Only SUDO can set GLOBAL ADMIN" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only SUDO can demote GLOBAL ADMIN" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'You are NOT GLOBAL ADMIN' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Robot and Group Moderation System", usage = { moderator = { "/modlist : moderator list", "/modset (@user) : set moderator", "/moddem (@user) : remove moderator", }, admin = { "/modadd : add moderation list", "/modrem : remove moderation list", "/adminlist : global admin list", "/adminset (@user) : set global admin", "/admindem (@user) : remove global admin", }, sudo = { "/adminset (@user) : set global admin", "/admindem (@user) : remove global admin", }, }, patterns = { "^[!/](modadd)$", "^[!/](modrem)$", "^[!/](modset) (.*)$", "^[!/](moddem) (.*)$", "^[!/](modlist)$", "^[!/](adminset) (.*)$", -- sudoers only "^[!/](admindem) (.*)$", -- sudoers only "^[!/](adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
nasomi/darkstar
scripts/zones/Lower_Jeuno/npcs/Hasim.lua
37
1701
----------------------------------- -- Area: Lower Jeuno -- NPC: Hasim -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,HASIM_SHOP_DIALOG); stock = {0x1244,930, -- Scroll of Baraera 0x123e,930, -- Scroll of Baraero 0x1243,3624, -- Scroll of Barblizzara 0x123d,3624, -- Scroll of Barblizzard 0x1242,1760, -- Scroll of Barfira 0x123c,1760, -- Scroll of Barfire 0x1245,156, -- Scroll of Barstonra 0x123f,156, -- Scroll of Barstone 0x1246,5754, -- Scroll of Barthundra 0x1240,5754, -- Scroll of Barthunder 0x1247,360, -- Scroll of Barwatera 0x1241,360, -- Scroll of Barwater 0x1208,11200, -- Scroll of Curaga II 0x1209,19932, -- Scroll of Curaga III 0x1204,23400, -- Scroll of Cure IV 0x122d,32000} -- Scroll of Protect III showShop(player, STATIC, stock); 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
nasomi/darkstar
scripts/zones/Castle_Oztroja/npcs/_m72.lua
16
2269
----------------------------------- -- Area: Castle Oztroja -- NPC: _m72 (Torch Stand) -- Notes: Opens door _477 when _m72 to _m75 are lit -- @pos -60 -72 -139 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) DoorID = npc:getID() - 2; Torch1 = npc:getID(); Torch2 = npc:getID() + 1; Torch3 = npc:getID() + 2; Torch4 = npc:getID() + 3; DoorA = GetNPCByID(DoorID):getAnimation(); TorchStand1A = npc:getAnimation(); TorchStand2A = GetNPCByID(Torch2):getAnimation(); TorchStand3A = GetNPCByID(Torch3):getAnimation(); TorchStand4A = GetNPCByID(Torch4):getAnimation(); if (DoorA == 9 and TorchStand1A == 9) then player:startEvent(0x000a); else player:messageSpecial(TORCH_LIT); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (option == 1) then GetNPCByID(Torch1):openDoor(55); if ((DoorA == 9) and (TorchStand2A == 8) and (TorchStand3A == 8) and (TorchStand4A == 8)) then GetNPCByID(DoorID):openDoor(35); -- confirmed retail tested -- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first -- They need to be reset to the door open time(35s) + 4s (39 seconds) GetNPCByID(Torch1):setAnimation(9); GetNPCByID(Torch2):setAnimation(9); GetNPCByID(Torch3):setAnimation(9); GetNPCByID(Torch4):setAnimation(9); GetNPCByID(Torch1):openDoor(39); -- confirmed retail tested GetNPCByID(Torch2):openDoor(39); GetNPCByID(Torch3):openDoor(39); GetNPCByID(Torch4):openDoor(39); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Halvung/npcs/qm2.lua
16
1157
----------------------------------- -- Area: Halvung -- NPC: ??? (Spawn Dextrose(ZNM T2)) -- @pos -144 11 464 62 ----------------------------------- package.loaded["scripts/zones/Halvung/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Halvung/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2589,1) and trade:getItemCount() == 1) then -- Trade Granulated Sugar player:tradeComplete(); SpawnMob(17031598,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
mbsg/openwrt-extra
luci/applications/luci-app-qosv4/luasrc/model/cbi/qosv4.lua
7
4535
require("luci.tools.webadmin") --[[ config 'qos_settings' option 'enable' '0' option 'UP' '100' option 'DOWN' '500' option qos_scheduler 1 config 'qos_ip' option 'enable' '0' option 'limit_ip' '192.168.1.5' option 'UPLOADR' '2' option 'DOWNLOADR' '2' option 'UPLOADC' '15' option 'DOWNLOADC' '15' option 'UPLOADR2' '1' option 'UPLOADC2' '5' option 'DOWNLOADR2' '1' option 'DOWNLOADC2' '2' config 'qos_nolimit_ip' option 'enable' '0' option 'limit_ip' '192.168.1.6' ]]-- local sys = require "luci.sys" m = Map("qosv4", translate("qosv4 title","QOSv4"), translate("qosv4 title desc","qosv4 title desc")) s = m:section(TypedSection, "qos_settings", translate("qos goble setting","qos goble setting")) s.anonymous = true s.addremove = false enable = s:option(Flag, "enable", translate("qos enable", "qos enable")) enable.default = false enable.optional = false enable.rmempty = false qos_scheduler = s:option(Flag, "qos_scheduler", translate("qos scheduler enable", "qos scheduler enable"), translate("qos scheduler desc","qos scheduler desc")) qos_scheduler.default = false qos_scheduler.optional = false qos_scheduler.rmempty = false DOWN = s:option(Value, "DOWN", translate("DOWN speed","DOWN speed"), translate("DOWN speed desc","DOWN speed desc")) DOWN.optional = false DOWN.rmempty = false UP = s:option(Value, "UP", translate("UP speed","UP speed"), translate("UP speed desc","UP speed desc")) UP.optional = false UP.rmempty = false DOWNLOADR = s:option(Value, "DOWNLOADR", translate("DOWNLOADR speed","DOWNLOADR speed")) DOWNLOADR.optional = false DOWNLOADR.rmempty = false UPLOADR = s:option(Value, "UPLOADR", translate("UPLOADR speed","UPLOADR speed")) UPLOADR.optional = false UPLOADR.rmempty = false DOWNLOADR2 = s:option(Value, "DOWNLOADR2", translate("DOWNLOADR2 speed","DOWNLOADR2 speed")) DOWNLOADR2.optional = false DOWNLOADR2.rmempty = false UPLOADR2 = s:option(Value, "UPLOADR2", translate("UPLOADR2 speed","UPLOADR2 speed")) UPLOADR2.optional = false UPLOADR2.rmempty = false DOWNLOADC2 = s:option(Value, "DOWNLOADC2", translate("DOWNLOADC2 speed","DOWNLOADC2 speed")) DOWNLOADC2.optional = false DOWNLOADC2.rmempty = false UPLOADC2 = s:option(Value, "UPLOADC2", translate("UPLOADC2 speed","UPLOADC2 speed")) UPLOADC2.optional = false UPLOADC2.rmempty = false s = m:section(TypedSection, "qos_ip", translate("qos black ip","qos black ip")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true enable = s:option(Flag, "enable", translate("enable", "enable")) enable.default = false enable.optional = false enable.rmempty = false limit_ip = s:option(Value, "limit_ip", translate("limit_ip","limit_ip")) limit_ip.rmempty = true luci.tools.webadmin.cbi_add_knownips(limit_ip) DOWNLOADC = s:option(Value, "DOWNLOADC", translate("DOWNLOADC speed","DOWNLOADC speed")) DOWNLOADC.optional = false DOWNLOADC.rmempty = false UPLOADC = s:option(Value, "UPLOADC", translate("UPLOADC speed","UPLOADC speed")) UPLOADC.optional = false UPLOADC.rmempty = false ip_prio = s:option(Value, "ip_prio", translate("ip prio","ip prio"), translate("ip prio desc"," default 5 ")) ip_prio.optional = false ip_prio.rmempty = false s = m:section(TypedSection, "transmission_limit", translate("transmission limit","transmission limit")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = false enable = s:option(Flag, "enable", translate("enable", "enable")) enable.default = false enable.optional = false enable.rmempty = false downlimit= s:option(Value, "downlimit", translate("downlimit speed","downlimit speed")) downlimit.optional = false downlimit.rmempty = false uplimit= s:option(Value, "uplimit", translate("uplimit speed","uplimit speed")) uplimit.optional = false uplimit.rmempty = false s = m:section(TypedSection, "qos_nolimit_ip", translate("qos white","qos white")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true enable = s:option(Flag, "enable", translate("enable", "enable")) enable.default = false enable.optional = false enable.rmempty = false nolimit_mac= s:option(Value, "nolimit_mac", translate("white mac","white mac")) nolimit_mac.rmempty = true nolimit_ip= s:option(Value, "nolimit_ip", translate("white ip","white ip")) nolimit_ip.rmempty = true sys.net.arptable(function(entry) nolimit_ip:value(entry["IP address"]) nolimit_mac:value( entry["HW address"], entry["HW address"] .. " (" .. entry["IP address"] .. ")" ) end) return m
gpl-2.0
nasomi/darkstar
scripts/zones/Korroloka_Tunnel/npcs/qm2.lua
17
3461
----------------------------------- -- Area: Korroloka Tunnel -- NPC: ??? (qm2) -- Involved In Quest: Ayame and Kaede -- @pos -208 -9 176 173 ----------------------------------- package.loaded["scripts/zones/Korroloka_Tunnel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Korroloka_Tunnel/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,AYAME_AND_KAEDE) == QUEST_ACCEPTED) then if (player:getVar("AyameAndKaede_Event") == 2 and player:hasKeyItem(STRANGELY_SHAPED_CORAL) == false) then local leechesDespawned = (GetMobAction(17486187) == 0 and GetMobAction(17486188) == 0 and GetMobAction(17486189) == 0); local spawnTime = player:getVar("KorrolokaLeeches_Spawned"); local canSpawn = (leechesDespawned and (os.time() - spawnTime) > 30); local killedLeeches = player:getVar("KorrolokaLeeches"); if (killedLeeches >= 1) then if ((killedLeeches == 3 and (os.time() - player:getVar("KorrolokaLeeches_Timer") < 30)) or (killedLeeches < 3 and leechesDespawned and (os.time() - spawnTime) < 30)) then player:addKeyItem(STRANGELY_SHAPED_CORAL); player:messageSpecial(KEYITEM_OBTAINED,STRANGELY_SHAPED_CORAL); player:setVar("KorrolokaLeeches",0); player:setVar("KorrolokaLeeches_Spawned",0); player:setVar("KorrolokaLeeches_Timer",0); elseif (leechesDespawned) then SpawnMob(17486187,168); -- Despawn after 3 minutes (-12 seconds for despawn delay). SpawnMob(17486188,168); SpawnMob(17486189,168); player:setVar("KorrolokaLeeches",0); player:setVar("KorrolokaLeeches_Spawned",os.time()+180); player:messageSpecial(SENSE_OF_BOREBODING); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end elseif (canSpawn) then SpawnMob(17486187,168); -- Despawn after 3 minutes (-12 seconds for despawn delay). SpawnMob(17486188,168); SpawnMob(17486189,168); player:setVar("KorrolokaLeeches_Spawned",os.time()+180); player:messageSpecial(SENSE_OF_BOREBODING); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Ramua.lua
53
1884
----------------------------------- -- Area: Northern San d'Oria -- NPC: Ramua -- Type: Woodworking Synthesis Image Support -- @pos -183.750 10.999 255.770 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,9); local SkillCap = getCraftSkillCap(player,SKILL_WOODWORKING); local SkillLevel = player:getSkillLevel(SKILL_WOODWORKING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == false) then player:startEvent(0x0271,SkillCap,SkillLevel,2,207,player:getGil(),0,0,0); else player:startEvent(0x0271,SkillCap,SkillLevel,2,207,player:getGil(),6857,0,0); end else player:startEvent(0x0271,SkillCap,SkillLevel,2,201,player:getGil(),0,0,0); -- Standard 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 == 0x0271 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,1,2); player:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,1,0,120); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/West_Sarutabaruta_[S]/mobs/Ramponneau.lua
14
1922
----------------------------------- -- Area: West Sarutabaruta (S) -- NM: Ramponneau ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT, mob:getShortID()); mob:addStatusEffect(EFFECT_SHOCK_SPIKES, 10, 0, 0); mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) mob:SetMobAbilityEnabled(false); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) local power = math.random(4,15); local params = {}; params.bonusmab = 0; params.includemab = false; power = addBonusesAbility(mob, ELE_ICE, target, power, params); power = power * applyResistanceAddEffect(mob, target, ELE_ICE, 0); power = adjustForTarget(target, power, ELE_ICE); power = finalMagicNonSpellAdjustments(mob, target, ELE_ICE, power); local message = MSGBASIC_ADD_EFFECT_DMG; if (power < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_ICE_DAMAGE, message, power; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) -- Set Ramponneau's Window Open Time local wait = 5400 -- 90 minutes SetServerVariable("[POP]Ramponneau", os.time(t) + wait ); DeterMob(mob:getID(), true); -- Set PH back to normal, then set to respawn spawn local PH = GetServerVariable("[PH]Ramponneau"); SetServerVariable("[PH]Ramponneau", 0); DeterMob(PH, false); GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH)); end;
gpl-3.0
sjthespian/dotfiles
hammerspoon/utils/app.lua
2
3658
-- Application-related utilities local lib = {} local ustr = require('utils.string') local ufile = require('utils.file') -- osascript to tell an application to do something function lib.tell(app, appCmd) local cmd = 'tell application "'..app..'" to '..appCmd local ok, result = hs.applescript(cmd) if ok and result == nil then result = true end if not ok then result = nil end return result end -- get iTunes player status function lib.getiTunesPlayerState() local state = nil if hs.itunes.isRunning() then state = ustr.unquote(hs.itunes.getPlaybackState()) end return state end -- get Spotify player status function lib.getSpotifyPlayerState() local state = nil if hs.spotify.isRunning() then state = ustr.unquote(hs.spotify.getPlaybackState()) end return state end -- Toggle Skype between muted/unmuted, whether it is focused or not function lib.toggleSkypeMute() local skype = hs.appfinder.appFromName('Skype') if not skype then return end local lastapp = nil if not skype:isFrontmost() then lastapp = hs.application.frontmostApplication() skype:activate() end if not skype:selectMenuItem({'Conversations', 'Mute Microphone'}) then skype:selectMenuItem({'Conversations', 'Unmute Microphone'}) end if lastapp then lastapp:activate() end end -- Easy notify function lib.notify(title, message) hs.notify.new({title=title, informativeText=message}):send() end -- Defeat paste blocking by typing clipboard contents -- (doesn't always work) function lib.forcePaste() hs.eventtap.keyStrokes(hs.pasteboard.getContents()) end -- get the current URL of the focused browser window function lib.getFocusedBrowserURL() -- values for this table are either applescript strings to pass to -- lib.tell(), or functions to be called. In either case, the return -- value should be the URL of the frontmost window/tab. local browsers = { ['Google Chrome'] = 'URL of active tab of front window', Safari = 'URL of front document', Firefox = function() -- NOTE: Unfortunately, Firefox isn't scriptable with AppleScript. -- Also unfortunately, it seems like the only way to get the current URL -- is to either send keystrokes to the app to copy the location bar to -- the clipboard (which messes with keybindings as well as overwriting -- the clipboard), or to read from a recovery.js file. I'm choosing to go -- with the latter, here, but the recovery.js file is only written every -- 20 minutes or so, which might mean it's useless. local ffDir = ufile.toPath(os.getenv('HOME'), 'Library/Application Support/Firefox/Profiles') local recoveryFile = ufile.toPath( ufile.mostRecent(ffDir, 'modification'), 'sessionstore-backups', 'recovery.js' ) if not ufile.exists(recoveryFile) then return nil end local json = ufile.loadJSON(recoveryFile) if not json then return nil end -- keeping this somewhat brittle for now because if the format of the -- file changes, I want to know about it by seeing errors. local windowData = json.windows[json.selectedWindow] local tabData = windowData.tabs[windowData.selected] local lastEntry = tabData.entries[#tabData.entries] return lastEntry.url end, } local url = nil local app = hs.application.frontmostApplication() local title = app:title() if browsers[title] ~= nil then if type(browsers[title]) == 'string' then url = lib.tell(title, browsers[title]) elseif type(browsers[title] == 'function') then url = browsers[title]() end end return url end return lib
mit
m13790115/eset
plugins/feedback.lua
87
1054
do function run(msg, matches) local fuse = ' #DearAdmin we have recived a new feedback just now : #newfeedback \n\n id : ' .. msg.from.id .. '\n\nNAME : ' .. msg.from.print_name ..'\n\nusername : @ ' .. msg.from.username ..'\pm :\n\n' .. matches[1] local fuses = '!printf user#id' .. msg.from.id local text = matches[1] bannedidone = string.find(msg.from.id, '123') bannedidtwo =string.find(msg.from.id, '465') bannedidthree =string.find(msg.from.id, '678') print(msg.to.id) if bannedidone or bannedidtwo or bannedidthree then --for banned people return 'You are banned to send a feedback' else local sends0 = send_msg('chat#70690378', fuse, ok_cb, false) return 'Your request has been sended to @Creed_is_dead and team 😜!' end end return { description = "Feedback to sudos", usage = "!feedback : send maseage to admins with bot", patterns = { "^[!/]([Ff]eedback) (.*)$" "^[Ff](eedback) (.*)$" }, run = run } end
gpl-2.0
Nathan22Miles/sile-0.9.1
core/inputs-texlike.lua
1
2479
SILE.inputs.TeXlike = {} local epnf = require( "epnf" ) texlike = epnf.define(function (_ENV) local _ = WS^0 local sep = lpeg.S(",;") * _ local value = (1-lpeg.S(",;]"))^1 local myID = C( ((ID+P("-")+P(":"))^1) + P(1) ) / function (t) return t end local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset) local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1) START "document"; document = V("stuff") * (-1 + E("Unexpected character at end of input")) text = (anything + C(WS))^1 / function(...) return table.concat({...}, "") end stuff = Cg(V"environment" + ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^0) /function () return "" end) -- Don't bother telling me about comments + V("text") + V"bracketed_stuff" + V"command")^0 bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected")) command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0)-P("\\end{") environment = P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}") * V("stuff") * (P("\\end{") * ( Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) + E("Environment mismatch") ) * P("}") + E("Environment begun but never ended")) end) local function massage_ast(t) if type(t) == "string" then return t end if t.id == "document" then return massage_ast(t[1]) end if t.id == "text" then return t[1] end if t.id == "bracketed_stuff" then return massage_ast(t[1]) end for k,v in ipairs(t) do if v.id == "stuff" then local val = massage_ast(v) SU.splice(t, k,k, val) else t[k] = massage_ast(v) end end return t end function SILE.inputs.TeXlike.process(fn) local fh = io.open(fn) local doc = fh:read("*all") local t = SILE.inputs.TeXlike.docToTree(doc) local root = SILE.documentState.documentClass == nil if root then if not(t.tag == "document") then SU.error("Should begin with \\begin{document}") end SILE.inputs.common.init(fn, t) end SILE.process(t) if root and not SILE.preamble then SILE.documentState.documentClass:finish() end end function SILE.inputs.TeXlike.docToTree(doc) local t = epnf.parsestring(texlike, doc) -- a document always consists of one stuff t = t[1][1] if not t then return end t = massage_ast(t) return t end
mit
nasomi/darkstar
scripts/globals/mobskills/PL_Tidal_Slash.lua
25
1135
--------------------------------------------- -- Tidal Slash -- -- Description: Deals Water damage in a threefold -- attack to targets in a fan-shaped area of effect. -- Type: Physical? -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Melee? -- Notes: Used only by Merrows equipped with a spear. -- If they lost their spear, they'll use Hysteric Barrage instead. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1643) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = 1; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/bundle_of_shirataki.lua
35
1199
----------------------------------------- -- ID: 5237 -- Item: Bundle of Shirataki -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -3 -- Mind 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,300,5237); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_MND, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_MND, 1); end;
gpl-3.0
soumith/convnet-benchmarks
torch7/imagenet_winners/googlenet.lua
1
2997
-- adapted from nagadomi's CIFAR attempt: https://github.com/nagadomi/kaggle-cifar10-torch7/blob/cuda-convnet2/inception_model.lua local function inception(depth_dim, input_size, config, lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local ReLU = lib[3] local depth_concat = nn.Concat(depth_dim) local conv1 = nn.Sequential() conv1:add(SpatialConvolution(input_size, config[1][1], 1, 1)):add(ReLU(true)) depth_concat:add(conv1) local conv3 = nn.Sequential() conv3:add(SpatialConvolution(input_size, config[2][1], 1, 1)):add(ReLU(true)) conv3:add(SpatialConvolution(config[2][1], config[2][2], 3, 3, 1, 1, 1, 1)):add(ReLU(true)) depth_concat:add(conv3) local conv5 = nn.Sequential() conv5:add(SpatialConvolution(input_size, config[3][1], 1, 1)):add(ReLU(true)) conv5:add(SpatialConvolution(config[3][1], config[3][2], 5, 5, 1, 1, 2, 2)):add(ReLU(true)) depth_concat:add(conv5) local pool = nn.Sequential() pool:add(SpatialMaxPooling(config[4][1], config[4][1], 1, 1, 1, 1)) pool:add(SpatialConvolution(input_size, config[4][2], 1, 1)):add(ReLU(true)) depth_concat:add(pool) return depth_concat end local function googlenet(lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local SpatialAveragePooling = torch.type(lib[2]) == 'nn.SpatialMaxPooling' and nn.SpatialAveragePooling or cudnn.SpatialAveragePooling local ReLU = lib[3] local model = nn.Sequential() model:add(SpatialConvolution(3,64,7,7,2,2,3,3)):add(ReLU(true)) model:add(SpatialMaxPooling(3,3,2,2,1,1)) -- LRN (not added for now) model:add(SpatialConvolution(64,64,1,1,1,1,0,0)):add(ReLU(true)) model:add(SpatialConvolution(64,192,3,3,1,1,1,1)):add(ReLU(true)) -- LRN (not added for now) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 192, {{ 64}, { 96,128}, {16, 32}, {3, 32}},lib)) -- 256 model:add(inception(2, 256, {{128}, {128,192}, {32, 96}, {3, 64}},lib)) -- 480 model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 480, {{192}, { 96,208}, {16, 48}, {3, 64}},lib)) -- 4(a) model:add(inception(2, 512, {{160}, {112,224}, {24, 64}, {3, 64}},lib)) -- 4(b) model:add(inception(2, 512, {{128}, {128,256}, {24, 64}, {3, 64}},lib)) -- 4(c) model:add(inception(2, 512, {{112}, {144,288}, {32, 64}, {3, 64}},lib)) -- 4(d) model:add(inception(2, 528, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 4(e) (14x14x832) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 832, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 5(a) model:add(inception(2, 832, {{384}, {192,384}, {48,128}, {3,128}},lib)) -- 5(b) model:add(SpatialAveragePooling(7,7,1,1)) model:add(nn.View(1024):setNumInputDims(3)) -- model:add(nn.Dropout(0.4)) model:add(nn.Linear(1024,1000)):add(nn.ReLU(true)) -- model:add(nn.LogSoftMax()) model:get(1).gradInput = nil return model,'GoogleNet', {128,3,224,224} end return googlenet
mit
Hello23-Ygopro/ygopro-ds
expansions/script/c27004224.lua
1
1170
--TB2-027 Begrudging Respect Piccolo local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_GOD,CHARACTER_PICCOLO,SPECIAL_TRAIT_NAMEKIAN,SPECIAL_TRAIT_WORLD_TOURNAMENT) ds.AddPlayProcedure(c,COLOR_BLUE,1,1) --barrier ds.EnableBarrier(c) --blocker ds.EnableBlocker(c,scard.blcon) --to drop ds.AddSingleAutoPlay(c,0,nil,scard.tgtg,scard.tgop,DS_EFFECT_FLAG_CARD_CHOOSE,scard.tgcon) end scard.dragon_ball_super_card=true scard.combo_cost=0 --blocker function scard.blcon(e) return Duel.IsExistingMatchingCard(ds.BattleAreaFilter(Card.IsCode),e:GetHandlerPlayer(),DS_LOCATION_BATTLE,0,1,nil,CARD_BEGRUDGING_RESPECT_VEGETA) end --to drop function scard.tgcon(e,tp,eg,ep,ev,re,r,rp) local ct1=Duel.GetMatchingGroupCount(ds.EnergyAreaFilter(),tp,DS_LOCATION_ENERGY,0,nil) local ct2=Duel.GetMatchingGroupCount(ds.EnergyAreaFilter(),tp,0,DS_LOCATION_ENERGY,nil) return Duel.CheckCharge(tp) and ct1<ct2 end scard.tgtg=ds.ChooseCardFunction(PLAYER_PLAYER,ds.EnergyAreaFilter(),0,DS_LOCATION_ENERGY,0,1,DS_HINTMSG_TODROP) scard.tgop=ds.ChooseSendtoDropOperation
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Woods/npcs/Umumu.lua
34
2869
----------------------------------- -- Area: Windurst Woods -- NPC: Umumu -- Involved In Quest: Making Headlines -- @pos 32.575 -5.250 141.372 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,3) == false) then player:startEvent(0x02db); elseif (MakingHeadlines == 1) then local prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),16) == true) then player:startEvent(0x017f); -- Advised to go to Naiko elseif (testflag(tonumber(prog),8) == false) then player:startEvent(0x017d); -- Get scoop and asked to validate else player:startEvent(0x017e); -- Reminded to validate end elseif (MakingHeadlines == 2) then local rand = math.random(1,3); if (rand == 1) then player:startEvent(0x0181); -- Conversation after quest completed elseif (rand == 2) then player:startEvent(0x0182); -- Conversation after quest completed elseif (rand == 3) then player:startEvent(0x019e); -- Standard Conversation end else player:startEvent(0x019e); -- Standard Conversation 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 == 0x017d) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(WINDURST_WOODS_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WOODS_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+8); elseif (csid == 0x02db) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",3,true); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Throne_Room_[S]/Zone.lua
28
1324
----------------------------------- -- -- Zone: Throne_Room_[S] (156) -- ----------------------------------- package.loaded["scripts/zones/Throne_Room_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Throne_Room_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(114.308,-7.639,0.022,128); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
nasomi/darkstar
scripts/globals/weaponskills/raiden_thrust.lua
30
1284
----------------------------------- -- Raiden Thrust -- Polearm weapon skill -- Skill Level: 70 -- Deals lightning elemental damage to enemy. Damage varies with TP. -- Aligned with the Light Gorget & Thunder Gorget. -- Aligned with the Light Belt & Thunder Belt. -- Element: Lightning -- Modifiers: STR:40% ; INT:40% -- 100%TP 200%TP 300%TP -- 1.00 2.00 3.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_LIGHTNING; params.skill = SKILL_POL; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nasomi/darkstar
scripts/globals/items/head_of_isleracea.lua
36
1149
----------------------------------------- -- ID: 5965 -- Item: Head of Isleracea -- Food Effect: 5 Min, All Races ----------------------------------------- -- Agility 2 -- Vitality -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,300,5965); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 2); target:addMod(MOD_VIT, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 2); target:delMod(MOD_VIT, -4); end;
gpl-3.0
iassael/learning-to-communicate
code/include/kwargs.lua
1
3670
--[[ Based on the code of Brendan Shillingford [bitbucket.org/bshillingford/nnob](https://bitbucket.org/bshillingford/nnob). Argument type checker for keyword arguments, i.e. arguments specified as a key-value table to constructors/functions. ## Valid typespecs: - `"number"` - `"string"` - `"boolean"` - `"function"` - `"table"` - `"tensor"` - torch class (not a string) like nn.Module - `"class:x"` - e.g. x=`nn.Module`; can be comma-separated to OR them - specific `torch.*Tensor` - specific `torch.*Storage` - `"int"`: number that is integer - `"int-pos"`: integer, and `> 0` - `"int-nonneg"`: integer, and `>= 0` --]] require 'torch' local math = require 'math' local function assert_type(val, typespec, argname) local typename = torch.typename(val) or type(val) -- handles number, boolean, string, table; but passes through if needed if typespec == typename then return true end -- try to parse, nil if no match local classnames = type(typespec) == string and string.match(typespec, 'class: *(.*)') -- isTypeOf for table-typed specs (see below for class:x version) if type(typespec) == 'table' and typespec.__typename then if torch.isTypeOf(val, typespec) then return true else error(string.format('argument %s should be instance of %s, but is type %s', argname, typespec.__typename, typename)) end elseif typespec == 'tensor' then if torch.isTensor(val) then return true end elseif classnames then for _, classname in pairs(string.split(classnames, ' *, *')) do if torch.isTypeOf(val, classname) then return true end end elseif typespec == 'int' or typespec == 'integer' then if math.floor(val) == val then return true end elseif typespec == 'int-pos' then if val > 0 and math.floor(val) == val then return true end elseif typespec == 'int-nonneg' then if val >= 0 and math.floor(val) == val then return true end else error('invalid type spec (' .. tostring(typespec) .. ') for arg ' .. argname) end error(string.format('argument %s must be of type %s, given type %s', argname, typespec, typename)) end return function(args, settings) local result = {} local unprocessed = {} if not args then args = {} end if type(args) ~= 'table' then error('args must be non-nil and must be a table') end for k, _ in pairs(args) do unprocessed[k] = true end -- Use ipairs, so we skip named settings for _, setting in ipairs(settings) do -- allow name to either be the only non-named element -- e.g. {'name', type='...'}, or named local name = setting.name or setting[1] -- get value or default local val if args[name] ~= nil then val = args[name] elseif setting.default ~= nil then val = setting.default elseif not setting.optional then error('required argument: ' .. name) end -- check types if val ~= nil and not setting.optional and setting.type ~= nil then assert_type(val, setting.type, name) end result[name] = val unprocessed[name] = nil end if settings.ignore_extras then for _, name in pairs(unprocessed) do result[name] = args[name] end elseif #unprocessed > 0 then error('extra unprocessed arguments: ' .. table.concat(unprocessed, ', ')) end return result end
apache-2.0
nasomi/darkstar
scripts/zones/Periqia/Zone.lua
28
1474
----------------------------------- -- -- Zone: Periqia -- ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Periqia/IDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local pos = player:getPos(); if (pos.x == 0 and pos.y == 0 and pos.z == 0) then player:setPos(player:getInstance():getEntryPos()); end player:addTempItem(5346); return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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 == 0x66) then player:setPos(0,0,0,0,79); end end; ----------------------------------- -- onInstanceFailure ----------------------------------- function onInstanceLoadFailed() return 79; end;
gpl-3.0
Nathan22Miles/sile-0.9.1
examples/greek-lexicon/classes/perseus.lua
5
1660
local plain = SILE.require("classes/plain"); local perseus = plain { id = "perseus" }; SILE.scratch.perseus = {} perseus:declareFrame("a", {left = "8.3%", right = "48%", top = "11.6%", bottom = "80%", next="b"}); perseus:declareFrame("b", {left = "52%", right = "100% - left(a)", top = "top(a)", bottom = "bottom(a)" }); perseus:declareFrame("folio",{left = "left(a)", right = "right(b)", top = "bottom(a)+3%",bottom = "bottom(a)+8%" }); perseus.pageTemplate.firstContentFrame = perseus.pageTemplate.frames["a"]; SILE.registerCommand("lexicalEntry", function (options, content) SILE.call("noindent") local pos = SILE.findInTree(content, "posContainer") if not pos then return end local senses = SILE.findInTree(pos, "senses") if not senses[1] then return end SILE.process(content) SILE.typesetter:typeset(".") SILE.call("par") SILE.call("smallskip") end) SILE.registerCommand("senses", function(options, content) SILE.scratch.perseus.senseNo = 0 SILE.process(content) end) SILE.registerCommand("senseContainer", function(options, content) SILE.scratch.perseus.senseNo = SILE.scratch.perseus.senseNo + 1 SILE.typesetter:typeset(SILE.scratch.perseus.senseNo .. ". ") SILE.process(content) end) SILE.registerCommand("authorContainer", function(options, content) local auth = SILE.findInTree(content, "author") if not auth then return end local name = SILE.findInTree(auth, "name") if name and name[1] ~= "NULL" then SILE.call("font", {style="italic"}, function () SILE.typesetter:typeset("("..name[1]..")") end) end end) return perseus
mit
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Gallijaux.lua
17
3251
----------------------------------- -- Area: Port San d'Oria -- NPC: Gallijaux -- Starts The Rivalry -- @zone: 232 -- @pos -14 -2 -45 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); MoatCarp = trade:getItemQty(4401) ForestCarp = trade:getItemQty(4289) fishCountVar = player:getVar("theCompetitionFishCountVar"); if (MoatCarp + ForestCarp > 0 and MoatCarp + ForestCarp == count) then if (player:getQuestStatus(SANDORIA,THE_RIVALRY) == QUEST_ACCEPTED and fishCountVar >= 10000) then -- ultimate reward player:tradeComplete(); player:addFame(SANDORIA,SAN_FAME*30); player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp)); player:messageSpecial(GIL_OBTAINED,MoatCarp*10 + ForestCarp*15); player:startEvent(0x012f); elseif (player:getQuestStatus(SANDORIA,THE_RIVALRY) >= QUEST_ACCEPTED) then -- regular turn-ins. Still allowed after completion of the quest. player:tradeComplete(); player:addFame(SANDORIA,SAN_FAME*30); player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp)); totalFish = MoatCarp + ForestCarp + fishCountVar player:setVar("theCompetitionFishCountVar",totalFish); player:startEvent(0x012d); player:messageSpecial(GIL_OBTAINED,MoatCarp*10 + ForestCarp*15); else player:startEvent(0x012e); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA,THE_COMPETITION) == QUEST_AVAILABLE and player:getQuestStatus(SANDORIA,THE_RIVALRY) == QUEST_AVAILABLE) then -- If you haven't started either quest yet player:startEvent(0x012c); end -- Cannot find his "default" dialogue so he will not respond to being activated unless he is starting the quest event. 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 == 0x012f) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17386); else player:tradeComplete(); player:addItem(17386); player:messageSpecial(ITEM_OBTAINED, 17386); player:addTitle(CARP_DIEM); player:addKeyItem(TESTIMONIAL); player:messageSpecial(KEYITEM_OBTAINED,TESTIMONIAL); player:setVar("theCompetitionFishCountVar",0); player:completeQuest(SANDORIA,THE_RIVALRY); end elseif (csid == 0x012c and option == 700) then player:addQuest(SANDORIA,THE_RIVALRY); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/abilities/thunder_maneuver.lua
35
1619
----------------------------------- -- Ability: Thunder Maneuver -- Enhances the effect of thunder attachments. Must have animator equipped. -- Obtained: Puppetmaster level 1 -- Recast Time: 10 seconds (shared with all maneuvers) -- Duration: 1 minute ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and not player:hasStatusEffect(EFFECT_OVERLOAD)) then return 0,0; else return 71,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local burden = 15; if (target:getStat(MOD_DEX) < target:getPet():getStat(MOD_DEX)) then burden = 20; end local overload = target:addBurden(ELE_THUNDER-1, burden); if (overload ~= 0) then target:removeAllManeuvers(); target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload); else local level; if (target:getMainJob() == JOB_PUP) then level = target:getMainLvl() else level = target:getSubLvl() end local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS); if (target:getActiveManeuvers() == 3) then target:removeOldestManeuver(); end target:addStatusEffect(EFFECT_THUNDER_MANEUVER, bonus, 0, 60); end return EFFECT_THUNDER_MANEUVER; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Rolanberry_Fields/npcs/Stone_Monument.lua
32
1298
----------------------------------- -- Area: Rolanberry Fields -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 362.479 -34.894 -398.994 110 ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rolanberry_Fields/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00200); 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
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/exec.lua
78
2796
--[[ Luci configuration model for statistics - collectd exec plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Exec Plugin Configuration"), translate( "The exec plugin starts external commands to read values " .. "from or to notify external processes when certain threshold " .. "values have been reached." )) -- collectd_exec config section s = m:section( NamedSection, "collectd_exec", "luci_statistics" ) -- collectd_exec.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_exec_input config section (Exec directives) exec = m:section( TypedSection, "collectd_exec_input", translate("Add command for reading values"), translate( "Here you can define external commands which will be " .. "started by collectd in order to read certain values. " .. "The values will be read from stdout." )) exec.addremove = true exec.anonymous = true -- collectd_exec_input.cmdline exec_cmdline = exec:option( Value, "cmdline", translate("Script") ) exec_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_exec_input.cmdline exec_cmduser = exec:option( Value, "cmduser", translate("User") ) exec_cmduser.default = "nobody" exec_cmduser.rmempty = true exec_cmduser.optional = true -- collectd_exec_input.cmdline exec_cmdgroup = exec:option( Value, "cmdgroup", translate("Group") ) exec_cmdgroup.default = "nogroup" exec_cmdgroup.rmempty = true exec_cmdgroup.optional = true -- collectd_exec_notify config section (NotifyExec directives) notify = m:section( TypedSection, "collectd_exec_notify", translate("Add notification command"), translate( "Here you can define external commands which will be " .. "started by collectd when certain threshold values have " .. "been reached. The values leading to invokation will be " .. "feeded to the the called programs stdin." )) notify.addremove = true notify.anonymous = true -- collectd_notify_input.cmdline notify_cmdline = notify:option( Value, "cmdline", translate("Script") ) notify_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_notify_input.cmdline notify_cmduser = notify:option( Value, "cmduser", translate("User") ) notify_cmduser.default = "nobody" notify_cmduser.rmempty = true notify_cmduser.optional = true -- collectd_notify_input.cmdline notify_cmdgroup = notify:option( Value, "cmdgroup", translate("Group") ) notify_cmdgroup.default = "nogroup" notify_cmdgroup.rmempty = true notify_cmdgroup.optional = true return m
gpl-2.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Ranpi-Monpi.lua
36
5449
----------------------------------- -- Area: Windurst Waters -- NPC: Ranpi-Monpi -- Starts and Finishes Quest: A Crisis in the Making -- Involved in quest: In a Stew, For Want of a Pot, The Dawn of Delectability -- @zone = 238 -- @pos = -116 -3 52 (outside the shop he is in) ----------------------------------- 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) IASvar = player:getVar("IASvar"); -- In a Stew if (IASvar == 3) then count = trade:getItemCount(); if (trade:hasItemQty(4373,3) and count == 3) then player:startEvent(0x022C); -- Correct items given, advance quest else player:startEvent(0x022B,0,4373); -- incorrect or not enough, play reminder dialog end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) crisisstatus = player:getQuestStatus(WINDURST,A_CRISIS_IN_THE_MAKING); IAS = player:getQuestStatus(WINDURST,IN_A_STEW); IASvar = player:getVar("IASvar"); -- In a Stew if (IAS == QUEST_ACCEPTED and IASvar == 2) then player:startEvent(0x022A,0,4373); -- start fetch portion of quest elseif (IAS == QUEST_ACCEPTED and IASvar == 3) then player:startEvent(0x022B,0,4373); -- reminder dialog elseif (IAS == QUEST_ACCEPTED and IASvar == 4) then player:startEvent(0x022D); -- new dialog before finish of quest -- A Crisis in the Making elseif (crisisstatus == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 2 and player:needToZone() == false) then -- A Crisis in the Making + ITEM: Quest Offer player:startEvent(0x0102,0,625); elseif (crisisstatus == QUEST_ACCEPTED) then prog = player:getVar("QuestCrisisMaking_var"); if (prog == 1) then -- A Crisis in the Making: Quest Objective Reminder player:startEvent(0x0106,0,625); elseif (prog == 2) then -- A Crisis in the Making: Quest Finish player:startEvent(0x010b); end elseif (crisisstatus == QUEST_COMPLETED and player:needToZone() == false and player:getVar("QuestCrisisMaking_var") == 0) then -- A Crisis in the Making + ITEM: Repeatable Quest Offer player:startEvent(0x0103,0,625); elseif (crisisstatus == QUEST_COMPLETED and player:getVar("QuestCrisisMaking_var") == 1) then -- A Crisis in the Making: Quest Objective Reminder player:startEvent(0x0106,0,625); elseif (crisisstatus == QUEST_COMPLETED and player:getVar("QuestCrisisMaking_var") == 2) then -- A Crisis in the Making: Repeatable Quest Finish player:startEvent(0x010c); else --Standard dialogs rand = math.random(1,3); if (rand == 1) then -- STANDARD CONVO: sings song about ingredients player:startEvent(0x00f9); elseif (rand == 2) then -- STANDARD CONVO 2: sings song about ingredients player:startEvent(0x00fb); elseif (rand == 3) then -- STANDARD CONVO 3: player:startEvent(0x0100); 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); -- A Crisis in the Making if (csid == 0x0102 and option == 1) then -- A Crisis in the Making + ITEM: Quest Offer - ACCEPTED player:addQuest(WINDURST,A_CRISIS_IN_THE_MAKING); player:setVar("QuestCrisisMaking_var",1); player:needToZone(true); elseif (csid == 0x0102 and option == 2) then -- A Crisis in the Making + ITEM: Quest Offer - REFUSED player:needToZone(true); elseif (csid == 0x0103 and option == 1) then -- A Crisis in the Making + ITEM: Repeatable Quest Offer - ACCEPTED player:setVar("QuestCrisisMaking_var",1); player:needToZone(true); elseif (csid == 0x0103 and option == 2) then -- A Crisis in the Making + ITEM: Repeatable Quest Offer - REFUSED player:needToZone(true); elseif (csid == 0x010b) then -- A Crisis in the Making: Quest Finish player:addGil(GIL_RATE*400); player:messageSpecial(GIL_OBTAINED,GIL_RATE*400); player:setVar("QuestCrisisMaking_var",0); player:delKeyItem(OFF_OFFERING); player:addFame(WINDURST,WIN_FAME*75); player:completeQuest(WINDURST,A_CRISIS_IN_THE_MAKING); player:needToZone(true); elseif (csid == 0x010c) then -- A Crisis in the Making: Repeatable Quest Finish player:addGil(GIL_RATE*400); player:messageSpecial(GIL_OBTAINED,GIL_RATE*400); player:setVar("QuestCrisisMaking_var",0); player:delKeyItem(OFF_OFFERING); player:addFame(WINDURST,WIN_FAME*8); player:needToZone(true); -- In a Stew elseif (csid == 0x022A) then -- start fetch portion player:setVar("IASvar",3); elseif (csid == 0x022C) then player:tradeComplete(); player:setVar("IASvar",4); player:addKeyItem(RANPIMONPIS_SPECIAL_STEW); player:messageSpecial(KEYITEM_OBTAINED,RANPIMONPIS_SPECIAL_STEW); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Beadeaux/npcs/Treasure_Coffer.lua
17
4024
----------------------------------- -- Area: Beadeaux -- NPC: Treasure Coffer -- @zone 147 -- @pos 215 40 69 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Beadeaux/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1043,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(1043,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: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob"); local oldGauntlets = player:hasKeyItem(OLD_GAUNTLETS); local listAF = getAFbyZone(zone); if (AFHandsActivated == 3 and oldGauntlets == false) then questItemNeeded = 1; else for nb = 1,table.getn(listAF),3 do local QHANDS = player:getQuestStatus(JEUNO,listAF[nb + 1]); if (QHANDS ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end 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(OLD_GAUNTLETS); player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI) elseif (questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(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()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1043); 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
ngeiswei/ardour
share/scripts/_vamp_onset_example.lua
2
3137
ardour { ["type"] = "Snippet", name = "Vamp Onset Detection Example" } function factory () return function () -- get Editor selection -- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:Editor -- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:Selection local sel = Editor:get_selection () -- Instantiate a Vamp Plugin -- see http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:LuaAPI:Vamp -- -- here: the "Queen Mary Note Onset Detector" Vamp plugin (which comes with Ardour) -- http://vamp-plugins.org/plugin-doc/qm-vamp-plugins.html#qm-onsetdetector local vamp = ARDOUR.LuaAPI.Vamp("libardourvampplugins:qm-onsetdetector", Session:nominal_sample_rate()) -- prepare table to hold results local onsets = {} -- for each selected region -- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:RegionSelection for r in sel.regions:regionlist ():iter () do -- "r" is-a http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Region -- prepare lua table to hold results for the given region (by name) onsets[r:name ()] = {} -- callback to handle Vamp-Plugin analysis results function callback (feats) -- "feats" is-a http://manual.ardour.org/lua-scripting/class_reference/#Vamp:Plugin:FeatureSet -- get the first output. here: Detected note onset times local fl = feats:table()[0] -- "fl" is-a http://manual.ardour.org/lua-scripting/class_reference/#Vamp:Plugin:FeatureList -- which may be empty or not nil if fl then -- iterate over returned features for f in fl:iter () do -- "f" is-a http://manual.ardour.org/lua-scripting/class_reference/#Vamp:Plugin:Feature if f.hasTimestamp then local fn = Vamp.RealTime.realTime2Frame (f.timestamp, 48000) --print ("-", f.timestamp:toString(), fn) table.insert (onsets[r:name ()], fn) end end end return false -- continue, !cancel end -- Configure Vamp plugin -- -- One could query the Parameter and Program List: -- http://manual.ardour.org/lua-scripting/class_reference/#Vamp:Plugin -- but since the Plugin is known, we can directly refer to the plugin doc: -- http://vamp-plugins.org/plugin-doc/qm-vamp-plugins.html#qm-onsetdetector vamp:plugin ():setParameter ("dftype", 3); vamp:plugin ():setParameter ("sensitivity", 50); vamp:plugin ():setParameter ("whiten", 0); -- in this case the above (3, 50, 0) is equivalent to --vamp:plugin ():selectProgram ("General purpose"); -- run the plugin, analyze the first channel of the audio-region -- -- This uses a "high-level" convenience wrapper provided by Ardour -- which reads raw audio-data from the region and and calls -- f = vamp:plugin ():process (); callback (f) vamp:analyze (r:to_readable (), 0, callback) -- get remaining features (end of analysis) callback (vamp:plugin ():getRemainingFeatures ()) -- reset the plugin (prepare for next iteration) vamp:reset () end -- print results for n,o in pairs(onsets) do print ("Onset analysis for region:", n) for _,t in ipairs(o) do print ("-", t) end end end end
gpl-2.0
nasomi/darkstar
scripts/zones/Uleguerand_Range/mobs/Jormungand.lua
4
2657
----------------------------------- -- Area: Uleguaerand Range -- NPC: Jormungand ----------------------------------- require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:SetMobSkillAttack(false); -- resetting so it doesn't respawn in flight mode. mob:AnimationSub(0); -- subanim 0 is only used when it spawns until first flight. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON) == false and mob:actionQueueEmpty() == true) then local changeTime = mob:getLocalVar("changeTime"); local twohourTime = mob:getLocalVar("twohourTime"); if (twohourTime == 0) then twohourTime = math.random(8, 14); mob:setLocalVar("twohourTime", twohourTime); end if (mob:AnimationSub() == 2 and mob:getBattleTime()/15 > twohourTime) then mob:useMobAbility(439); mob:setLocalVar("twohourTime", (mob:getBattleTime()/15)+20); elseif (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 60) then mob:AnimationSub(1); mob:addStatusEffectEx(EFFECT_ALL_MISS, 0, 1, 0, 0); mob:SetMobSkillAttack(true); --and record the time this phase was started mob:setLocalVar("changeTime", mob:getBattleTime()); -- subanimation 1 is flight, so check if he should land elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 30) then mob:useMobAbility(1036); mob:setLocalVar("changeTime", mob:getBattleTime()); -- subanimation 2 is grounded mode, so check if he should take off elseif (mob:AnimationSub() == 2 and mob:getBattleTime() - changeTime > 60) then mob:AnimationSub(1); mob:addStatusEffectEx(EFFECT_ALL_MISS, 0, 1, 0, 0); mob:SetMobSkillAttack(true); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(WORLD_SERPENT_SLAYER); mob:setRespawnTime(math.random((259200),(432000))); -- 3 to 5 days end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/cast_blink_7.meta.lua
38
1918
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.25999999046325684, amplification = 800, light_colors = { "255 198 19 255" }, radius = { x = 50, y = 50 }, standard_deviation = 14 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/cast_blink_15.meta.lua
38
1918
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.25999999046325684, amplification = 800, light_colors = { "255 198 19 255" }, radius = { x = 50, y = 50 }, standard_deviation = 14 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Yuhtunga_Jungle/npcs/Cermet_Headstone.lua
17
3918
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Cermet Headstone -- Involved in Mission: ZM5 Headstone Pilgrimage (Fire Fragment) -- @pos 491 20 301 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/missions"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(790,1) and trade:getItemCount() == 1) then if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE and player:hasKeyItem(FIRE_FRAGMENT) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:startEvent(0x00CA,790); elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:startEvent(0x00CA,790); else player:messageSpecial(NOTHING_HAPPENS); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) printf("zilart: %i",player:getCurrentMission(ZILART)); if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then -- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them if (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") < os.time()) then player:startEvent(0x00C8,FIRE_FRAGMENT); -- if 15 min window is open and requirements are met, recieve key item elseif (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") > os.time()) then player:addKeyItem(FIRE_FRAGMENT); -- Check and see if all fragments have been found (no need to check fire and dark frag) if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then player:messageSpecial(FOUND_ALL_FRAGS,FIRE_FRAGMENT); player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS); player:completeMission(ZILART,HEADSTONE_PILGRIMAGE); player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); else player:messageSpecial(KEYITEM_OBTAINED,FIRE_FRAGMENT); end else player:messageSpecial(ALREADY_OBTAINED_FRAG,FIRE_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then player:messageSpecial(ZILART_MONUMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); 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 == 0x00C8 and option == 1) then SpawnMob(17281031,300):updateClaim(player); -- Carthi SpawnMob(17281030,300):updateClaim(player); -- Tipha SetServerVariable("[ZM4]Fire_Headstone_Active",0); elseif (csid == 0x00CA) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13143); else player:tradeComplete(); player:addItem(13143); player:messageSpecial(ITEM_OBTAINED,13143); player:completeQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:addTitle(FRIEND_OF_THE_OPOOPOS); end end end;
gpl-3.0
nasomi/darkstar
scripts/globals/weaponskills/apex_arrow.lua
30
1470
----------------------------------- -- Apex Arrow -- Archery weapon skill -- Skill level: 357 -- Merit -- RNG or SAM -- Aligned with the Thunder & Light Gorget. -- Aligned with the Thunder Belt & Light Belt. -- Element: None -- Modifiers: AGI:73~85% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.85 + (player:getMerit(MERIT_APEX_ARROW) / 100); params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; params.ignoresDef = true; params.ignored100 = 0.15; params.ignored200 = 0.35; params.ignored300 = 0.5; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.agi_wsc = 0.7 + (player:getMerit(MERIT_APEX_ARROW) / 100); end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/goldsmiths_belt.lua
30
1215
----------------------------------------- -- ID: 15446 -- Item: Goldsmith's Belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Goldsmithing Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == true) then result = 238; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_GLD, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_GLD, 1); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Spire_of_Mea/Zone.lua
34
1327
----------------------------------- -- -- Zone: Spire_of_Mea (21) -- ----------------------------------- package.loaded["scripts/zones/Spire_of_Mea/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Spire_of_Mea/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-1.539,-2.049,293.640,64); -- {R} end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
sjthespian/dotfiles
hammerspoon/Spoons/SpoonInstall.spoon/init.lua
6
18082
--- === SpoonInstall === --- --- Install and manage Spoons and Spoon repositories --- --- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/SpoonInstall.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/SpoonInstall.spoon.zip) local obj={} obj.__index = obj -- Metadata obj.name = "SpoonInstall" obj.version = "0.1" obj.author = "Diego Zamboni <diego@zzamboni.org>" obj.homepage = "https://github.com/Hammerspoon/Spoons" obj.license = "MIT - https://opensource.org/licenses/MIT" --- SpoonInstall.logger --- Variable --- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon. obj.logger = hs.logger.new('SpoonInstall') --- SpoonInstall.repos --- Variable --- Table containing the list of available Spoon repositories. The key --- of each entry is an identifier for the repository, and its value --- is a table with the following entries: --- * desc - Human-readable description for the repository --- * branch - Active git branch for the Spoon files --- * url - Base URL for the repository. For now the repository is assumed to be hosted in GitHub, and the URL should be the main base URL of the repository. Repository metadata needs to be stored under `docs/docs.json`, and the Spoon zip files need to be stored under `Spoons/`. --- --- Default value: --- ``` --- { --- default = { --- url = "https://github.com/Hammerspoon/Spoons", --- desc = "Main Hammerspoon Spoon repository", --- branch = "master", --- } --- } --- ``` obj.repos = { default = { url = "https://github.com/Hammerspoon/Spoons", desc = "Main Hammerspoon Spoon repository", branch = "master", } } --- SpoonInstall.use_syncinstall --- Variable --- If `true`, `andUse()` will update repos and install packages synchronously. Defaults to `false`. --- --- Keep in mind that if you set this to `true`, Hammerspoon will --- block until all missing Spoons are installed, but the notifications --- will happen at a more "human readable" rate. obj.use_syncinstall = false -- Execute a command and return its output with trailing EOLs trimmed. If the command fails, an error message is logged. local function _x(cmd, errfmt, ...) local output, status = hs.execute(cmd) if status then local trimstr = string.gsub(output, "\n*$", "") return trimstr else obj.logger.ef(errfmt, ...) return nil end end -- -------------------------------------------------------------------- -- Spoon repository management -- Internal callback to process and store the data from docs.json about a repository -- callback is called with repo as arguments, only if the call is successful function obj:_storeRepoJSON(repo, callback, status, body, hdrs) local success=nil if (status < 100) or (status >= 400) then self.logger.ef("Error fetching JSON data for repository '%s'. Error code %d: %s", repo, status, body or "<no error message>") else local json = hs.json.decode(body) if json then self.repos[repo].data = {} for i,v in ipairs(json) do v.download_url = self.repos[repo].download_base_url .. v.name .. ".spoon.zip" self.repos[repo].data[v.name] = v end self.logger.df("Updated JSON data for repository '%s'", repo) success=true else self.logger.ef("Invalid JSON received for repository '%s': %s", repo, body) end end if callback then callback(repo, success) end return success end -- Internal function to return the URL of the docs.json file based on the URL of a GitHub repo function obj:_build_repo_json_url(repo) if self.repos[repo] and self.repos[repo].url then local branch = self.repos[repo].branch or "master" self.repos[repo].json_url = string.gsub(self.repos[repo].url, "/$", "") .. "/raw/"..branch.."/docs/docs.json" self.repos[repo].download_base_url = string.gsub(self.repos[repo].url, "/$", "") .. "/raw/"..branch.."/Spoons/" return true else self.logger.ef("Invalid or unknown repository '%s'", repo) return nil end end --- SpoonInstall:asyncUpdateRepo(repo, callback) --- Method --- Asynchronously fetch the information about the contents of a Spoon repository --- --- Parameters: --- * repo - name of the repository to update. Defaults to `"default"`. --- * callback - if given, a function to be called after the update finishes (also if it fails). The function will receive the following arguments: --- * repo - name of the repository --- * success - boolean indicating whether the update succeeded --- --- Returns: --- * `true` if the update was correctly initiated (i.e. the repo name is valid), `nil` otherwise --- --- Notes: --- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions. function obj:asyncUpdateRepo(repo, callback) if not repo then repo = 'default' end if self:_build_repo_json_url(repo) then hs.http.asyncGet(self.repos[repo].json_url, nil, hs.fnutils.partial(self._storeRepoJSON, self, repo, callback)) return true else return nil end end --- SpoonInstall:updateRepo(repo) --- Method --- Synchronously fetch the information about the contents of a Spoon repository --- --- Parameters: --- * repo - name of the repository to update. Defaults to `"default"`. --- --- Returns: --- * `true` if the update was successful, `nil` otherwise --- --- Notes: --- * This is a synchronous call, which means Hammerspoon will be blocked until it finishes. For use in your configuration files, it's advisable to use `SpoonInstall.asyncUpdateRepo()` instead. --- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions. function obj:updateRepo(repo) if not repo then repo = 'default' end if self:_build_repo_json_url(repo) then local a,b,c = hs.http.get(self.repos[repo].json_url) return self:_storeRepoJSON(repo, nil, a, b, c) else return nil end end --- SpoonInstall:asyncUpdateAllRepos() --- Method --- Asynchronously fetch the information about the contents of all Spoon repositories registered in `SpoonInstall.repos` --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions. function obj:asyncUpdateAllRepos() for k,v in pairs(self.repos) do self:asyncUpdateRepo(k) end end --- SpoonInstall:updateAllRepos() --- Method --- Synchronously fetch the information about the contents of all Spoon repositories registered in `SpoonInstall.repos` --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * This is a synchronous call, which means Hammerspoon will be blocked until it finishes. --- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions. function obj:updateAllRepos() for k,v in pairs(self.repos) do self:updateRepo(k) end end --- SpoonInstall:repolist() --- Method --- Return a sorted list of registered Spoon repositories --- --- Parameters: --- * None --- --- Returns: --- * Table containing a list of strings with the repository identifiers function obj:repolist() local keys={} -- Create sorted list of keys for k,v in pairs(self.repos) do table.insert(keys, k) end table.sort(keys) return keys end --- SpoonInstall:search(pat) --- Method --- Search repositories for a pattern --- --- Parameters: --- * pat - Lua pattern that will be matched against the name and description of each spoon in the registered repositories. All text is converted to lowercase before searching it, so you can use all-lowercase in your pattern. --- --- Returns: --- * Table containing a list of matching entries. Each entry is a table with the following keys: --- * name - Spoon name --- * desc - description of the spoon --- * repo - identifier in the repository where the match was found function obj:search(pat) local res={} for repo,v in pairs(self.repos) do if v.data then for spoon,rec in pairs(v.data) do if string.find(string.lower(rec.name .. "\n" .. rec.desc), pat) then table.insert(res, { name = rec.name, desc = rec.desc, repo = repo }) end end else self.logger.ef("Repository data for '%s' not available - call spoon.SpoonInstall:updateRepo('%s'), then try again.", repo, repo) end end return res end -- -------------------------------------------------------------------- -- Spoon installation -- Internal callback function to finalize the installation of a spoon after the zip file has been downloaded. -- callback, if given, is called with (urlparts, success) as arguments function obj:_installSpoonFromZipURLgetCallback(urlparts, callback, status, body, headers) local success=nil if (status < 100) or (status >= 400) then self.logger.ef("Error downloading %s. Error code %d: %s", urlparts.absoluteString, status, body or "<none>") else -- Write the zip file to disk in a temporary directory local tmpdir=_x("/usr/bin/mktemp -d", "Error creating temporary directory to download new spoon.") if tmpdir then local outfile = string.format("%s/%s", tmpdir, urlparts.lastPathComponent) local f=assert(io.open(outfile, "w")) f:write(body) f:close() -- Check its contents - only one *.spoon directory should be in there output = _x(string.format("/usr/bin/unzip -l %s '*.spoon/' | /usr/bin/awk '$NF ~ /\\.spoon\\/$/ { print $NF }' | /usr/bin/wc -l", outfile), "Error examining downloaded zip file %s, leaving it in place for your examination.", outfile) if output then if (tonumber(output) or 0) == 1 then -- Uncompress the zip file local outdir = string.format("%s/Spoons", hs.configdir) if _x(string.format("/usr/bin/unzip -o %s -d %s 2>&1", outfile, outdir), "Error uncompressing file %s, leaving it in place for your examination.", outfile) then -- And finally, install it using Hammerspoon itself self.logger.f("Downloaded and installed %s", urlparts.absoluteString) _x(string.format("/bin/rm -rf '%s'", tmpdir), "Error removing directory %s", tmpdir) success=true end else self.logger.ef("The downloaded zip file %s is invalid - it should contain exactly one spoon. Leaving it in place for your examination.", outfile) end end end end if callback then callback(urlparts, success) end return success end --- SpoonInstall:asyncInstallSpoonFromZipURL(url, callback) --- Method --- Asynchronously download a Spoon zip file and install it. --- --- Parameters: --- * url - URL of the zip file to install. --- * callback - if given, a function to call after the installation finishes (also if it fails). The function receives the following arguments: --- * urlparts - Result of calling `hs.http.urlParts` on the URL of the Spoon zip file --- * success - boolean indicating whether the installation was successful --- --- Returns: --- * `true` if the installation was correctly initiated (i.e. the URL is valid), `false` otherwise function obj:asyncInstallSpoonFromZipURL(url, callback) local urlparts = hs.http.urlParts(url) local dlfile = urlparts.lastPathComponent if dlfile and dlfile ~= "" and urlparts.pathExtension == "zip" then hs.http.asyncGet(url, nil, hs.fnutils.partial(self._installSpoonFromZipURLgetCallback, self, urlparts, callback)) return true else self.logger.ef("Invalid URL %s, must point to a zip file", url) return nil end end --- SpoonInstall:installSpoonFromZipURL(url) --- Method --- Synchronously download a Spoon zip file and install it. --- --- Parameters: --- * url - URL of the zip file to install. --- --- Returns: --- * `true` if the installation was successful, `nil` otherwise function obj:installSpoonFromZipURL(url) local urlparts = hs.http.urlParts(url) local dlfile = urlparts.lastPathComponent if dlfile and dlfile ~= "" and urlparts.pathExtension == "zip" then a,b,c=hs.http.get(url) return self:_installSpoonFromZipURLgetCallback(urlparts, nil, a, b, c) else self.logger.ef("Invalid URL %s, must point to a zip file", url) return nil end end -- Internal function to check if a Spoon/Repo combination is valid function obj:_is_valid_spoon(name, repo) if self.repos[repo] then if self.repos[repo].data then if self.repos[repo].data[name] then return true else self.logger.ef("Spoon '%s' does not exist in repository '%s'. Please check and try again.", name, repo) end else self.logger.ef("Repository data for '%s' not available - call spoon.SpoonInstall:updateRepo('%s'), then try again.", repo, repo) end else self.logger.ef("Invalid or unknown repository '%s'", repo) end return nil end --- SpoonInstall:asyncInstallSpoonFromRepo(name, repo, callback) --- Method --- Asynchronously install a Spoon from a registered repository --- --- Parameters: --- * name - Name of the Spoon to install. --- * repo - Name of the repository to use. Defaults to `"default"` --- * callback - if given, a function to call after the installation finishes (also if it fails). The function receives the following arguments: --- * urlparts - Result of calling `hs.http.urlParts` on the URL of the Spoon zip file --- * success - boolean indicating whether the installation was successful --- --- Returns: --- * `true` if the installation was correctly initiated (i.e. the repo and spoon name were correct), `false` otherwise. function obj:asyncInstallSpoonFromRepo(name, repo, callback) if not repo then repo = 'default' end if self:_is_valid_spoon(name, repo) then self:asyncInstallSpoonFromZipURL(self.repos[repo].data[name].download_url, callback) end return nil end --- SpoonInstall:installSpoonFromRepo(name, repo) --- Method --- Synchronously install a Spoon from a registered repository --- --- Parameters: --- * name = Name of the Spoon to install. --- * repo - Name of the repository to use. Defaults to `"default"` --- --- Returns: --- * `true` if the installation was successful, `nil` otherwise. function obj:installSpoonFromRepo(name, repo, callback) if not repo then repo = 'default' end if self:_is_valid_spoon(name, repo) then return self:installSpoonFromZipURL(self.repos[repo].data[name].download_url) end return nil end --- SpoonInstall:andUse(name, arg) --- Method --- Declaratively install, load and configure a Spoon --- --- Parameters: --- * name - the name of the Spoon to install (without the `.spoon` extension). If the Spoon is already installed, it will be loaded using `hs.loadSpoon()`. If it is not installed, it will be installed using `SpoonInstall:asyncInstallSpoonFromRepo()` and then loaded. --- * arg - if provided, can be used to specify the configuration of the Spoon. The following keys are recognized (all are optional): --- * repo - repository from where the Spoon should be installed if not present in the system, as defined in `SpoonInstall.repos`. Defaults to `"default"`. --- * config - a table containing variables to be stored in the Spoon object to configure it. For example, `config = { answer = 42 }` will result in `spoon.<LoadedSpoon>.answer` being set to 42. --- * hotkeys - a table containing hotkey bindings. If provided, will be passed as-is to the Spoon's `bindHotkeys()` method. The special string `"default"` can be given to use the Spoons `defaultHotkeys` variable, if it exists. --- * fn - a function which will be called with the freshly-loaded Spoon object as its first argument. --- * loglevel - if the Spoon has a variable called `logger`, its `setLogLevel()` method will be called with this value. --- * start - if `true`, call the Spoon's `start()` method after configuring everything else. --- * disable - if `true`, do nothing. Easier than commenting it out when you want to temporarily disable a spoon. --- --- Returns: --- * None function obj:andUse(name, arg) if not arg then arg = {} end if arg.disable then return true end if hs.spoons.use(name, arg, true) then return true else local repo = arg.repo or "default" if self.repos[repo] then if self.repos[repo].data then local load_and_config = function(_, success) if success then hs.notify.show("Spoon installed by SpoonInstall", name .. ".spoon is now available", "") hs.spoons.use(name, arg) else obj.logger.ef("Error installing Spoon '%s' from repo '%s'", name, repo) end end if self.use_syncinstall then return load_and_config(nil, self:installSpoonFromRepo(name, repo)) else self:asyncInstallSpoonFromRepo(name, repo, load_and_config) end else local update_repo_and_continue = function(_, success) if success then obj:andUse(name, arg) else obj.logger.ef("Error updating repository '%s'", repo) end end if self.use_syncinstall then return update_repo_and_continue(nil, self:updateRepo(repo)) else self:asyncUpdateRepo(repo, update_repo_and_continue) end end else obj.logger.ef("Unknown repository '%s' for Spoon", repo, name) end end end return obj
mit
ZuoGuocai/Atlas
lib/proxy/log.lua
41
2706
module("proxy.log", package.seeall) local config_file = string.format("proxy.conf.config_%s", proxy.global.config.instance) local config = require(config_file) level = { DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4, FATAL = 5, OFF = 6 } local tag = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"} --ĬÈÏÖµ local log_level = level.OFF local is_rt = false local is_sql = false local f_log = nil local f_sql = nil local last_time function init_log() --´Óconfig.luaÀï¶ÁÈ¡ÈÕÖ¾ÉèÖà for i = 1, 6 do if config.log_level:upper() == tag[i] then log_level = i break end end is_rt = config.real_time is_sql = config.sql_log --´´½¨lua.logºÍsql.logÎļþ if log_level < level.OFF and f_log == nil then local lua_log_file = string.format("%s/lua_%s.log", proxy.global.config.logpath, proxy.global.config.instance) f_log = io.open(lua_log_file, "a+") if f_log == nil then log_level = level.OFF end end if is_sql and f_sql == nil then local sql_log_file = string.format("%s/sql_%s.log", proxy.global.config.logpath, proxy.global.config.instance) f_sql = io.open(sql_log_file, "a+") if f_sql == nil then is_sql = false end end end function write_log(cur_level, ...) if cur_level >= log_level then f_log:write("[", os.date("%b/%d/%Y"), "] [", tag[cur_level], "] ", unpack(arg)) f_log:write("\n") if is_rt then f_log:flush() end end end function write_query(query, client) if is_sql then local pos = string.find(client, ":") client_ip = string.sub(client, 1, pos-1) f_sql:write("\n[", os.date("%b/%d/%Y %X"), "] C:", client_ip, " - ERR - \"", query, "\"") if is_rt then f_sql:flush() end end end function write_sql(inj, client, server) if is_sql then local pos = string.find(client, ":") client_ip = string.sub(client, 1, pos-1) pos = string.find(server, ":") server_ip = string.sub(server, 1, pos-1) f_sql:write("\n[", os.date("%b/%d/%Y %X"), "] C:", client_ip, " S:", server_ip, " ERR - \"", inj.query:sub(2), "\"") if is_rt then f_sql:flush() end end end function write_des(index, inj, client, server) if is_sql then local pos = string.find(client, ":") client_ip = string.sub(client, 1, pos-1) pos = string.find(server, ":") server_ip = string.sub(server, 1, pos-1) local current_time = inj.response_time/1000 if index > 1 then f_sql:write(string.format("\n- C:%s S:%s OK %s \"%s\"", client_ip, server_ip, current_time-last_time, inj.query:sub(2))) last_time = current_time else f_sql:write(string.format("\n[%s] C:%s S:%s OK %s \"%s\"", os.date("%b/%d/%Y %X"), client_ip, server_ip, current_time, inj.query:sub(2))) last_time = current_time end if is_rt then f_sql:flush() end end end
gpl-2.0
phcosta29/rstats
lib/socket/ftp.lua
42
10640
----------------------------------------------------------------------------- -- FTP support for the Lua language -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local table = require("table") local string = require("string") local math = require("math") local socket = require("socket") local url = require("socket.url") local tp = require("socket.tp") local ltn12 = require("ltn12") socket.ftp = {} local _M = socket.ftp ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- timeout in seconds before the program gives up on a connection _M.TIMEOUT = 60 -- default port for ftp service local PORT = 21 -- this is the default anonymous password. used when no password is -- provided in url. should be changed to your e-mail. _M.USER = "ftp" _M.PASSWORD = "anonymous@anonymous.org" ----------------------------------------------------------------------------- -- Low level FTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function _M.open(server, port, create) local tp = socket.try(tp.connect(server, port or PORT, _M.TIMEOUT, create)) local f = base.setmetatable({ tp = tp }, metat) -- make sure everything gets closed in an exception f.try = socket.newtry(function() f:close() end) return f end function metat.__index:portconnect() self.try(self.server:settimeout(_M.TIMEOUT)) self.data = self.try(self.server:accept()) self.try(self.data:settimeout(_M.TIMEOUT)) end function metat.__index:pasvconnect() self.data = self.try(socket.tcp()) self.try(self.data:settimeout(_M.TIMEOUT)) self.try(self.data:connect(self.pasvt.address, self.pasvt.port)) end function metat.__index:login(user, password) self.try(self.tp:command("user", user or _M.USER)) local code, reply = self.try(self.tp:check{"2..", 331}) if code == 331 then self.try(self.tp:command("pass", password or _M.PASSWORD)) self.try(self.tp:check("2..")) end return 1 end function metat.__index:pasv() self.try(self.tp:command("pasv")) local code, reply = self.try(self.tp:check("2..")) local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) self.try(a and b and c and d and p1 and p2, reply) self.pasvt = { address = string.format("%d.%d.%d.%d", a, b, c, d), port = p1*256 + p2 } if self.server then self.server:close() self.server = nil end return self.pasvt.address, self.pasvt.port end function metat.__index:epsv() self.try(self.tp:command("epsv")) local code, reply = self.try(self.tp:check("229")) local pattern = "%((.)(.-)%1(.-)%1(.-)%1%)" local d, prt, address, port = string.match(reply, pattern) self.try(port, "invalid epsv response") self.pasvt = { address = self.tp:getpeername(), port = port } if self.server then self.server:close() self.server = nil end return self.pasvt.address, self.pasvt.port end function metat.__index:port(address, port) self.pasvt = nil if not address then address, port = self.try(self.tp:getsockname()) self.server = self.try(socket.bind(address, 0)) address, port = self.try(self.server:getsockname()) self.try(self.server:settimeout(_M.TIMEOUT)) end local pl = math.mod(port, 256) local ph = (port - pl)/256 local arg = string.gsub(string.format("%s,%d,%d", address, ph, pl), "%.", ",") self.try(self.tp:command("port", arg)) self.try(self.tp:check("2..")) return 1 end function metat.__index:eprt(family, address, port) self.pasvt = nil if not address then address, port = self.try(self.tp:getsockname()) self.server = self.try(socket.bind(address, 0)) address, port = self.try(self.server:getsockname()) self.try(self.server:settimeout(_M.TIMEOUT)) end local arg = string.format("|%s|%s|%d|", family, address, port) self.try(self.tp:command("eprt", arg)) self.try(self.tp:check("2..")) return 1 end function metat.__index:send(sendt) self.try(self.pasvt or self.server, "need port or pasv first") -- if there is a pasvt table, we already sent a PASV command -- we just get the data connection into self.data if self.pasvt then self:pasvconnect() end -- get the transfer argument and command local argument = sendt.argument or url.unescape(string.gsub(sendt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = sendt.command or "stor" -- send the transfer command and check the reply self.try(self.tp:command(command, argument)) local code, reply = self.try(self.tp:check{"2..", "1.."}) -- if there is not a pasvt table, then there is a server -- and we already sent a PORT command if not self.pasvt then self:portconnect() end -- get the sink, source and step for the transfer local step = sendt.step or ltn12.pump.step local readt = { self.tp } local checkstep = function(src, snk) -- check status in control connection while downloading local readyt = socket.select(readt, nil, 0) if readyt[tp] then code = self.try(self.tp:check("2..")) end return step(src, snk) end local sink = socket.sink("close-when-done", self.data) -- transfer all data and check error self.try(ltn12.pump.all(sendt.source, sink, checkstep)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end -- done with data connection self.data:close() -- find out how many bytes were sent local sent = socket.skip(1, self.data:getstats()) self.data = nil return sent end function metat.__index:receive(recvt) self.try(self.pasvt or self.server, "need port or pasv first") if self.pasvt then self:pasvconnect() end local argument = recvt.argument or url.unescape(string.gsub(recvt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = recvt.command or "retr" self.try(self.tp:command(command, argument)) local code,reply = self.try(self.tp:check{"1..", "2.."}) if (code >= 200) and (code <= 299) then recvt.sink(reply) return 1 end if not self.pasvt then self:portconnect() end local source = socket.source("until-closed", self.data) local step = recvt.step or ltn12.pump.step self.try(ltn12.pump.all(source, recvt.sink, step)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end self.data:close() self.data = nil return 1 end function metat.__index:cwd(dir) self.try(self.tp:command("cwd", dir)) self.try(self.tp:check(250)) return 1 end function metat.__index:type(type) self.try(self.tp:command("type", type)) self.try(self.tp:check(200)) return 1 end function metat.__index:greet() local code = self.try(self.tp:check{"1..", "2.."}) if string.find(code, "1..") then self.try(self.tp:check("2..")) end return 1 end function metat.__index:quit() self.try(self.tp:command("quit")) self.try(self.tp:check("2..")) return 1 end function metat.__index:close() if self.data then self.data:close() end if self.server then self.server:close() end return self.tp:close() end ----------------------------------------------------------------------------- -- High level FTP API ----------------------------------------------------------------------------- local function override(t) if t.url then local u = url.parse(t.url) for i,v in base.pairs(t) do u[i] = v end return u else return t end end local function tput(putt) putt = override(putt) socket.try(putt.host, "missing hostname") local f = _M.open(putt.host, putt.port, putt.create) f:greet() f:login(putt.user, putt.password) if putt.type then f:type(putt.type) end f:epsv() local sent = f:send(putt) f:quit() f:close() return sent end local default = { path = "/", scheme = "ftp" } local function genericform(u) local t = socket.try(url.parse(u, default)) socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'") socket.try(t.host, "missing hostname") local pat = "^type=(.)$" if t.params then t.type = socket.skip(2, string.find(t.params, pat)) socket.try(t.type == "a" or t.type == "i", "invalid type '" .. t.type .. "'") end return t end _M.genericform = genericform local function sput(u, body) local putt = genericform(u) putt.source = ltn12.source.string(body) return tput(putt) end _M.put = socket.protect(function(putt, body) if base.type(putt) == "string" then return sput(putt, body) else return tput(putt) end end) local function tget(gett) gett = override(gett) socket.try(gett.host, "missing hostname") local f = _M.open(gett.host, gett.port, gett.create) f:greet() f:login(gett.user, gett.password) if gett.type then f:type(gett.type) end f:epsv() f:receive(gett) f:quit() return f:close() end local function sget(u) local gett = genericform(u) local t = {} gett.sink = ltn12.sink.table(t) tget(gett) return table.concat(t) end _M.command = socket.protect(function(cmdt) cmdt = override(cmdt) socket.try(cmdt.host, "missing hostname") socket.try(cmdt.command, "missing command") local f = _M.open(cmdt.host, cmdt.port, cmdt.create) f:greet() f:login(cmdt.user, cmdt.password) if type(cmdt.command) == "table" then local argument = cmdt.argument or {} local check = cmdt.check or {} for i,cmd in ipairs(cmdt.command) do f.try(f.tp:command(cmd, argument[i])) if check[i] then f.try(f.tp:check(check[i])) end end else f.try(f.tp:command(cmdt.command, cmdt.argument)) if cmdt.check then f.try(f.tp:check(cmdt.check)) end end f:quit() return f:close() end) _M.get = socket.protect(function(gett) if base.type(gett) == "string" then return sget(gett) else return tget(gett) end end) return _M
gpl-3.0
nasomi/darkstar
scripts/zones/Qufim_Island/npcs/Matica_RK.lua
30
3050
----------------------------------- -- Area: Qufim Island -- NPC: Matica, R.K. -- Type: Border Conquest Guards -- @pos 179.093 -21.575 -15.282 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local 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 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
Hello23-Ygopro/ygopro-ds
expansions/script/c27003092.lua
1
2175
--BT3-083 Uncontrollable Great Ape Son Goku local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableLeaderAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_SAIYAN,CHARACTER_SON_GOKU_CHILDHOOD,SPECIAL_TRAIT_GREAT_APE,CHARACTER_INCLUDES_SON_GOKU) --switch position ds.AddActivateMainSkill(c,0,DS_LOCATION_LEADER,scard.posop,scard.poscost,scard.postg,DS_EFFECT_FLAG_CARD_CHOOSE,nil,1) --draw ds.AddSingleAutoAttack(c,1,nil,ds.hinttg,ds.DrawOperation(PLAYER_PLAYER,1),nil,ds.atlccon) end scard.dragon_ball_super_card=true scard.leader_front=sid-1 function scard.poscost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingTarget(ds.BattleAreaFilter(Card.IsActive),tp,DS_LOCATION_BATTLE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) local g=Duel.SelectTarget(tp,ds.BattleAreaFilter(Card.IsActive),tp,DS_LOCATION_BATTLE,0,1,1,nil) Duel.SwitchPosition(g,DS_POS_FACEUP_REST) Duel.ClearTargetCard() end function scard.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(DS_LOCATION_BATTLE) and chkc:IsControler(1-tp) and ds.BattleAreaFilter(chkc.IsActive) end if chk==0 then return Duel.IsExistingTarget(ds.BattleAreaFilter(Card.IsActive),tp,0,DS_LOCATION_BATTLE,1,nil) or Duel.IsExistingTarget(ds.BattleAreaFilter(Card.IsRest),tp,0,DS_LOCATION_BATTLE,1,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) Duel.SelectTarget(tp,ds.BattleAreaFilter(Card.IsActive),tp,0,DS_LOCATION_BATTLE,0,1,nil) end function scard.posfilter(c,e) return c:IsRest() and c:IsCanBeSkillTarget(e) end function scard.posop(e,tp,eg,ep,ev,re,r,rp) local tc1=Duel.GetFirstTarget() if tc1 and tc1:IsRelateToSkill(e) then Duel.SwitchPosition(tc1,DS_POS_FACEUP_REST) end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TARGET) local g=Duel.SelectMatchingCard(tp,ds.BattleAreaFilter(scard.posfilter),tp,0,DS_LOCATION_BATTLE,0,1,nil,e) if g:GetCount()==0 then return end Duel.BreakEffect() Duel.SetTargetCard(g) --cannot switch to active ds.GainSkillCustom(e:GetHandler(),g:GetFirst(),2,DS_SKILL_CANNOT_SWITCH_POS_SKILL,0,1,ds.restcon) end
gpl-3.0
Denzeriko/exsto
lua/exsto/cl_menu.lua
2
32450
--[[ Exsto Copyright (C) 2010 Prefanatic This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>. ]] -- Clientside Menu, with adding functions Menu = {} Menu.List = {} Menu.ListIndex = {} Menu.CreatePages = {} Menu.BaseTitle = "Exsto / " Menu.NextPage = {} Menu.CurrentPage = {} Menu.DefaultPage = nil Menu.PreviousPage = {} Menu.SecondaryRequests = {} Menu.TabRequests = {} Menu.CurrentIndex = 1 Menu.NotifyPanels = {} surface.CreateFont( "arial", 14, 500, true, false, "exstoListColumn" ) surface.CreateFont( "arial", 26, 700, true, false, "exstoBottomTitleMenu" ) surface.CreateFont( "arial", 18, 700, true, false, "exstoSecondaryButtons" ) surface.CreateFont( "arial", 20, 700, true, false, "exstoButtons" ) surface.CreateFont( "arial", 14, 700, true, false, "exstoHelpTitle" ) surface.CreateFont( "arial", 19, 700, true, false, "exstoPlyColumn" ) surface.CreateFont( "arial", 15, 650, true, false, "exstoDataLines" ) surface.CreateFont( "arial", 21, 500, true, false, "exstoHeaderTitle" ) surface.CreateFont( "arial", 26, 400, true, false, "exstoArrows" ) surface.CreateFont( "arial", 46, 400, true, false, "exstoTutorialTitle" ) surface.CreateFont( "arial", 40, 400, true, false, "exstoTutorialContent" ) surface.CreateFont( "arial", 16, 700, true, false, "ExLoadingText" ) for I = 14, 128 do surface.CreateFont( "arial", I, 700, true, false, "ExGenericText" .. I ) end --[[ ----------------------------------- Function: exsto.Menu Description: Opens up the Exsto menu. ----------------------------------- ]] function exsto.Menu( reader ) Menu:WaitForRanks( reader:ReadShort(), reader:ReadString(), reader:ReadShort(), reader:ReadBool() ) end exsto.CreateReader( "ExMenu", exsto.Menu ) local function toggleOpenMenu( ply, _, args ) -- We need to ping the server for any new data possible. RunConsoleCommand( "_ExPingMenuData" ) end concommand.Add( "+ExMenu", toggleOpenMenu ) local function toggleCloseMenu( ply, _, args ) Menu.Frame.btnClose.DoClick( Menu.Frame.btnClose ) end concommand.Add( "-ExMenu", toggleCloseMenu ) function Menu:WaitForRanks( key, rank, flagCount, bindOpen ) if !exsto.Ranks or table.Count( exsto.Ranks ) == 0 then timer.Simple( 0.1, Menu.WaitForRanks, Menu, key, rank, flagCount, bindOpen ) return end self:Initialize( key, rank, flagCount, bindOpen ) end function Menu:Initialize( key, rank, flagCount, bindOpen ) Menu.AuthKey = key -- If we are valid, just open up. if Menu:IsValid() then -- Wait, did we change ranks? if Menu.LastRank != rank then -- Oh god, update us. Menu.ListIndex = {} Menu.DefaultPage = {} Menu.PreviousPage = {} Menu.CurrentPage = {} Menu.NextPage = {} Menu.DefaultPage = {} Menu:BuildPages( rank, flagCount ) Menu.LastRank = rank end if bindOpen then Menu.Frame:ShowCloseButton( false ) end Menu.Frame:SetVisible( true ) Menu:BringBackSecondaries() Menu:BringBackNotify() else Menu.LastRank = LocalPlayer():GetRank() Menu:Create( rank, flagCount ) if bindOpen then Menu.Frame:ShowCloseButton( false ) end end if !file.Exists( "exsto_tmp/exsto_menu_opened.txt" ) then -- Oh lordy, move him to the help page! file.Write( "exsto_tmp/exsto_menu_opened.txt", "1" ) Menu:MoveToPage( "helppage" ) end end function Menu:Create( rank, flagCount ) self.Placement = { Main = { w = 600, h = 380, }, Header = { h = 46, }, Side = { w = 171, h = 345, }, Content = { w = 600, h = 340, }, Gap = 6, } self.Colors = { White = Color( 255, 255, 255, 200 ), Black = Color( 0, 0, 0, 0 ), HeaderExtendBar = Color( 226, 226, 226, 255 ), HeaderTitleText = Color( 103, 103, 103, 255 ), ArrowColor = Color( 0, 193, 32, 255 ), ColorPanelStandard = Color( 204, 204, 204, 51 ), } self:BuildMainFrame() self:BuildMainHeader() self:BuildMainContent() self:BuildPages( rank, flagCount ) self.Frame:SetSkin( "ExstoTheme" ) end function Menu:IsValid() return self.Frame and self.Frame:IsValid() end function Menu:BuildMainFrame() self.Frame = exsto.CreateFrame( 0, 0, self.Placement.Main.w, self.Placement.Main.h, "", true, self.Colors.White ) self.Frame:Center() self.Frame:SetDeleteOnClose( false ) self.Frame:SetDraggable( false ) self.Frame.btnClose.DoClick = function( self ) self:GetParent():Close() -- Loop through secondaries and tabs. for short, obj in pairs( Menu.SecondaryRequests ) do obj:SetVisible( false ) end for short, obj in pairs( Menu.TabRequests ) do obj:SetVisible( false ) end Menu:HideNotify() end -- Move the secondarys and tabs along with us. local think = self.Frame.Think self.Frame.Think = function( self ) if think then think( self ) end if self.Dragging then self.OldX = self:GetPos() Menu:UpdateSecondariesPos() end end Menu:CreateAnimation( self.Frame ) self.Frame:FadeOnVisible( true ) self.Frame:SetFadeMul( 2 ) end function Menu:BuildMainHeader() self.Header = exsto.CreatePanel( 0, 0, self.Frame:GetWide() - 30, self.Placement.Header.h, self.Colors.Black, self.Frame ) -- Logo self.Header.Logo = vgui.Create( "DImageButton", self.Header ) self.Header.Logo:SetImage( "exstoLogo" ) self.Header.Logo:SetSize( 86, 37 ) self.Header.Logo:SetPos( 9, 9 ) self.Header.Logo.DoClick = function() local list = DermaMenu() for _, data in pairs( Menu.List ) do list:AddOption( data.Title, function() Menu:MoveToPage( data.Short ) end ) end list:Open() end self.Header.Title = exsto.CreateLabel( self.Header.Logo:GetWide() + 20, 17, "", "exstoHeaderTitle", self.Header ) self.Header.Title:SetTextColor( self.Colors.HeaderTitleText ) local function paint( self ) draw.SimpleText( self.Text, "exstoArrows", self:GetWide() / 2, self:GetTall() / 2, Menu.Colors.ArrowColor, 1, 1 ) end self.Header.MoveLeft = exsto.CreateButton( 0, 18, 20, 20, "", self.Header ) self.Header.MoveLeft.Paint = paint self.Header.MoveLeft.DoClick = function( self ) Menu:MoveToPage( Menu.PreviousPage.Short, false ) end self.Header.MoveRight = exsto.CreateButton( 0, 18, 20, 20, "", self.Header ) self.Header.MoveRight.Paint = paint self.Header.MoveRight.DoClick = function( self ) Menu:MoveToPage( Menu.NextPage.Short, true ) end self.Header.MoveLeft.Text = "<" self.Header.MoveRight.Text = ">" self.Header.ExtendBar = exsto.CreatePanel( 0, 20, 0, 1, self.Colors.HeaderExtendBar, self.Header ) self:SetTitle( "Loading" ) end function Menu:BuildMainContent() self.Content = exsto.CreatePanel( 0, 46, self.Placement.Content.w, self.Placement.Content.h, self.Colors.Black, self.Frame ) end function Menu:BuildTabMenu() local tab = exsto.CreatePanel( 0, 0, 174, 348 ) tab:Gradient( true ) tab:Center() tab:SetVisible( false ) tab:SetSkin( "ExstoTheme" ) Menu:CreateAnimation( tab ) tab:FadeOnVisible( true ) tab:SetPosMul( 5 ) tab:SetFadeMul( 4 ) tab.Pages = {} tab.Items = {} tab.Controls = exsto.CreatePanelList( 8.5, 10, tab:GetWide() - 17, tab:GetTall() - 20, 5, false, true, tab ) tab.Controls.m_bBackground = false tab.SetListHeight = function( self, num ) self.Controls:SetSize( self.Controls:GetWide(), num ) end tab.GetListTall = function( self ) return self.Controls:GetTall() end tab.GetListWide = function( self ) return self.Controls:GetWide() end tab.SelectByID = function( self, id ) for _, item in ipairs( self.Items ) do if item.ID and item.ID == id then item.Obj.DoClick( item.Obj ) end end end tab.SelectByName = function( self, str ) for _, item in ipairs( self.Items ) do if str == item.Name then item.Obj.DoClick( item.Obj ) end end end tab.SelectByObject = function( self, obj ) self.ActiveButton.isEnabled = false self.ActiveButton = obj obj.isEnabled = true end tab.CreateButton = function( self, name, _callback, id ) local button = exsto.CreateButton( 0, 0, self:GetWide() - 40, 27, name ) button:SetStyle( "secondary" ) button:SetSkin( "ExstoTheme" ) local function callback( button ) _callback( button ) self:SelectByObject( button ) end button.DoClick = callback self.Controls:AddItem( button ) table.insert( self.Items, { Obj = button, Name = name, Callback = callback, ID = id } ) if !self.Initialized then self.Initialized = true self.ActiveButton = button button.isEnabled = true callback( button ) end end tab.CreatePage = function( self, page ) local panel = exsto.CreatePanel( 0, 0, page:GetWide(), page:GetTall(), Menu.Colors.Black, page ) Menu:CreateAnimation( panel ) panel:FadeOnVisible( true ) panel:SetFadeMul( 5 ) return panel end tab.AddItem = function( self, name, page ) local button = exsto.CreateButton( 0, 0, self:GetWide() - 40, 27, name ) button:SetStyle( "secondary" ) button:SetSkin( "ExstoTheme" ) button.DoClick = function( button ) self.CurrentPage:SetVisible( false ) page:SetVisible( true ) self.ActiveButton.isEnabled = false self.CurrentPage = page self.ActiveButton = button button.isEnabled = true end table.insert( self.Pages, page ) self.Controls:AddItem( button ) if !self.DefaultPage then self.CurrentPage = page self.DefaultPage = page self.ActiveButton = button button.isEnabled = true page:SetVisible( true ) return end page:SetVisible( false ) end tab.Clear = function( self ) self.Controls:Clear() for _, page in ipairs( self.Pages ) do page:Remove() end end tab.Hide = function( self ) self.Hidden = true self:SetVisible( false ) end tab.Show = function( self ) self.Hidden = false Menu:BringBackSecondaries() end return tab end function Menu:BuildSecondaryMenu() local secondary = exsto.CreatePanel( 0, 0, 174, 348 ) secondary:Gradient( true ) secondary:Center() secondary:SetVisible( false ) secondary:SetSkin( "ExstoTheme" ) Menu:CreateAnimation( secondary ) secondary:FadeOnVisible( true ) secondary:SetPosMul( 5 ) secondary:SetFadeMul( 4 ) secondary.Hide = function( self ) self.Hidden = true self:SetVisible( false ) end secondary.Show = function( self ) self.Hidden = false Menu:BringBackSecondaries() end return secondary end function Menu:UpdateSecondariesPos() local mainX, mainY = Menu.Frame:GetPos() local mainW, mainH = Menu.Frame:GetSize() if self.ActiveSecondary then self.ActiveSecondary:SetPos( mainX + mainW + Menu.Placement.Gap, mainY + mainH - self.ActiveSecondary:GetTall() ) end if self.ActiveTab then self.ActiveTab:SetPos( mainX - Menu.Placement.Gap - self.ActiveTab:GetWide(), mainY + mainH - self.ActiveTab:GetTall() ) end end function Menu:HideSecondaries() local mainX, mainY = Menu.Frame:GetPos() local mainW, mainH = Menu.Frame:GetSize() if self.ActiveSecondary then self.ActiveSecondary:SetPos( ( mainX + ( mainW / 2 ) ) - ( self.ActiveSecondary:GetWide() / 2 ), mainY + mainH - self.ActiveSecondary:GetTall() ) end if self.ActiveTab then self.ActiveTab:SetPos( ( mainX + ( mainW / 2 ) ) - ( self.ActiveTab:GetWide() / 2 ), mainY + mainH - self.ActiveTab:GetTall() ) end end function Menu:BringBackSecondaries() if self.ActiveSecondary then if !self.ActiveSecondary.Hidden then self.ActiveSecondary:SetVisible( true ) end end if self.ActiveTab then if !self.ActiveTab.Hidden then self.ActiveTab:SetVisible( true ) end end self:UpdateSecondariesPos() end function Menu:BringBackNotify() for _, obj in ipairs( self.NotifyPanels ) do obj:SetVisible( true ) end end function Menu:HideNotify() for _, obj in ipairs( self.NotifyPanels ) do obj:SetVisible( false ) end end function Menu:CreateColorPanel( x, y, w, h, page ) local panel = exsto.CreatePanel( x, y, w, h, Color( 204, 204, 204, 51 ), page ) self:CreateAnimation( panel ) panel:SetPosMul( 1 ) panel.Accept = function( self ) if self:GetStyle() == "accept" then return end self.Style = "accept" self:SetColor( Color( 0, 255, 24, 51 ) ) end panel.Deny = function( self ) if self:GetStyle() == "deny" then return end self.Style = "deny" self:SetColor( Color( 255, 0, 0, 51 ) ) end panel.Neutral = function( self ) if self:GetStyle() == "neutral" then return end self.Style = "neutral" self:SetColor( Color( 204, 204, 204, 51 ) ) end panel.GetStyle = function( self ) return self.Style end return panel end function Menu:CreateAnimation( obj ) obj.Anims = {} obj.SetPosMul = function( self, mul ) self.Anims[ 1 ].Mul = mul self.Anims[ 2 ].Mul = mul end obj.SetFadeMul = function( self, mul ) self.Anims[ 3 ].Mul = mul end obj.SetColorMul = function( self, mul ) for I = 4, 7 do self.Anims[ I ].Mul = mul end end obj.DisableAnims = function( self ) self.Anims.Disabled = true end obj.EnableAnims = function( self ) self.Anims.Disabled = false end -- Position Support obj.oldGetPos = obj.GetPos obj.oldPos = obj.SetPos local oldSetX = function( self, x ) obj.oldPos( self, x, self.Anims[ 2 ].Last ) end local oldSetY = function( self, y ) obj.oldPos( self, self.Anims[ 1 ].Last, y ) end obj.SetPos = function( self, x, y ) self:SetX( x ) self:SetY( y ) self.Anims[ 1 ].Current = x self.Anims[ 2 ].Current = y end obj.SetX = function( self, x ) self.Anims[ 1 ].Current = x end obj.SetY = function( self, y ) self.Anims[ 2 ].Current = y end obj.GetPos = function( self ) return self.Anims[ 1 ].Last, self.Anims[ 2 ].Last end -- Fading Support local oldVisible = obj.SetVisible local oldSetAlpha = function( self, alpha ) self:SetAlpha( alpha ) oldVisible( self, alpha >= 5 ) end obj.FadeOnVisible = function( self, bool ) self.fadeOnVisible = bool end obj.SetVisible = function( self, bool ) if self.fadeOnVisible then if bool == true then self.Anims[ 3 ].Current = 255 oldVisible( self, bool ) elseif bool == false then self.Anims[ 3 ].Current = 0 end else oldVisible( self, bool ) end end -- Color Support. local oldSetColor = function( self, color ) self.bgColor = color end local oldSetRed = function( self, red ) self.bgColor.r = red end local oldSetGreen = function( self, green ) self.bgColor.g = green end local oldSetBlue = function( self, blue ) self.bgColor.b = blue end local oldSetAlpha2 = function( self, alpha ) self.bgColor.a = alpha end obj.SetColor = function( self, color ) print( "Setting color for" .. tostring( self ) ) self:SetRed( color.r ) self:SetGreen( color.g ) self:SetBlue( color.b ) self.Anims[ 7 ].Current = color.a end obj.SetRed = function( self, red ) self.Anims[ 4 ].Current = red end obj.SetGreen = function( self, green ) self.Anims[ 5 ].Current = green end obj.SetBlue = function( self, blue ) self.Anims[ 6 ].Current = blue end local think, dist, speed = obj.Think obj.Think = function( self ) for _, data in ipairs( self.Anims ) do if math.Round( data.Last ) != math.Round( data.Current ) then if self.Anims.Disabled then data.Last = data.Current data.Call( self, self.Anims[ _ ].Last ) else dist = data.Current - data.Last speed = RealFrameTime() * ( dist / data.Mul ) * 40 self.Anims[ _ ].Last = math.Approach( data.Last, data.Current, speed ) data.Call( self, self.Anims[ _ ].Last ) end end end end -- Presets. local x, y = obj.oldGetPos( obj ) obj.Anims[ 1 ] = { Current = x, Last = x, Mul = 40, Call = oldSetX, } obj.Anims[ 2 ] = { Current = y, Last = y, Mul = 40, Call = oldSetY, } -- Alpha. obj.Anims[ 3 ] = { Current = 255, Last = 255, Mul = 20, Call = oldSetAlpha } local col = obj.bgColor if col then -- Color Object obj.Anims[ 4 ] = { Current = col.r, Last = col.r, Mul = 20, Call = oldSetRed } obj.Anims[ 5 ] = { Current = col.g, Last = col.g, Mul = 20, Call = oldSetGreen } obj.Anims[ 6 ] = { Current = col.b, Last = col.b, Mul = 20, Call = oldSetBlue } obj.Anims[ 7 ] = { Current = col.a, Last = col.a, Mul = 20, Call = oldSetAlpha2 } end end --[[ ----------------------------------- Function: Menu.CreateExtras Description: Creates the pages ----------------------------------- ]] function Menu:BuildPages( rank, flagCount ) -- Protection against clientside hacks. Kill if the server's flagcount for the rank is not the same as the clients local clientFlags = exsto.Ranks[ rank:lower() ] if #clientFlags.Flags != flagCount then return end surface.SetFont( "exstoPlyColumn" ) -- Clean our old for short, data in pairs( self.List ) do if data.Panel:IsValid() then data.Panel:Remove() end end self.ListIndex = {} self.List = {} -- Loop through what we need to build. for _, data in ipairs( self.CreatePages ) do if table.HasValue( clientFlags.AllFlags, data.Short ) then exsto.Print( exsto_CONSOLE_DEBUG, "MENU --> Creating page for " .. data.Title .. "!" ) -- Call the build function. local page = data.Function( self.Content ) -- Insert his data into the list. self:AddToList( data, page ) -- Are we the default? Set us up as visible if data.Default then self.List[ data.Short ].Panel:SetVisible( true ) end end end -- If he can't see any pages, why bother? if #self.ListIndex == 0 then self:SetTitle( "There are no pages for you to view!" ) return false end -- Set our current page and the ones near us. for index, short in ipairs( self.ListIndex ) do if self.List[ short ] then -- Hes a default, set him up as our first selection. if self.List[ short ].Default then self:MoveToPage( short ) self.DefaultPage = self.CurrentPage self.DefaultPage.Panel:SetVisible( true ) else self:GetPageData( index ).Panel:SetVisible( false ) end end end -- If there still isn't any default, set the default as the first index. if !self.DefaultPage then self:MoveToPage( self.ListIndex[ 1 ] ) self.DefaultPage = self.CurrentPage self.DefaultPage.Panel:SetVisible( true ) end end --[[ ----------------------------------- Function: Menu.AddToList Description: Adds a page to the menu list. ----------------------------------- ]] function Menu:AddToList( info, panel ) self.List[info.Short] = { Title = info.Title, Short = info.Short, Default = info.Default, Flag = info.Flag, Panel = panel, } -- Create an indexed list of the pages. table.insert( self.ListIndex, info.Short ) end --[[ ----------------------------------- Function: Menu:GetPageData Description: Grabs page data from the index. ----------------------------------- ]] function Menu:GetPageData( index ) local short = self.ListIndex[ index ] if !short then return nil end return self.List[ short ] end --[[ ----------------------------------- Function: Menu:SetTitle Description: Sets the menu title. ----------------------------------- ]] function Menu:SetTitle( text ) self.Header.Title:SetText( text ) self.Header.Title:SizeToContents() local start = self.Header.Logo:GetWide() + self.Header.Title:GetWide() + 34 self.Header.ExtendBar:SetPos( start, 27 ) self.Header.ExtendBar:SetWide( self.Header:GetWide() - start - 60 ) self.Header.MoveLeft:MoveRightOf( self.Header.ExtendBar, 10 ) self.Header.MoveRight:MoveRightOf( self.Header.MoveLeft, 5 ) end --[[ ----------------------------------- Function: Menu:CreateDialog Description: Creates a small notification dialog. ----------------------------------- ]] function Menu:CreateDialog() self.Dialog = {} self.Dialog.Queue = {} self.Dialog.Active = false self.Dialog.IsLoading = false self.Dialog.BG = exsto.CreatePanel( 0, 0, self.Frame:GetWide(), self.Frame:GetTall(), Color( 0, 0, 0, 190 ), self.Frame ) self.Dialog.BG:SetVisible( false ) local id = surface.GetTextureID( "gui/center_gradient" ) self.Dialog.BG.Paint = function( self ) surface.SetDrawColor( 0, 0, 0, 190 ) surface.SetTexture( id ) surface.DrawTexturedRect( 0, 0, self:GetWide(), self:GetTall() ) end local w, h = surface.GetTextureSize( surface.GetTextureID( "loading" ) ) self.Dialog.Anim = exsto.CreateImage( 0, 0, w, h, "loacing", self.Dialog.BG ) self.Dialog.Anim:SetKeepAspect( true ) self.Dialog.Msg = exsto.CreateLabel( 20, self.Dialog.Anim:GetTall() + 40, "", "exstoBottomTitleMenu", self.Dialog.BG ) self.Dialog.Msg:DockMargin( ( self.Dialog.BG:GetWide() / 2 ) - 200, self.Dialog.Anim:GetTall() + 40, ( self.Dialog.BG:GetWide() / 2 ) - 200, 0 ) self.Dialog.Msg:Dock( FILL ) self.Dialog.Msg:SetContentAlignment( 7 ) self.Dialog.Msg:SetWrap( true ) self.Dialog.Yes = exsto.CreateButton( ( self.Frame:GetWide() / 2 ) - 140, self.Dialog.BG:GetTall() - 50, 100, 40, "Yes", self.Dialog.BG ) self.Dialog.Yes:SetStyle( "positive" ) self.Dialog.Yes.OnClick = function() if self.Dialog.YesFunc then self.Dialog.YesFunc() end sef:CleanDialog() end self.Dialog.No = exsto.CreateButton( ( self.Frame:GetWide() / 2 ) + 40, self.Dialog.BG:GetTall() - 50, 100, 40, "No", self.Dialog.BG ) self.Dialog.No:SetStyle( "negative" ) self.Dialog.No.OnClick = function() if self.Dialog.NoFunc then self.Dialog.NoFunc() end self:CleanDialog() end self.Dialog.OK = exsto.CreateButton( ( self.Frame:GetWide() / 2 ) - 50, self.Dialog.BG:GetTall() - 50, 100, 40, "OK", self.Dialog.BG ) self.Dialog.OK.OnClick = function() self:CleanDialog() end self:CleanDialog() end function Menu:CleanDialog() if !self.Dialog then return end Menu:BringBackSecondaries() self.Dialog.BG:SetVisible( false ) self.Dialog.Msg:SetText( "" ) self.Dialog.OK:SetVisible( false ) self.Dialog.Yes:SetVisible( false ) self.Dialog.No:SetVisible( false ) self.Dialog.IsLoading = false self.Dialog.Active = false if self.Dialog.Queue[1] then local data = self.Dialog.Queue[1] self:PushGeneric( data.Text, data.Texture, data.Color, data.Type ) table.remove( self.Dialog.Queue, 1 ) end end --[[ ----------------------------------- Function: Menu:PushLoad Description: Shows a loading screen. ----------------------------------- ]] function Menu:PushLoad() self:PushGeneric( "Loading...", nil, nil, "loading" ) timer.Create( "exstoLoadTimeout", 10, 1, function() if Menu.Dialog.IsLoading then Menu:EndLoad() Menu:PushError( "Loading timed out!" ) end end ) end function Menu:EndLoad() if !self.Frame then return end if !self.Dialog then return end if !self.Dialog.IsLoading then return end self:CleanDialog() end function Menu:PushError( msg ) self:PushGeneric( msg, "exstoErrorAnim", Color( 176, 0, 0, 255 ), "error" ) end function Menu:PushNotify( msg ) self:PushGeneric( msg, nil, nil, "notify" ) end function Menu:PushQuestion( msg, yesFunc, noFunc ) self:PushGeneric( msg, nil, nil, "question" ) self.Dialog.YesFunc = yesFunc self.Dialog.NoFunc = noFunc end function Menu:PushGeneric( msg, imgTexture, textCol, type ) if !self.Dialog then self:CreateDialog() end if self.Dialog.Active and type != "loading" then table.insert( self.Dialog.Queue, { Text = msg, Texture = imgTexture, Color = textCol, Type = type } ) return elseif self.Dialog.Active and type == "loading" then self:EndLoad() end Menu:HideSecondaries() self.Dialog.Active = true self.Dialog.Anim:SetImage( imgTexture or "exstoGenericAnim" ) self.Dialog.Msg:SetText( msg ) self.Dialog.Msg:SetTextColor( textCol or Color( 12, 176, 0, 255 ) ) if type == "notify" or type == "error" then self.Dialog.OK:SetVisible( true ) elseif type == "question" then self.Dialog.Yes:SetVisible( true ) self.Dialog.No:SetVisible( true ) elseif type == "input" then self.Dialog.OK:SetVisible( true ) --self.Dialog.Input:SetVisible( true ) elseif type == "loading" then self.Dialog.IsLoading = true end self.Dialog.BG:SetVisible( true ) end --[[ ----------------------------------- Function: Menu.CallServer Description: Calls a server function ----------------------------------- ]] function Menu.CallServer( command, ... ) RunConsoleCommand( command, Menu.AuthKey, unpack( {...} ) ) end --[[ ----------------------------------- Function: Menu.GetPageIndex Description: Gets an index of a page. ----------------------------------- ]] function Menu:GetPageIndex( short ) for k,v in pairs( Menu.ListIndex ) do if v == short then return k end end end function Menu:TuckExtras() if self.ActiveSecondary then -- Tuck him away. self.ActiveSecondary:SetVisible( false ) self.ActiveSecondary = nil end if self.ActiveTab then self.ActiveTab:SetVisible( false ) self.ActiveTab = nil end end function Menu:CheckRequests( short ) -- Send our our requests local secondary = self.SecondaryRequests[ short ] if secondary then if !secondary.Hidden then secondary:SetVisible( true ) end self.ActiveSecondary = secondary self:UpdateSecondariesPos() end local tabs = self.TabRequests[ short ] if tabs then if !tabs.Hidden then tabs:SetVisible( true ) end self.ActiveTab = tabs self:UpdateSecondariesPos() end end --[[ ----------------------------------- Function: Menu.MoveToPage Description: Moves to a page ----------------------------------- ]] function Menu:MoveToPage( short, right ) local page = self.List[ short ] local index = self:GetPageIndex( short ) if short == self.CurrentPage.Short then return end -- Why bother. local oldCurrent = self.CurrentPage.Panel local oldIndex = self.CurrentIndex self.PreviousPage = self.List[self.ListIndex[index - 1]] or self.List[self.ListIndex[#self.ListIndex]] self.CurrentPage = page self.NextPage = self.List[self.ListIndex[index + 1]] or self.List[self.ListIndex[1]] self.CurrentIndex = index self:SetTitle( self.CurrentPage.Title ) self:HideSecondaries() self:TuckExtras() self:CheckRequests( short ) if !oldCurrent then return end local oldW, oldH = oldCurrent:GetSize() local startPos = oldW if oldIndex > self.CurrentIndex then startPos = -oldW end if oldIndex == #self.ListIndex and self.CurrentIndex == 1 then startPos = oldW end if self.CurrentIndex == #self.ListIndex and oldIndex == 1 then startPos = -oldW end self.CurrentPage.Panel:SetVisible( true ) -- Make him alive. self.CurrentPage.Panel:oldPos( startPos, 0 ) self.CurrentPage.Panel.Anims[ 1 ].Last = startPos self.CurrentPage.Panel.Anims[ 1 ].Current = startPos self.CurrentPage.Panel:SetPos( 0, 0 ) oldCurrent:SetPos( -startPos, 0 ) end concommand.Add( "_Test", function( ply, _, args ) Menu.CurrentPage.Panel:PushGeneric( args[1] ) end ) --[[ ----------------------------------- Function: Menu:CalcFontSize Description: Calculates the best font to use in an area ----------------------------------- ]] function Menu:CalcFontSize( text, maxWidth, maxFont ) for I = 14, maxFont do surface.SetFont( "ExGenericText" .. I ) local w = surface.GetTextSize( text ) if w > maxWidth then maxFont = math.Round( I - 3 ) break end end return "ExGenericText" .. maxFont end --[[ ----------------------------------- Function: Menu:CreatePage Description: Creates a menu page for the Exsto menu ----------------------------------- ]] local glow = surface.GetTextureID( "glow2" ) local loading = surface.GetTextureID( "loading" ) function Menu:CreatePage( info, func ) -- Create a build function local function buildPage( bg ) -- Create the placement background. local page = exsto.CreatePanel( 0, 0, Menu.Placement.Content.w, Menu.Placement.Content.h - 6, Menu.Colors.Black, bg ) page:SetVisible( false ) Menu:CreateAnimation( page ) page:SetPosMul( 5 ) function page:RequestSecondary( force ) local secondary = Menu:BuildSecondaryMenu() Menu.SecondaryRequests[ info.Short ] = secondary if force then Menu.ActiveSecondary = secondary end return secondary end function page:RequestTabs( force ) local tabs = Menu:BuildTabMenu() Menu.TabRequests[ info.Short ] = tabs if force then Menu.ActiveTab = tabs end return tabs end page.ExNotify_Queue = {} function page:PushLoad() self.ExNotify_Active = true self.ExNotify_Loading = true self.ExNotify_Rotation = 0 end function page:EndLoad() self.ExNotify_Active = false self.ExNotify_Loading = false end function page:PushGeneric( text, timeOnline, err ) if self.ExNotify_Active then table.insert( self.ExNotify_Queue, { Text = text, TimeOnline = timeOnline, Err = err } ) return end self.ExNotify_Active = true self.ExNotify_Generic = true self.ExNotify_Text = text or "No Text Provided" self.ExNotify_EndTime = CurTime() + ( timeOnline or 5 ) self.ExNotify_Error = err or false self.ExNotify_Alpha = 0 if !self.ExNotify_Panel then self.ExNotify_Panel = exsto.CreatePanel( 0, self:GetTall() - 40, self:GetWide(), 23 ) self.ExNotify_Panel:Gradient( true ) self.ExNotify_Panel:SetSkin( "ExstoTheme" ) table.insert( Menu.NotifyPanels, self.ExNotify_Panel ) local x, y = Menu.Frame:GetPos() self.ExNotify_Panel:SetPos( x, Menu.Frame:GetTall() - 40 + y ) self.ExNotify_TextPanel = exsto.CreateLabel( 5, 3, text or "No Text Provided", "ExGenericText18", self.ExNotify_Panel ) self.ExNotify_TextPanel:SetWrap( true ) Menu:CreateAnimation( self.ExNotify_Panel ) self.ExNotify_Panel:FadeOnVisible( true ) self.ExNotify_Panel:SetFadeMul( 2 ) self.ExNotify_Panel:SetPosMul( 3 ) end self.ExNotify_Panel:SetVisible( true ) local x, y = Menu.Frame:GetPos() self.ExNotify_Panel:SetPos( x, Menu.Frame:GetTall() + 6 + y ) end function page:PushError( text, timeOnline ) self:PushGeneric( text, timeOnline, true ) end function page:DialogCleanup() self.ExNotify_Active = false self.ExNotify_Generic = false self.ExNotify_Loading = false self.ExNotify_Text = "" self.ExNotify_EndTime = false self.ExNotify_Error = false self.ExNotify_Alpha = 0 local x, y = Menu.Frame:GetPos() self.ExNotify_Panel:SetPos( x, self:GetTall() - 40 + y ) if self.ExNotify_Queue[1] then self:PushGeneric( self.ExNotify_Queue[1].Text, self.ExNotify_Queue[1].TimeOnline, self.ExNotify_Queue[1].Err ) table.remove( self.ExNotify_Queue, 1 ) end end page.Text_LoadingColor = Color( 0, 192, 10, 255 ) page.Text_ErrorColor = Color( 192, 0, 10, 255 ) page.Text_GenericColor = Color( 30, 30, 30, 255 ) page.Text_OutlineColor = Color( 255, 255, 255, 255 ) page.PaintOver = function( self ) if self.ExNotify_Active then if self.ExNotify_Loading then surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetTexture( glow ) surface.DrawTexturedRect( ( self:GetWide() / 2 ) - ( 512 / 2 ), ( self:GetTall() / 2 ) - ( 512 / 2 ), 512, 512 ) self.ExNotify_Rotation = self.ExNotify_Rotation + 1 surface.SetTexture( loading ) surface.DrawTexturedRectRotated( ( self:GetWide() / 2 ), ( self:GetTall() / 2 ), 128, 128, self.ExNotify_Rotation ) draw.SimpleText( "Loading", "ExLoadingText", ( self:GetWide() / 2 ), ( self:GetTall() / 2 ), self.Text_LoadingColor, 1, 1 ) elseif self.ExNotify_Generic then if self.ExNotify_EndTime <= CurTime() then self:DialogCleanup() return end end end end local success, err = pcall( func, page ) if !success then exsto.ErrorNoHalt( "MENU --> Error creating page '" .. info.Short .. "':\n" .. err ) end return page end -- Insert data into a *to create* list. table.insert( Menu.CreatePages, { Title = info.Title, Flag = info.Flag, Short = info.Short, Default = info.Default, Function = buildPage, } ) end
gpl-3.0
nasomi/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f1.lua
34
1105
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Shiva's Gate -- @pos 215 -34 20 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
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/edit_me.lua
1
1362
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2017 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email mdwyer@snap.net.nz URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] -- EDIT ME! -- This script contains the telnet password, database connection info and the optional webdav folder where your server's daily chatlogs will be saved. require "lfs" function initBot() homedir = getMudletHomeDir() lfs.mkdir(homedir .. "/daily") lfs.mkdir(homedir .. "/dns") lfs.mkdir(homedir .. "/proxies") lfs.mkdir(homedir .. "/temp") lfs.mkdir(homedir .. "/scripts") lfs.mkdir(homedir .. "/chatlogs") -- EDIT ME! telnetPassword = "" webdavFolder = "/var/www/chatlogs/" ircServer = "127.0.0.1" ircPort = 6667 ircChannel = "bot" -- EDIT ME! botDB = "bot" botDBUser = "bot" botDBPass = "" -- EDIT ME! botsDB = "bots" botsDBUser = "bots" botsDBPass = "" end function openDB() lastAction = "Open Database" env = mysql.mysql() conn = env:connect(botDB, botDBUser, botDBPass) conn:execute("INSERT INTO memRestrictedItems (select * from restrictedItems)") conn:execute("INSERT INTO memLottery (select * from lottery)") end function openBotsDB() connBots = env:connect(botsDB, botsDBUser, botsDBPass) end
gpl-3.0
nasomi/darkstar
scripts/zones/Port_Windurst/npcs/Janshura-Rashura.lua
17
2714
----------------------------------- -- Area: Port Windurst -- NPC: Janshura Rashura -- Starts Windurst Missions -- @pos -227 -8 184 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() ~= WINDURST) then player:startEvent(0x0047); -- for other nation else CurrentMission = player:getCurrentMission(WINDURST); MissionStatus = player:getVar("MissionStatus"); pRank = player:getRank(); cs, p, offset = getMissionOffset(player,3,CurrentMission,MissionStatus); if (CurrentMission <= 15 and (cs ~= 0 or offset ~= 0 or (CurrentMission == 0 and offset == 0))) then if (cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (CurrentMission ~= 255) then player:startEvent(0x004c); elseif (player:hasCompletedMission(WINDURST,THE_HORUTOTO_RUINS_EXPERIMENT) == false) then player:startEvent(0x0053); elseif (player:hasCompletedMission(WINDURST,THE_HEART_OF_THE_MATTER) == false) then player:startEvent(0x0068); elseif (player:hasCompletedMission(WINDURST,THE_PRICE_OF_PEACE) == false) then player:startEvent(0x006d); elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_WINDURST)) then player:startEvent(0x00a3); else flagMission, repeatMission = getMissionMask(player); player:startEvent(0x004e,flagMission,0,0,0,STAR_CRESTED_SUMMONS,repeatMission); 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); finishMissionTimeline(player,3,csid,option); if (csid == 0x0076 and option == 1) then player:addTitle(NEW_BEST_OF_THE_WEST_RECRUIT); elseif (csid == 0x004e and (option == 12 or option == 15)) then player:addKeyItem(STAR_CRESTED_SUMMONS); player:messageSpecial(KEYITEM_OBTAINED,STAR_CRESTED_SUMMONS); end end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/examples/notificationsExample.lua
17
2113
-- Send a notification to all players that displays up top for 5 seconds Notifications:TopToAll({text="Top Notification for 5 seconds ", duration=5.0}) -- Send a notification to playerID 0 which will display up top for 9 seconds and be green, on the same line as the previous notification Notifications:Top(0, {text="GREEEENNNN", duration=9, style={color="green"}, continue=true}) -- Display 3 styles of hero icons on the same line for 5 seconds. Notifications:TopToAll({hero="npc_dota_hero_axe", duration=5.0}) Notifications:TopToAll({hero="npc_dota_hero_axe", imagestyle="landscape", continue=true}) Notifications:TopToAll({hero="npc_dota_hero_axe", imagestyle="portrait", continue=true}) -- Display a generic image and then 2 ability icons and an item on the same line for 5 seconds Notifications:TopToAll({image="file://{images}/status_icons/dota_generic.psd", duration=5.0}) Notifications:TopToAll({ability="nyx_assassin_mana_burn", continue=true}) Notifications:TopToAll({ability="lina_fiery_soul", continue=true}) Notifications:TopToAll({item="item_force_staff", continue=true}) -- Send a notification to all players on radiant (GOODGUYS) that displays near the bottom of the screen for 10 seconds to be displayed with the NotificationMessage class added Notifications:BottomToTeam(DOTA_TEAM_GOODGUYS, {text="AAAAAAAAAAAAAA", duration=10, class="NotificationMessage"}) -- Send a notification to player 0 which will display near the bottom a large red notification with a solid blue border for 5 seconds Notifications:Bottom(PlayerResource:GetPlayer(0), {text="Super Size Red", duration=5, style={color="red", ["font-size"]="110px", border="10px solid blue"}}) -- Remove 1 bottom and 2 top notifications 2 seconds later Timers:CreateTimer(2,function() Notifications:RemoveTop(0, 2) Notifications:RemoveBottomFromTeam(DOTA_TEAM_GOODGUYS, 1) -- Add 1 more notification to the bottom Notifications:BottomToAll({text="GREEEENNNN again", duration=9, style={color="green"}}) end) -- Clear all notifications from the bottom Timers:CreateTimer(7, function() Notifications:ClearBottomFromAll() end)
mit
nasomi/darkstar
scripts/globals/mobskills/Shadow_Spread.lua
37
1164
--------------------------------------------- --- Shadow Spread --- --- Description: A dark shroud renders any nearby targets blinded, asleep, and cursed. --- --------------------------------------------- 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 typeEffect = 0; local currentMsg = MSG_NONE; local msg = MSG_NONE; msg = MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 25, 0, 300); if(msg == MSG_ENFEEB_IS) then typeEffect = EFFECT_CURSE_I; currentMsg = msg; end msg = MobStatusEffectMove(mob, target, EFFECT_BLINDNESS, 20, 0, 180); if(msg == MSG_ENFEEB_IS) then typeEffect = EFFECT_BLINDNESS; currentMsg = msg; end msg = MobStatusEffectMove(mob, target, EFFECT_SLEEP_I, 1, 0, 30); if(msg == MSG_ENFEEB_IS) then typeEffect = EFFECT_SLEEP_I; currentMsg = msg; end skill:setMsg(currentMsg); return typeEffect; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Charlaimagnat.lua
17
2826
----------------------------------- -- Area: Northern San d'Oria -- NPC: Charlaimagnat -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); 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) local realday = tonumber(tostring(os.date("%Y")) .. os.date("%m") .. os.date("%d")); local TheMissingPiece = player:getQuestStatus(OUTLANDS,THE_MISSING_PIECE); if (TheMissingPiece == QUEST_ACCEPTED and player:hasKeyItem(TABLET_OF_ANCIENT_MAGIC) and player:hasKeyItem(LETTER_FROM_ALFESAR)) then player:startEvent(0x02bf); -- Continuing the Quest elseif (TheMissingPiece == QUEST_ACCEPTED and realday < player:getVar("TheMissingPiece_date")) then player:startEvent(0x02c0); -- didn't wait a day yet elseif (TheMissingPiece == QUEST_ACCEPTED and realday >= player:getVar("TheMissingPiece_date")) then player:startEvent(0x02c1); -- Quest Completed else player:startEvent(0x02be); -- standard 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 == 0x02bf) then player:setVar("TheMissingPiece_date", tostring(os.date("%Y")) .. os.date("%m") .. os.date("%d") + 1); player:addTitle(ACQUIRER_OF_ANCIENT_ARCANUM); player:delKeyItem(TABLET_OF_ANCIENT_MAGIC); player:delKeyItem(LETTER_FROM_ALFESAR); elseif (csid == 0x02c1) then if (player:getFreeSlotsCount() == 0) then -- does the player have space player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4729); else -- give player teleport-altep player:addItem(4729); player:messageSpecial(ITEM_OBTAINED,4729); player:addFame(RABAO,30); player:completeQuest(OUTLANDS,THE_MISSING_PIECE); end; end; end;
gpl-3.0
thesabbir/luci
applications/luci-app-firewall/luasrc/model/cbi/firewall/forwards.lua
66
3741
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ds = require "luci.dispatcher" local ft = require "luci.tools.firewall" m = Map("firewall", translate("Firewall - Port Forwards"), translate("Port forwarding allows remote computers on the Internet to \ connect to a specific computer or service within the \ private LAN.")) -- -- Port Forwards -- s = m:section(TypedSection, "redirect", translate("Port Forwards")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s.sortable = true s.extedit = ds.build_url("admin/network/firewall/forwards/%s") s.template_addremove = "firewall/cbi_addforward" function s.create(self, section) local n = m:formvalue("_newfwd.name") local p = m:formvalue("_newfwd.proto") local E = m:formvalue("_newfwd.extzone") local e = m:formvalue("_newfwd.extport") local I = m:formvalue("_newfwd.intzone") local a = m:formvalue("_newfwd.intaddr") local i = m:formvalue("_newfwd.intport") if p == "other" or (p and a) then created = TypedSection.create(self, section) self.map:set(created, "target", "DNAT") self.map:set(created, "src", E or "wan") self.map:set(created, "dest", I or "lan") self.map:set(created, "proto", (p ~= "other") and p or "all") self.map:set(created, "src_dport", e) self.map:set(created, "dest_ip", a) self.map:set(created, "dest_port", i) self.map:set(created, "name", n) end if p ~= "other" then created = nil end end function s.parse(self, ...) TypedSection.parse(self, ...) if created then m.uci:save("firewall") luci.http.redirect(ds.build_url( "admin/network/firewall/redirect", created )) end end function s.filter(self, sid) return (self.map:get(sid, "target") ~= "SNAT") end ft.opt_name(s, DummyValue, translate("Name")) local function forward_proto_txt(self, s) return "%s-%s" %{ translate("IPv4"), ft.fmt_proto(self.map:get(s, "proto"), self.map:get(s, "icmp_type")) or "TCP+UDP" } end local function forward_src_txt(self, s) local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "src_port")) local m = ft.fmt_mac(self.map:get(s, "src_mac")) if p and m then return translatef("From %s in %s with source %s and %s", a, z, p, m) elseif p or m then return translatef("From %s in %s with source %s", a, z, p or m) else return translatef("From %s in %s", a, z) end end local function forward_via_txt(self, s) local a = ft.fmt_ip(self.map:get(s, "src_dip"), translate("any router IP")) local p = ft.fmt_port(self.map:get(s, "src_dport")) if p then return translatef("Via %s at %s", a, p) else return translatef("Via %s", a) end end match = s:option(DummyValue, "match", translate("Match")) match.rawhtml = true match.width = "50%" function match.cfgvalue(self, s) return "<small>%s<br />%s<br />%s</small>" % { forward_proto_txt(self, s), forward_src_txt(self, s), forward_via_txt(self, s) } end dest = s:option(DummyValue, "dest", translate("Forward to")) dest.rawhtml = true dest.width = "40%" function dest.cfgvalue(self, s) local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "dest_port")) or ft.fmt_port(self.map:get(s, "src_dport")) if p then return translatef("%s, %s in %s", a, p, z) else return translatef("%s in %s", a, z) end end ft.opt_enabled(s, Flag, translate("Enable")).width = "1%" return m
apache-2.0
nasomi/darkstar
scripts/globals/items/piece_of_bubble_chocolate.lua
35
1170
----------------------------------------- -- ID: 4496 -- Item: piece_of_bubble_chocolate -- Food Effect: 30Min, All Races ----------------------------------------- -- 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,1800,4496); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
nasomi/darkstar
scripts/globals/spells/dragonfoe_mambo.lua
18
1581
----------------------------------------- -- Spell: Dragonfoe Mambo -- Grants evasion bonus to all members. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); -- Since nobody knows the evasion values for mambo, I'll just make shit up! (aka - same as madrigal) local power = 9; if (sLvl+iLvl > 130) then power = power + math.floor((sLvl+iLvl-130) / 18); end if (power >= 30) then power = 30; end local iBoost = caster:getMod(MOD_MAMBO_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MAMBO,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_MAMBO; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Southern_San_dOria/npcs/Guilboire.lua
36
1435
----------------------------------- -- Area: Southern San d'Oria -- NPC: Guilboire -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_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(0x291); 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
aikon-com-cn/NoxicDB
other/calendar_events/Lunar Festival/Lunar Festival/fireworks.lua
2
13098
--[[ How does it work: - First the player is casting a spell to launch a rocket - This spell is summoning a rocket NPC (!) - The code is looking for the nearest firework launcher and moves the rocket NPC there - After that the rocket NPC is casting a spell that does the visual effect ]]-- local NPC_OMEN = 15467 local NPC_FIREWORK_BLUE = 15879 local NPC_FIREWORK_GREEN = 15880 local NPC_FIREWORK_PURPLE = 15881 local NPC_FIREWORK_RED = 15882 local NPC_FIREWORK_YELLOW = 15883 local NPC_FIREWORK_WHITE = 15884 local NPC_FIREWORK_BIG_BLUE = 15885 local NPC_FIREWORK_BIG_GREEN = 15886 local NPC_FIREWORK_BIG_PURPLE = 15887 local NPC_FIREWORK_BIG_RED = 15888 local NPC_FIREWORK_BIG_YELLOW = 15889 local NPC_FIREWORK_BIG_WHITE = 15890 local NPC_CLUSTER_BLUE = 15872 local NPC_CLUSTER_RED = 15873 local NPC_CLUSTER_GREEN = 15874 local NPC_CLUSTER_PURPLE = 15875 local NPC_CLUSTER_WHITE = 15876 local NPC_CLUSTER_YELLOW = 15877 local NPC_CLUSTER_BIG_BLUE = 15911 local NPC_CLUSTER_BIG_GREEN = 15912 local NPC_CLUSTER_BIG_PURPLE = 15913 local NPC_CLUSTER_BIG_RED = 15914 local NPC_CLUSTER_BIG_WHITE = 15915 local NPC_CLUSTER_BIG_YELLOW = 15916 local NPC_CLUSTER_ELUNE = 15918 local GO_FIREWORK_LAUNCHER_1 = 180771 local GO_FIREWORK_LAUNCHER_2 = 180868 local GO_FIREWORK_LAUNCHER_3 = 180850 local GO_CLUSTER_LAUNCHER_1 = 180772 local GO_CLUSTER_LAUNCHER_2 = 180859 local GO_CLUSTER_LAUNCHER_3 = 180869 local GO_CLUSTER_LAUNCHER_4 = 180874 local SPELL_ROCKET_BLUE = 26344 local SPELL_ROCKET_GREEN = 26345 local SPELL_ROCKET_PURPLE = 26346 local SPELL_ROCKET_RED = 26347 local SPELL_ROCKET_WHITE = 26348 local SPELL_ROCKET_YELLOW = 26349 local SPELL_ROCKET_BIG_BLUE = 26351 local SPELL_ROCKET_BIG_GREEN = 26352 local SPELL_ROCKET_BIG_PURPLE = 26353 local SPELL_ROCKET_BIG_RED = 26354 local SPELL_ROCKET_BIG_WHITE = 26355 local SPELL_ROCKET_BIG_YELLOW = 26356 local SPELL_LUNAR_FORTUNE = 26522 local SPELL_LUNAR_INVITATION = 26373 local ZONE_MOONGLADE = 493 function OnSummon(pUnit, event) local entry = pUnit:GetEntry() if(entry == NPC_FIREWORK_BLUE or entry == NPC_FIREWORK_GREEN or entry == NPC_FIREWORK_PURPLE or entry == NPC_FIREWORK_RED or entry == NPC_FIREWORK_YELLOW or entry == NPC_FIREWORK_WHITE or entry == NPC_FIREWORK_BIG_BLUE or entry == NPC_FIREWORK_BIG_GREEN or entry == NPC_FIREWORK_BIG_PURPLE or entry == NPC_FIREWORK_BIG_RED or entry == NPC_FIREWORK_BIG_YELLOW or entry == NPC_FIREWORK_BIG_WHITE)then local Obj1 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_1) local Obj2 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_2) local Obj3 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_3) if(Obj1 ~= nil or Obj2 ~= nil or Obj3 ~= nil)then if(Obj1 ~= nil)then local O1X, O1Y, O1Z, _ = Obj1:GetSpawnLocation() pUnit:TeleportCreature(O1X, O1Y, O1Z) elseif(Obj2 ~= nil)then local O2X, O2Y, O2Z, _ = Obj2:GetSpawnLocation() pUnit:TeleportCreature(O2X, O2Y, O2Z) elseif(Obj3 ~= nil)then local O3X, O3Y, O3Z, _ = Obj3:GetSpawnLocation() pUnit:TeleportCreature(O3X, O3Y, O3Z) end if(entry == NPC_FIREWORK_BLUE)then pUnit:FullCastSpell(SPELL_ROCKET_BLUE) elseif(entry == NPC_FIREWORK_GREEN)then pUnit:FullCastSpell(SPELL_ROCKET_GREEN) elseif(entry == NPC_FIREWORK_PURPLE)then pUnit:FullCastSpell(SPELL_ROCKET_PURPLE) elseif(entry == NPC_FIREWORK_RED)then pUnit:FullCastSpell(SPELL_ROCKET_RED) elseif(entry == NPC_FIREWORK_WHITE)then pUnit:FullCastSpell(SPELL_ROCKET_WHITE) elseif(entry == NPC_FIREWORK_YELLOW)then pUnit:FullCastSpell(SPELL_ROCKET_YELLOW) elseif(entry == NPC_FIREWORK_BIG_BLUE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) elseif(entry == NPC_FIREWORK_BIG_GREEN)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_GREEN) elseif(entry == NPC_FIREWORK_BIG_PURPLE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_PURPLE) elseif(entry == NPC_FIREWORK_BIG_RED)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_RED) elseif(entry == NPC_FIREWORK_BIG_WHITE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) elseif(entry == NPC_FIREWORK_BIG_YELLOW)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_YELLOW) end end elseif(entry == NPC_CLUSTER_BLUE or entry == NPC_CLUSTER_GREEN or entry == NPC_CLUSTER_PURPLE or entry == NPC_CLUSTER_RED or entry == NPC_CLUSTER_YELLOW or entry == NPC_CLUSTER_WHITE or entry == NPC_CLUSTER_BIG_BLUE or entry == NPC_CLUSTER_BIG_GREEN or entry == NPC_CLUSTER_BIG_PURPLE or entry == NPC_CLUSTER_BIG_RED or entry == NPC_CLUSTER_BIG_YELLOW or entry == NPC_CLUSTER_BIG_WHITE or entry == NPC_CLUSTER_ELUNE)then local Obj1 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_1) local Obj2 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_2) local Obj3 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_3) local Obj4 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_4) if(Obj1 ~= nil or Obj2 ~= nil or Obj3 ~= nil or Obj4 ~= nil)then if(Obj1 ~= nil)then local O1X, O1Y, O1Z, _ = Obj1:GetSpawnLocation() pUnit:TeleportCreature(O1X, O1Y, O1Z) elseif(Obj2 ~= nil)then local O2X, O2Y, O2Z, _ = Obj2:GetSpawnLocation() pUnit:TeleportCreature(O2X, O2Y, O2Z) elseif(Obj3 ~= nil)then local O3X, O3Y, O3Z, _ = Obj3:GetSpawnLocation() pUnit:TeleportCreature(O3X, O3Y, O3Z) elseif(Obj4 ~= nil)then local O4X, O4Y, O4Z, _ = Obj4:GetSpawnLocation() pUnit:TeleportCreature(O4X, O4Y, O4Z) end if(pUnit:GetZoneId() == ZONE_MOONGLADE)then if(pUnit:CalcToDistance(7558.993, -2839.999, 450.0214) < 100)then local chance = math.random(1,20) if(chance == 1)then PerformIngameSpawn(1, NPC_OMEN, 1, 7558.993, -2839.999, 450.0214, 4.46, 14, 0, 0, 0, 0, 0, 0) else PerformIngameSpawn(1, NPC_MINION_OF_OMEN, 1, pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), pUnit:GetO() + math.random(-1,1), 14, 0, 0, 0, 0, 0, 0) end end end if(entry == NPC_CLUSTER_BLUE)then pUnit:FullCastSpell(SPELL_ROCKET_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BLUE) elseif(entry == NPC_CLUSTER_GREEN)then pUnit:FullCastSpell(SPELL_ROCKET_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_GREEN) elseif(entry == NPC_CLUSTER_PURPLE)then pUnit:FullCastSpell(SPELL_ROCKET_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_PURPLE) elseif(entry == NPC_CLUSTER_RED)then pUnit:FullCastSpell(SPELL_ROCKET_RED) pUnit:FullCastSpell(SPELL_ROCKET_RED) pUnit:FullCastSpell(SPELL_ROCKET_RED) pUnit:FullCastSpell(SPELL_ROCKET_RED) elseif(entry == NPC_CLUSTER_WHITE)then pUnit:FullCastSpell(SPELL_ROCKET_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_WHITE) elseif(entry == NPC_CLUSTER_YELLOW)then pUnit:FullCastSpell(SPELL_ROCKET_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_YELLOW) elseif(entry == NPC_CLUSTER_BIG_BLUE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) elseif(entry == NPC_CLUSTER_BIG_GREEN)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_BIG_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_BIG_GREEN) pUnit:FullCastSpell(SPELL_ROCKET_BIG_GREEN) elseif(entry == NPC_CLUSTER_BIG_PURPLE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_PURPLE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_PURPLE) elseif(entry == NPC_CLUSTER_BIG_RED)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_RED) pUnit:FullCastSpell(SPELL_ROCKET_BIG_RED) pUnit:FullCastSpell(SPELL_ROCKET_BIG_RED) pUnit:FullCastSpell(SPELL_ROCKET_BIG_RED) elseif(entry == NPC_CLUSTER_BIG_WHITE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) elseif(entry == NPC_CLUSTER_BIG_YELLOW)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_BIG_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_BIG_YELLOW) pUnit:FullCastSpell(SPELL_ROCKET_BIG_YELLOW) elseif(entry == NPC_CLUSTER_ELUNE)then pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_WHITE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) pUnit:FullCastSpell(SPELL_ROCKET_BIG_BLUE) for k,v in pairs(pUnit:GetInRangePlayers())do if(v:HasAura(SPELL_LUNAR_FORTUNE))then v:RemoveAura(SPELL_LUNAR_FORTUNE) end v:AddAura(SPELL_LUNAR_FORTUNE, 3600000, false) end end end end end RegisterUnitEvent(NPC_FIREWORK_BLUE,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_GREEN,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_PURPLE,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_RED,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_YELLOW,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_WHITE,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_BLUE,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_GREEN,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_PURPLE,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_RED,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_YELLOW,18,OnSummon) RegisterUnitEvent(NPC_FIREWORK_BIG_WHITE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BLUE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_GREEN,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_PURPLE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_RED,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_YELLOW,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_WHITE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_BLUE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_GREEN,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_PURPLE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_RED,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_YELLOW,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_BIG_WHITE,18,OnSummon) RegisterUnitEvent(NPC_CLUSTER_ELUNE,18,OnSummon) function NearLauncher( pUnit ) local Obj1 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_1) local Obj2 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_2) local Obj3 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_FIREWORK_LAUNCHER_3) if ( Obj1 ~= nil or Obj2 ~= nil or Obj3 ~= nil ) then return true end return false end function NearCluster( pUnit ) local Obj1 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_1) local Obj2 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_2) local Obj3 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_3) local Obj4 = pUnit:GetGameObjectNearestCoords(pUnit:GetX(), pUnit:GetY(), pUnit:GetZ(), GO_CLUSTER_LAUNCHER_4) if ( Obj1 ~= nil or Obj2 ~= nil or Obj3 ~= nil or Obj4 ~= nil ) then return true end return false end function LaunchRocket (event, pPlayer, SpellId, pSpellObject) -- spells local SM_RD_Rocket = 26286 -- Small Red Rocket local SM_BL_Rocket = 26291 -- Small Blue Rocket local SM_GN_Rocket = 26292 -- Small Green Rocket local BL_FW_Cluster = 26304 -- Blue Firework Cluster local GN_FW_Cluster = 26325 -- Green Firework Cluster local RD_FW_Cluster = 26327 -- Red Firework Cluster local Quest = 8867 if ( pPlayer:HasQuest(Quest) ) then if ( NearLauncher(pPlayer) and (SpellId==SM_RD_Rocket or SpellId==SM_BL_Rocket or SpellId==SM_GN_Rocket) ) then if(pPlayer:GetQuestObjectiveCompletion(Quest, 0) < 8)then pPlayer:AdvanceQuestObjective(Quest, 0) end elseif ( NearCluster(pPlayer) and (SpellId==BL_FW_Cluster or SpellId==GN_FW_Cluster or SpellId==RD_FW_Cluster) ) then if(pPlayer:GetQuestObjectiveCompletion(Quest, 1) < 2)then pPlayer:AdvanceQuestObjective(Quest, 1) end end end end function MoonTeleport( event, pPlayer, SpellId, pSpellObject ) local Quest = 8883 local Moonlight = 15897 if ( pPlayer:HasQuest(Quest) ) then local pMoonlight = pPlayer:GetCreatureNearestCoords(pPlayer:GetX(), pPlayer:GetY(), pPlayer:GetZ(), Moonlight) if ( pMoonlight ~= nil and pPlayer:GetDistanceYards(pMoonlight)<1.5) then RegisterTimedEvent("Moonflight", 2000, 1, pPlayer) end end end function Moonflight(pPlayer) pPlayer:Teleport(1, 7935, -2624, 492.6, 0.84) end RegisterServerHook(10, "LaunchRocket") -- SERVER_HOOK_CAST_SPELL RegisterServerHook(10, "MoonTeleport") -- SERVER_HOOK_CAST_SPELL
agpl-3.0
nasomi/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n1.lua
51
1327
----------------------------------- -- Area: Spire_of_vahlz -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/plate_of_anchovies.lua
35
1201
----------------------------------------- -- ID: 5652 -- Item: plate_of_anchovies -- Food Effect: 3Min, All Races ----------------------------------------- -- Dexterity 1 -- 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,180,5652); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_ACCP, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_ACCP, -3); end;
gpl-3.0
nicholas-leonard/nn
Reshape.lua
20
1893
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module') function Reshape:__init(...) parent.__init(self) local arg = {...} self.size = torch.LongStorage() self.batchsize = torch.LongStorage() if torch.type(arg[#arg]) == 'boolean' then self.batchMode = arg[#arg] table.remove(arg, #arg) end local n = #arg if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then self.size:resize(#arg[1]):copy(arg[1]) else self.size:resize(n) for i=1,n do self.size[i] = arg[i] end end self.nelement = 1 self.batchsize:resize(#self.size+1) for i=1,#self.size do self.nelement = self.nelement * self.size[i] self.batchsize[i+1] = self.size[i] end end function Reshape:updateOutput(input) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input) self._input:copy(input) input = self._input end if (self.batchMode == false) or ( (self.batchMode == nil) and (input:nElement() == self.nelement and input:size(1) ~= 1) ) then self.output:view(input, self.size) else self.batchsize[1] = input:size(1) self.output:view(input, self.batchsize) end return self.output end function Reshape:updateGradInput(input, gradOutput) if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end self.gradInput:viewAs(gradOutput, input) return self.gradInput end function Reshape:__tostring__() return torch.type(self) .. '(' .. table.concat(self.size:totable(), 'x') .. ')' end function Reshape:clearState() nn.utils.clear(self, '_input', '_gradOutput') return parent.clearState(self) end
bsd-3-clause
nasomi/darkstar
scripts/globals/weaponskills/shark_bite.lua
30
1459
----------------------------------- -- Shark Bite -- Dagger weapon skill -- Skill level: 225 -- Delivers a twofold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Will stack with Trick Attack. -- Aligned with the Breeze Gorget & Thunder Gorget. -- Aligned with the Breeze Belt & Thunder Belt. -- Element: None -- Modifiers: DEX:40% AGI:40% -- 100%TP 200%TP 300%TP -- 2.00 4 5.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 2; params.ftp200 = 2.5; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.5; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 4; params.ftp300 = 5.75; params.dex_wsc = 0.4; params.agi_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
keharriso/love-nuklear
example/closure.lua
1
1142
-- Show off the optional closure-oriented versions of basic functions local function menu(ui) ui:layoutRow('dynamic', 30, 2) ui:menu('Menu A', nil, 100, 200, function () ui:layoutRow('dynamic', 30, 1) if ui:menuItem('Item 1') then print 'Closure: Item 1' end if ui:menuItem('Item 2') then print 'Closure: Item 2' end end) ui:menu('Menu B', nil, 100, 200, function () ui:layoutRow('dynamic', 30, 1) if ui:menuItem('Item 3') then print 'Closure: Item 3' end if ui:menuItem('Item 4') then print 'Closure: Item 4' end end) end local comboText = 'Combo 1' function combo(ui) ui:layoutRow('dynamic', 30, 1) if ui:comboboxItem('Combo 1') then print 'Closure: Combo 1' comboText = 'Combo 1' end if ui:comboboxItem('Combo 2') then print 'Closure: Combo 2' comboText = 'Combo 2' end if ui:comboboxItem('Combo 3') then print 'Closure: Combo 3' comboText = 'Combo 3' end end local function window(ui) ui:menubar(menu) ui:layoutRow('dynamic', 30, 1) ui:combobox(comboText, combo) end return function (ui) ui:window('Closure', 200, 200, 150, 120, {'title', 'movable', 'border'}, window) end
mit
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/wifi.lua
27
33913
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local wa = require "luci.tools.webadmin" local nw = require "luci.model.network" local ut = require "luci.util" local nt = require "luci.sys".net local fs = require "nixio.fs" arg[1] = arg[1] or "" m = Map("wireless", "", translate("The <em>Device Configuration</em> section covers physical settings of the radio " .. "hardware such as channel, transmit power or antenna selection which are shared among all " .. "defined wireless networks (if the radio hardware is multi-SSID capable). Per network settings " .. "like encryption or operation mode are grouped in the <em>Interface Configuration</em>.")) m:chain("network") m:chain("firewall") local ifsection function m.on_commit(map) local wnet = nw:get_wifinet(arg[1]) if ifsection and wnet then ifsection.section = wnet.sid m.title = luci.util.pcdata(wnet:get_i18n()) end end nw.init(m.uci) local wnet = nw:get_wifinet(arg[1]) local wdev = wnet and wnet:get_device() -- redirect to overview page if network does not exist anymore (e.g. after a revert) if not wnet or not wdev then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) return end -- wireless toggle was requested, commit and reload page function m.parse(map) if m:formvalue("cbid.wireless.%s.__toggle" % wdev:name()) then if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then wnet:set("disabled", nil) else wnet:set("disabled", "1") end wdev:set("disabled", nil) nw:commit("wireless") luci.sys.call("(env -i /bin/ubus call network reload) >/dev/null 2>/dev/null") luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", arg[1])) return end Map.parse(map) end m.title = luci.util.pcdata(wnet:get_i18n()) local function txpower_list(iw) local list = iw.txpwrlist or { } local off = tonumber(iw.txpower_offset) or 0 local new = { } local prev = -1 local _, val for _, val in ipairs(list) do local dbm = val.dbm + off local mw = math.floor(10 ^ (dbm / 10)) if mw ~= prev then prev = mw new[#new+1] = { display_dbm = dbm, display_mw = mw, driver_dbm = val.dbm, driver_mw = val.mw } end end return new end local function txpower_current(pwr, list) pwr = tonumber(pwr) if pwr ~= nil then local _, item for _, item in ipairs(list) do if item.driver_dbm >= pwr then return item.driver_dbm end end end return (list[#list] and list[#list].driver_dbm) or pwr or 0 end local iw = luci.sys.wifi.getiwinfo(arg[1]) local hw_modes = iw.hwmodelist or { } local tx_power_list = txpower_list(iw) local tx_power_cur = txpower_current(wdev:get("txpower"), tx_power_list) s = m:section(NamedSection, wdev:name(), "wifi-device", translate("Device Configuration")) s.addremove = false s:tab("general", translate("General Setup")) s:tab("macfilter", translate("MAC-Filter")) s:tab("advanced", translate("Advanced Settings")) --[[ back = s:option(DummyValue, "_overview", translate("Overview")) back.value = "" back.titleref = luci.dispatcher.build_url("admin", "network", "wireless") ]] st = s:taboption("general", DummyValue, "__status", translate("Status")) st.template = "admin_network/wifi_status" st.ifname = arg[1] en = s:taboption("general", Button, "__toggle") if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then en.title = translate("Wireless network is disabled") en.inputtitle = translate("Enable") en.inputstyle = "apply" else en.title = translate("Wireless network is enabled") en.inputtitle = translate("Disable") en.inputstyle = "reset" end local hwtype = wdev:get("type") -- NanoFoo local nsantenna = wdev:get("antenna") -- Check whether there is a client interface on the same radio, -- if yes, lock the channel choice as the station will dicatate the freq local has_sta = nil local _, net for _, net in ipairs(wdev:get_wifinets()) do if net:mode() == "sta" and net:id() ~= wnet:id() then has_sta = net break end end if has_sta then ch = s:taboption("general", DummyValue, "choice", translate("Channel")) ch.value = translatef("Locked to channel %d used by %s", has_sta:channel(), has_sta:shortname()) else ch = s:taboption("general", Value, "channel", translate("Channel")) ch:value("auto", translate("auto")) for _, f in ipairs(iw and iw.freqlist or { }) do if not f.restricted then ch:value(f.channel, "%i (%.3f GHz)" %{ f.channel, f.mhz / 1000 }) end end end ------------------- MAC80211 Device ------------------ if hwtype == "mac80211" then if #tx_power_list > 1 then tp = s:taboption("general", ListValue, "txpower", translate("Transmit Power"), "dBm") tp.rmempty = true tp.default = tx_power_cur function tp.cfgvalue(...) return txpower_current(Value.cfgvalue(...), tx_power_list) end for _, p in ipairs(tx_power_list) do tp:value(p.driver_dbm, "%i dBm (%i mW)" %{ p.display_dbm, p.display_mw }) end end mode = s:taboption("advanced", ListValue, "hwmode", translate("Band")) if hw_modes.n then if hw_modes.g then mode:value("11g", "2.4GHz (802.11g+n)") end if hw_modes.a then mode:value("11a", "5GHz (802.11a+n)") end htmode = s:taboption("advanced", ListValue, "htmode", translate("HT mode (802.11n)")) htmode:value("", translate("disabled")) htmode:value("HT20", "20MHz") htmode:value("HT40", "40MHz") function mode.cfgvalue(...) local v = Value.cfgvalue(...) if v == "11na" then return "11a" elseif v == "11ng" then return "11g" end return v end noscan = s:taboption("advanced", Flag, "noscan", translate("Force 40MHz mode"), translate("Always use 40MHz channels even if the secondary channel overlaps. Using this option does not comply with IEEE 802.11n-2009!")) noscan:depends("htmode", "HT40") noscan.default = noscan.disabled else if hw_modes.g then mode:value("11g", "2.4GHz (802.11g)") end if hw_modes.a then mode:value("11a", "5GHz (802.11a)") end end local cl = iw and iw.countrylist if cl and #cl > 0 then cc = s:taboption("advanced", ListValue, "country", translate("Country Code"), translate("Use ISO/IEC 3166 alpha2 country codes.")) cc.default = tostring(iw and iw.country or "00") for _, c in ipairs(cl) do cc:value(c.alpha2, "%s - %s" %{ c.alpha2, c.name }) end else s:taboption("advanced", Value, "country", translate("Country Code"), translate("Use ISO/IEC 3166 alpha2 country codes.")) end s:taboption("advanced", Value, "distance", translate("Distance Optimization"), translate("Distance to farthest network member in meters.")) -- external antenna profiles local eal = iw and iw.extant if eal and #eal > 0 then ea = s:taboption("advanced", ListValue, "extant", translate("Antenna Configuration")) for _, eap in ipairs(eal) do ea:value(eap.id, "%s (%s)" %{ eap.name, eap.description }) if eap.selected then ea.default = eap.id end end end s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold")) s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold")) end ------------------- Madwifi Device ------------------ if hwtype == "atheros" then tp = s:taboption("general", (#tx_power_list > 0) and ListValue or Value, "txpower", translate("Transmit Power"), "dBm") tp.rmempty = true tp.default = tx_power_cur function tp.cfgvalue(...) return txpower_current(Value.cfgvalue(...), tx_power_list) end for _, p in ipairs(tx_power_list) do tp:value(p.driver_dbm, "%i dBm (%i mW)" %{ p.display_dbm, p.display_mw }) end mode = s:taboption("advanced", ListValue, "hwmode", translate("Mode")) mode:value("", translate("auto")) if hw_modes.b then mode:value("11b", "802.11b") end if hw_modes.g then mode:value("11g", "802.11g") end if hw_modes.a then mode:value("11a", "802.11a") end if hw_modes.g then mode:value("11bg", "802.11b+g") end if hw_modes.g then mode:value("11gst", "802.11g + Turbo") end if hw_modes.a then mode:value("11ast", "802.11a + Turbo") end mode:value("fh", translate("Frequency Hopping")) s:taboption("advanced", Flag, "diversity", translate("Diversity")).rmempty = false if not nsantenna then ant1 = s:taboption("advanced", ListValue, "txantenna", translate("Transmitter Antenna")) ant1.widget = "radio" ant1.orientation = "horizontal" ant1:depends("diversity", "") ant1:value("0", translate("auto")) ant1:value("1", translate("Antenna 1")) ant1:value("2", translate("Antenna 2")) ant2 = s:taboption("advanced", ListValue, "rxantenna", translate("Receiver Antenna")) ant2.widget = "radio" ant2.orientation = "horizontal" ant2:depends("diversity", "") ant2:value("0", translate("auto")) ant2:value("1", translate("Antenna 1")) ant2:value("2", translate("Antenna 2")) else -- NanoFoo local ant = s:taboption("advanced", ListValue, "antenna", translate("Transmitter Antenna")) ant:value("auto") ant:value("vertical") ant:value("horizontal") ant:value("external") end s:taboption("advanced", Value, "distance", translate("Distance Optimization"), translate("Distance to farthest network member in meters.")) s:taboption("advanced", Value, "regdomain", translate("Regulatory Domain")) s:taboption("advanced", Value, "country", translate("Country Code")) s:taboption("advanced", Flag, "outdoor", translate("Outdoor Channels")) --s:option(Flag, "nosbeacon", translate("Disable HW-Beacon timer")) end ------------------- Broadcom Device ------------------ if hwtype == "broadcom" then tp = s:taboption("general", (#tx_power_list > 0) and ListValue or Value, "txpower", translate("Transmit Power"), "dBm") tp.rmempty = true tp.default = tx_power_cur function tp.cfgvalue(...) return txpower_current(Value.cfgvalue(...), tx_power_list) end for _, p in ipairs(tx_power_list) do tp:value(p.driver_dbm, "%i dBm (%i mW)" %{ p.display_dbm, p.display_mw }) end mode = s:taboption("advanced", ListValue, "hwmode", translate("Mode")) mode:value("11bg", "802.11b+g") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11gst", "802.11g + Turbo") ant1 = s:taboption("advanced", ListValue, "txantenna", translate("Transmitter Antenna")) ant1.widget = "radio" ant1:depends("diversity", "") ant1:value("3", translate("auto")) ant1:value("0", translate("Antenna 1")) ant1:value("1", translate("Antenna 2")) ant2 = s:taboption("advanced", ListValue, "rxantenna", translate("Receiver Antenna")) ant2.widget = "radio" ant2:depends("diversity", "") ant2:value("3", translate("auto")) ant2:value("0", translate("Antenna 1")) ant2:value("1", translate("Antenna 2")) s:taboption("advanced", Flag, "frameburst", translate("Frame Bursting")) s:taboption("advanced", Value, "distance", translate("Distance Optimization")) --s:option(Value, "slottime", translate("Slot time")) s:taboption("advanced", Value, "country", translate("Country Code")) s:taboption("advanced", Value, "maxassoc", translate("Connection Limit")) end --------------------- HostAP Device --------------------- if hwtype == "prism2" then s:taboption("advanced", Value, "txpower", translate("Transmit Power"), "att units").rmempty = true s:taboption("advanced", Flag, "diversity", translate("Diversity")).rmempty = false s:taboption("advanced", Value, "txantenna", translate("Transmitter Antenna")) s:taboption("advanced", Value, "rxantenna", translate("Receiver Antenna")) end ----------------------- Interface ----------------------- s = m:section(NamedSection, wnet.sid, "wifi-iface", translate("Interface Configuration")) ifsection = s s.addremove = false s.anonymous = true s.defaults.device = wdev:name() s:tab("general", translate("General Setup")) s:tab("encryption", translate("Wireless Security")) s:tab("macfilter", translate("MAC-Filter")) s:tab("advanced", translate("Advanced Settings")) s:taboption("general", Value, "ssid", translate("<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) mode = s:taboption("general", ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Access Point")) mode:value("sta", translate("Client")) mode:value("adhoc", translate("Ad-Hoc")) bssid = s:taboption("general", Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) network = s:taboption("general", Value, "network", translate("Network"), translate("Choose the network(s) you want to attach to this wireless interface or " .. "fill out the <em>create</em> field to define a new network.")) network.rmempty = true network.template = "cbi/network_netlist" network.widget = "checkbox" network.novirtual = true function network.write(self, section, value) local i = nw:get_interface(section) if i then if value == '-' then value = m:formvalue(self:cbid(section) .. ".newnet") if value and #value > 0 then local n = nw:add_network(value, {proto="none"}) if n then n:add_interface(i) end else local n = i:get_network() if n then n:del_interface(i) end end else local v for _, v in ipairs(i:get_networks()) do v:del_interface(i) end for v in ut.imatch(value) do local n = nw:get_network(v) if n then if not n:is_empty() then n:set("type", "bridge") end n:add_interface(i) end end end end end -------------------- MAC80211 Interface ---------------------- if hwtype == "mac80211" then if fs.access("/usr/sbin/iw") then mode:value("mesh", "802.11s") end mode:value("ahdemo", translate("Pseudo Ad-Hoc (ahdemo)")) mode:value("monitor", translate("Monitor")) bssid:depends({mode="adhoc"}) bssid:depends({mode="sta"}) bssid:depends({mode="sta-wds"}) mp = s:taboption("macfilter", ListValue, "macfilter", translate("MAC-Address Filter")) mp:depends({mode="ap"}) mp:depends({mode="ap-wds"}) mp:value("", translate("disable")) mp:value("allow", translate("Allow listed only")) mp:value("deny", translate("Allow all except listed")) ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List")) ml.datatype = "macaddr" ml:depends({macfilter="allow"}) ml:depends({macfilter="deny"}) nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end) mode:value("ap-wds", "%s (%s)" % {translate("Access Point"), translate("WDS")}) mode:value("sta-wds", "%s (%s)" % {translate("Client"), translate("WDS")}) function mode.write(self, section, value) if value == "ap-wds" then ListValue.write(self, section, "ap") m.uci:set("wireless", section, "wds", 1) elseif value == "sta-wds" then ListValue.write(self, section, "sta") m.uci:set("wireless", section, "wds", 1) else ListValue.write(self, section, value) m.uci:delete("wireless", section, "wds") end end function mode.cfgvalue(self, section) local mode = ListValue.cfgvalue(self, section) local wds = m.uci:get("wireless", section, "wds") == "1" if mode == "ap" and wds then return "ap-wds" elseif mode == "sta" and wds then return "sta-wds" else return mode end end hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hidden:depends({mode="ap"}) hidden:depends({mode="ap-wds"}) wmm = s:taboption("general", Flag, "wmm", translate("WMM Mode")) wmm:depends({mode="ap"}) wmm:depends({mode="ap-wds"}) wmm.default = wmm.enabled end -------------------- Madwifi Interface ---------------------- if hwtype == "atheros" then mode:value("ahdemo", translate("Pseudo Ad-Hoc (ahdemo)")) mode:value("monitor", translate("Monitor")) mode:value("ap-wds", "%s (%s)" % {translate("Access Point"), translate("WDS")}) mode:value("sta-wds", "%s (%s)" % {translate("Client"), translate("WDS")}) mode:value("wds", translate("Static WDS")) function mode.write(self, section, value) if value == "ap-wds" then ListValue.write(self, section, "ap") m.uci:set("wireless", section, "wds", 1) elseif value == "sta-wds" then ListValue.write(self, section, "sta") m.uci:set("wireless", section, "wds", 1) else ListValue.write(self, section, value) m.uci:delete("wireless", section, "wds") end end function mode.cfgvalue(self, section) local mode = ListValue.cfgvalue(self, section) local wds = m.uci:get("wireless", section, "wds") == "1" if mode == "ap" and wds then return "ap-wds" elseif mode == "sta" and wds then return "sta-wds" else return mode end end bssid:depends({mode="adhoc"}) bssid:depends({mode="ahdemo"}) bssid:depends({mode="wds"}) wdssep = s:taboption("advanced", Flag, "wdssep", translate("Separate WDS")) wdssep:depends({mode="ap-wds"}) s:taboption("advanced", Flag, "doth", "802.11h") hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hidden:depends({mode="ap"}) hidden:depends({mode="adhoc"}) hidden:depends({mode="ap-wds"}) hidden:depends({mode="sta-wds"}) isolate = s:taboption("advanced", Flag, "isolate", translate("Separate Clients"), translate("Prevents client-to-client communication")) isolate:depends({mode="ap"}) s:taboption("advanced", Flag, "bgscan", translate("Background Scan")) mp = s:taboption("macfilter", ListValue, "macpolicy", translate("MAC-Address Filter")) mp:value("", translate("disable")) mp:value("allow", translate("Allow listed only")) mp:value("deny", translate("Allow all except listed")) ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List")) ml.datatype = "macaddr" ml:depends({macpolicy="allow"}) ml:depends({macpolicy="deny"}) nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end) s:taboption("advanced", Value, "rate", translate("Transmission Rate")) s:taboption("advanced", Value, "mcast_rate", translate("Multicast Rate")) s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold")) s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold")) s:taboption("advanced", Value, "minrate", translate("Minimum Rate")) s:taboption("advanced", Value, "maxrate", translate("Maximum Rate")) s:taboption("advanced", Flag, "compression", translate("Compression")) s:taboption("advanced", Flag, "bursting", translate("Frame Bursting")) s:taboption("advanced", Flag, "turbo", translate("Turbo Mode")) s:taboption("advanced", Flag, "ff", translate("Fast Frames")) s:taboption("advanced", Flag, "wmm", translate("WMM Mode")) s:taboption("advanced", Flag, "xr", translate("XR Support")) s:taboption("advanced", Flag, "ar", translate("AR Support")) local swm = s:taboption("advanced", Flag, "sw_merge", translate("Disable HW-Beacon timer")) swm:depends({mode="adhoc"}) local nos = s:taboption("advanced", Flag, "nosbeacon", translate("Disable HW-Beacon timer")) nos:depends({mode="sta"}) nos:depends({mode="sta-wds"}) local probereq = s:taboption("advanced", Flag, "probereq", translate("Do not send probe responses")) probereq.enabled = "0" probereq.disabled = "1" end -------------------- Broadcom Interface ---------------------- if hwtype == "broadcom" then mode:value("wds", translate("WDS")) mode:value("monitor", translate("Monitor")) hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hidden:depends({mode="ap"}) hidden:depends({mode="adhoc"}) hidden:depends({mode="wds"}) isolate = s:taboption("advanced", Flag, "isolate", translate("Separate Clients"), translate("Prevents client-to-client communication")) isolate:depends({mode="ap"}) s:taboption("advanced", Flag, "doth", "802.11h") s:taboption("advanced", Flag, "wmm", translate("WMM Mode")) bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end ----------------------- HostAP Interface --------------------- if hwtype == "prism2" then mode:value("wds", translate("WDS")) mode:value("monitor", translate("Monitor")) hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hidden:depends({mode="ap"}) hidden:depends({mode="adhoc"}) hidden:depends({mode="wds"}) bssid:depends({mode="sta"}) mp = s:taboption("macfilter", ListValue, "macpolicy", translate("MAC-Address Filter")) mp:value("", translate("disable")) mp:value("allow", translate("Allow listed only")) mp:value("deny", translate("Allow all except listed")) ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List")) ml:depends({macpolicy="allow"}) ml:depends({macpolicy="deny"}) nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end) s:taboption("advanced", Value, "rate", translate("Transmission Rate")) s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold")) s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold")) end ------------------- WiFI-Encryption ------------------- encr = s:taboption("encryption", ListValue, "encryption", translate("Encryption")) encr.override_values = true encr.override_depends = true encr:depends({mode="ap"}) encr:depends({mode="sta"}) encr:depends({mode="adhoc"}) encr:depends({mode="ahdemo"}) encr:depends({mode="ap-wds"}) encr:depends({mode="sta-wds"}) encr:depends({mode="mesh"}) cipher = s:taboption("encryption", ListValue, "cipher", translate("Cipher")) cipher:depends({encryption="wpa"}) cipher:depends({encryption="wpa2"}) cipher:depends({encryption="psk"}) cipher:depends({encryption="psk2"}) cipher:depends({encryption="wpa-mixed"}) cipher:depends({encryption="psk-mixed"}) cipher:value("auto", translate("auto")) cipher:value("ccmp", translate("Force CCMP (AES)")) cipher:value("tkip", translate("Force TKIP")) cipher:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)")) function encr.cfgvalue(self, section) local v = tostring(ListValue.cfgvalue(self, section)) if v == "wep" then return "wep-open" elseif v and v:match("%+") then return (v:gsub("%+.+$", "")) end return v end function encr.write(self, section, value) local e = tostring(encr:formvalue(section)) local c = tostring(cipher:formvalue(section)) if value == "wpa" or value == "wpa2" then self.map.uci:delete("wireless", section, "key") end if e and (c == "tkip" or c == "ccmp" or c == "tkip+ccmp") then e = e .. "+" .. c end self.map:set(section, "encryption", e) end function cipher.cfgvalue(self, section) local v = tostring(ListValue.cfgvalue(encr, section)) if v and v:match("%+") then v = v:gsub("^[^%+]+%+", "") if v == "aes" then v = "ccmp" elseif v == "tkip+aes" then v = "tkip+ccmp" elseif v == "aes+tkip" then v = "tkip+ccmp" elseif v == "ccmp+tkip" then v = "tkip+ccmp" end end return v end function cipher.write(self, section) return encr:write(section) end encr:value("none", "No Encryption") encr:value("wep-open", translate("WEP Open System"), {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}, {mode="adhoc"}, {mode="ahdemo"}, {mode="wds"}) encr:value("wep-shared", translate("WEP Shared Key"), {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}, {mode="adhoc"}, {mode="ahdemo"}, {mode="wds"}) if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") -- Probe EAP support local has_ap_eap = (os.execute("hostapd -veap >/dev/null 2>/dev/null") == 0) local has_sta_eap = (os.execute("wpa_supplicant -veap >/dev/null 2>/dev/null") == 0) if hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}) if has_ap_eap and has_sta_eap then encr:value("wpa", "WPA-EAP", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}) encr:value("wpa2", "WPA2-EAP", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}) end elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="ap-wds"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="ap-wds"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="ap-wds"}) if has_ap_eap then encr:value("wpa", "WPA-EAP", {mode="ap"}, {mode="ap-wds"}) encr:value("wpa2", "WPA2-EAP", {mode="ap"}, {mode="ap-wds"}) end encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}, {mode="sta-wds"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}, {mode="sta-wds"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}, {mode="sta-wds"}) if has_sta_eap then encr:value("wpa", "WPA-EAP", {mode="sta"}, {mode="sta-wds"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}, {mode="sta-wds"}) end encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end auth_server = s:taboption("encryption", Value, "auth_server", translate("Radius-Authentication-Server")) auth_server:depends({mode="ap", encryption="wpa"}) auth_server:depends({mode="ap", encryption="wpa2"}) auth_server:depends({mode="ap-wds", encryption="wpa"}) auth_server:depends({mode="ap-wds", encryption="wpa2"}) auth_server.rmempty = true auth_server.datatype = "host" auth_port = s:taboption("encryption", Value, "auth_port", translate("Radius-Authentication-Port"), translatef("Default %d", 1812)) auth_port:depends({mode="ap", encryption="wpa"}) auth_port:depends({mode="ap", encryption="wpa2"}) auth_port:depends({mode="ap-wds", encryption="wpa"}) auth_port:depends({mode="ap-wds", encryption="wpa2"}) auth_port.rmempty = true auth_port.datatype = "port" auth_secret = s:taboption("encryption", Value, "auth_secret", translate("Radius-Authentication-Secret")) auth_secret:depends({mode="ap", encryption="wpa"}) auth_secret:depends({mode="ap", encryption="wpa2"}) auth_secret:depends({mode="ap-wds", encryption="wpa"}) auth_secret:depends({mode="ap-wds", encryption="wpa2"}) auth_secret.rmempty = true auth_secret.password = true acct_server = s:taboption("encryption", Value, "acct_server", translate("Radius-Accounting-Server")) acct_server:depends({mode="ap", encryption="wpa"}) acct_server:depends({mode="ap", encryption="wpa2"}) acct_server:depends({mode="ap-wds", encryption="wpa"}) acct_server:depends({mode="ap-wds", encryption="wpa2"}) acct_server.rmempty = true acct_server.datatype = "host" acct_port = s:taboption("encryption", Value, "acct_port", translate("Radius-Accounting-Port"), translatef("Default %d", 1813)) acct_port:depends({mode="ap", encryption="wpa"}) acct_port:depends({mode="ap", encryption="wpa2"}) acct_port:depends({mode="ap-wds", encryption="wpa"}) acct_port:depends({mode="ap-wds", encryption="wpa2"}) acct_port.rmempty = true acct_port.datatype = "port" acct_secret = s:taboption("encryption", Value, "acct_secret", translate("Radius-Accounting-Secret")) acct_secret:depends({mode="ap", encryption="wpa"}) acct_secret:depends({mode="ap", encryption="wpa2"}) acct_secret:depends({mode="ap-wds", encryption="wpa"}) acct_secret:depends({mode="ap-wds", encryption="wpa2"}) acct_secret.rmempty = true acct_secret.password = true wpakey = s:taboption("encryption", Value, "_wpa_key", translate("Key")) wpakey:depends("encryption", "psk") wpakey:depends("encryption", "psk2") wpakey:depends("encryption", "psk+psk2") wpakey:depends("encryption", "psk-mixed") wpakey.datatype = "wpakey" wpakey.rmempty = true wpakey.password = true wpakey.cfgvalue = function(self, section, value) local key = m.uci:get("wireless", section, "key") if key == "1" or key == "2" or key == "3" or key == "4" then return nil end return key end wpakey.write = function(self, section, value) self.map.uci:set("wireless", section, "key", value) self.map.uci:delete("wireless", section, "key1") end wepslot = s:taboption("encryption", ListValue, "_wep_key", translate("Used Key Slot")) wepslot:depends("encryption", "wep-open") wepslot:depends("encryption", "wep-shared") wepslot:value("1", translatef("Key #%d", 1)) wepslot:value("2", translatef("Key #%d", 2)) wepslot:value("3", translatef("Key #%d", 3)) wepslot:value("4", translatef("Key #%d", 4)) wepslot.cfgvalue = function(self, section) local slot = tonumber(m.uci:get("wireless", section, "key")) if not slot or slot < 1 or slot > 4 then return 1 end return slot end wepslot.write = function(self, section, value) self.map.uci:set("wireless", section, "key", value) end local slot for slot=1,4 do wepkey = s:taboption("encryption", Value, "key" .. slot, translatef("Key #%d", slot)) wepkey:depends("encryption", "wep-open") wepkey:depends("encryption", "wep-shared") wepkey.datatype = "wepkey" wepkey.rmempty = true wepkey.password = true function wepkey.write(self, section, value) if value and (#value == 5 or #value == 13) then value = "s:" .. value end return Value.write(self, section, value) end end if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then nasid = s:taboption("encryption", Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid:depends({mode="ap-wds", encryption="wpa"}) nasid:depends({mode="ap-wds", encryption="wpa2"}) nasid.rmempty = true eaptype = s:taboption("encryption", ListValue, "eap_type", translate("EAP-Method")) eaptype:value("tls", "TLS") eaptype:value("ttls", "TTLS") eaptype:value("peap", "PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) eaptype:depends({mode="sta-wds", encryption="wpa"}) eaptype:depends({mode="sta-wds", encryption="wpa2"}) cacert = s:taboption("encryption", FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) cacert:depends({mode="sta-wds", encryption="wpa"}) cacert:depends({mode="sta-wds", encryption="wpa2"}) clientcert = s:taboption("encryption", FileUpload, "client_cert", translate("Path to Client-Certificate")) clientcert:depends({mode="sta", encryption="wpa"}) clientcert:depends({mode="sta", encryption="wpa2"}) clientcert:depends({mode="sta-wds", encryption="wpa"}) clientcert:depends({mode="sta-wds", encryption="wpa2"}) privkey = s:taboption("encryption", FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="tls", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="tls", encryption="wpa"}) privkey:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"}) privkey:depends({mode="sta-wds", eap_type="tls", encryption="wpa"}) privkeypwd = s:taboption("encryption", Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="tls", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="tls", encryption="wpa"}) privkeypwd:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"}) privkeypwd:depends({mode="sta-wds", eap_type="tls", encryption="wpa"}) auth = s:taboption("encryption", Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="peap", encryption="wpa2"}) auth:depends({mode="sta", eap_type="peap", encryption="wpa"}) auth:depends({mode="sta", eap_type="ttls", encryption="wpa2"}) auth:depends({mode="sta", eap_type="ttls", encryption="wpa"}) auth:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"}) auth:depends({mode="sta-wds", eap_type="peap", encryption="wpa"}) auth:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"}) auth:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"}) identity = s:taboption("encryption", Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="peap", encryption="wpa2"}) identity:depends({mode="sta", eap_type="peap", encryption="wpa"}) identity:depends({mode="sta", eap_type="ttls", encryption="wpa2"}) identity:depends({mode="sta", eap_type="ttls", encryption="wpa"}) identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"}) identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa"}) identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"}) identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"}) password = s:taboption("encryption", Value, "password", translate("Password")) password:depends({mode="sta", eap_type="peap", encryption="wpa2"}) password:depends({mode="sta", eap_type="peap", encryption="wpa"}) password:depends({mode="sta", eap_type="ttls", encryption="wpa2"}) password:depends({mode="sta", eap_type="ttls", encryption="wpa"}) password:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"}) password:depends({mode="sta-wds", eap_type="peap", encryption="wpa"}) password:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"}) password:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"}) end return m
gpl-2.0
the0val/SmartMine-Turtle
smartmine.lua
1
7281
--[[ Stripminer by ]] -- preferences local branchSpacing = 12 -- Distance the turtle moves between branches. One more than the number of blocks between tunnels (12) local branchLenth = 200 -- Minimum length of branch. Last pokehole will be placed either on this distance or as the only set of pokeholes after (200) local pokeSpacing = 4 -- Distance the turtle moves before next poke. One more than the number of blocks inbetween (4) local pokeLenth = 5 -- Lenth of pokeholes (5) local torchSlot = 16 -- Slot to find torches in, used to light up the branches and main tunnel (16) local smartMine = true -- Whether or not to scan surrounding blocks for ores (true) -- ores that the turtle should look for and mine if found table.insert(ores.general, "minecraft:gold_ore") table.insert(ores.general, "minecraft:iron_ore") table.insert(ores.general, "minecraft:coal_ore") table.insert(ores.general, "minecraft:lapis_ore") table.insert(ores.general, "minecraft:diamond_ore") table.insert(ores.general, "minecraft:redstone_ore") table.insert(ores.general, "minecraft:emerald_ore") -- variables local torchSpacing = 12 local posData = {} local smartMove = {} -- Table containing movemnent functions local ores = {detailed = {}, general = {}} -- List of ores that should be mined when detected. Detailed for metadata-sensetive, general for metadata-insensetive local mineOre = function() end local writePosData = function() end -- Sets up a metatabel for posData to call writePosData every time a value in posData changes -- This is to make resuming after turning of the turtle easier do local posStorage = {branchesDug = 0, action = "", otherInfo = ""} local posMetatable = {__index = posStorage, __newindex = function(_, key, value) posStorage[key] = value writePosData() end} setmetatable(posData, posMetatable) end -------------- -- functions-- -------------- -- Basic local function sForward() -- Moves the turtle forward and removes any blocks or kills mobs that are in the way while not turtle.forward() do turtle.dig() turtle.attack() end end smartMove.forward = sForward smartMove.back = turtle.back local function sUp() -- Moves the turtle up and removes any blocks or kills mobs that are in the way while not turtle.up() do turtle.digUp() turtle.attackUp() end end smartMove.up = sUp local function sDown() -- Moves the turtle down and removes any blocks or kills mobs that are in the way while not turtle.down() do turtle.digDown() turtle.attackDown() end end smartMove.down = sDown -- Math, logic and data handling local function addToOres( includeMeta, data ) if includeMeta then ores.detailed[data.name.."/"..data.metadata] = true else ores.general[data.name] = true end end local function inspect( direction ) -- Checks 'direction' and mines it using mineOre() if it matches something in ores direction = direction or "" local functionStr = "inspect"..direction local success, data = turtle[functionStr]() if success then if ores.detailed[data.name.."/"..data.metadata] or ores.general[data.name] then mineOre(string.lower(direction)) end end end local function inspectUp() inspect("Up") end local function inspectDown() inspect("Down") end local function inspectLower() inspectDown() inspect() end local function inspectUpper() inspectUp() inspect() end local function inspectAll() inspectUpper() inspectDown() turtle.turnLeft() inspect() turtle.turnLeft() turtle.turnLeft() inspect() turtle.turnLeft() end -- Final movement local function poke() -- digs a 1*1 hole on either side with depth pokeLenth. Assumes turtle is facing in the direction of the branch turtle.turnRight() for i = 1, pokeLenth do sForward() inspectAll() end for i = 1, pokeLenth do turtle.back() end turtle.turnRight() turtle.turnRight() for i = 1, pokeLenth do sForward() inspectAll() end for i = 1, pokeLenth do turtle.back() end turtle.turnRight() end local function branch() --[[ Digs a 2*1 branch with pokeholes, places torches on the ground when going back. Assumes turtle is in front of where the branch starts, facing the right way and one block of the ground. Returns to starting position when done]] local lengthDug = 0 turtle.select(torchSlot) -- prepare and position for i = 1, (posData.branchesDug % 2) + 2 do sForward() inspectUp() turtle.digDown() end poke() local pokeholesDug = 0 while lengthDug < branchLenth do for i = 1, pokeSpacing do sForward() inspectUpper() turtle.digDown() lengthDug = lengthDug + 1 end poke() end -- go back and place torches inspect() turtle.down() inspect() for i = 0, lengthDug - 1 do turtle.back() inspectDown() if i % torchSpacing == 1 then turtle.select(torchSlot) turtle.place() end end for i = 1, (posData.branchesDug % 2) + 2 do turtle.back() inspectDown() if i % torchSpacing == 1 then turtle.select(torchSlot) turtle.place() end end posData.branchesDug = posData.branchesDug + 1 turtle.up() end local function tunnel() --[[ moves and digs in main tunnel assumes you are in the center of the tunnel and that your facing the way of the tunnel in the end, you will be facing th same way you started and still in the middle]] posData.state = "tunnel_dig" for i = 1, branchSpacing do sForward() turtle.digUp() turtle.digDown() turtle.turnLeft() sForward() turtle.digUp() turtle.digDown() turtle.back() turtle.turnLeft() turtle.turnLeft() sForward() turtle.digUp() turtle.digDown() turtle.back() turtle.turnLeft() if i == math.ceil(branchSpacing / 2) then turtle.turnRight() turtle.place() turtle.turnLeft() end end end function mineOre( moveDirection ) -- Recursive function that mines every ore in a connected cluster by checking all surrounding blocks using inspect() moveDirection = (moveDirection == "" or moveDirection == nil) and "forward" or moveDirection local opposites = {up = "down", down = "up", forward = "back"} smartMove[moveDirection]() inspectUp() inspectLower() turtle.turnLeft() inspect() turtle.turnLeft() inspect() turtle.turnLeft() inspect() turtle.turnLeft() smartMove[opposites[moveDirection]]() end -- File system local function initPosData() -- reads from file .smartminePos. If present initializes posData with those values -- if absent assumes it's the first time running the program and keeps the values in posData if fs.exists(".smartminePos") then local file = fs.open(".smartminePos", "r") posData = textutils.unserialize(file.readAll()) file.close() end end local function writePosData() -- called every time posData is updated. Saves the content of posData is file .smartminePos local file = fs.open(".smartminePos", "w") file.write(textutils.serialize(posData)) file.close() end ------------------------ -- Program starts here-- ------------------------ -- Setup local brun = true --Loop while brun do branch() turtle.back() turtle.turnLeft() tunnel() turtle.turnRight() turtle.forward() end
mit
EricssonResearch/scott-eu
simulation-ros/src/turtlebot2i/turtlebot2i_safety/scenarios/turtlebot2i_GPS.lua
1
4720
-- Check the end of the script for some explanations! if (sim_call_type == sim.childscriptcall_initialization) then modelBase = sim.getObjectAssociatedWithScript(sim.handle_self) ref = sim.getObjectHandle('GPS_reference') xShiftAmplitude = 0 yShiftAmplitude = 0 zShiftAmplitude = 0 xShift = 0 yShift = 0 zShift = 0 end if (sim_call_type == sim.childscriptcall_cleanup) then end if (sim_call_type == sim.childscriptcall_sensing) then xNoiseAmplitude = sim.getScriptSimulationParameter(sim.handle_self,'xNoiseAmplitude') if not xNoiseAmplitude then xNoiseAmplitude=0 end if xNoiseAmplitude<0 then xNoiseAmplitude=0 end if xNoiseAmplitude>100 then xNoiseAmplitude=100 end yNoiseAmplitude = sim.getScriptSimulationParameter(sim.handle_self,'yNoiseAmplitude') if not yNoiseAmplitude then yNoiseAmplitude=0 end if yNoiseAmplitude<0 then yNoiseAmplitude=0 end if yNoiseAmplitude>100 then yNoiseAmplitude=100 end zNoiseAmplitude = sim.getScriptSimulationParameter(sim.handle_self,'zNoiseAmplitude') if not zNoiseAmplitude then zNoiseAmplitude=0 end if zNoiseAmplitude<0 then zNoiseAmplitude=0 end if zNoiseAmplitude>100 then zNoiseAmplitude=100 end xShiftAmplitudeN = sim.getScriptSimulationParameter(sim.handle_self,'xShiftAmplitude') if not xShiftAmplitudeN then xShiftAmplitudeN=0 end if xShiftAmplitudeN<0 then xShiftAmplitudeN=0 end if xShiftAmplitudeN>100 then xShiftAmplitudeN=100 end if (xShiftAmplitudeN~=xShiftAmplitude) then xShiftAmplitude=xShiftAmplitudeN xShift=2*(math.random()-0.5)*xShiftAmplitude end yShiftAmplitudeN = sim.getScriptSimulationParameter(sim.handle_self,'yShiftAmplitude') if not yShiftAmplitudeN then yShiftAmplitudeN=0 end if yShiftAmplitudeN<0 then yShiftAmplitudeN=0 end if yShiftAmplitudeN>100 then yShiftAmplitudeN=100 end if (yShiftAmplitudeN~=yShiftAmplitude) then yShiftAmplitude=yShiftAmplitudeN yShift=2*(math.random()-0.5)*yShiftAmplitude end zShiftAmplitudeN = sim.getScriptSimulationParameter(sim.handle_self,'zShiftAmplitude') if not zShiftAmplitudeN then zShiftAmplitudeN=0 end if zShiftAmplitudeN<0 then zShiftAmplitudeN=0 end if zShiftAmplitudeN>100 then zShiftAmplitudeN=100 end if (zShiftAmplitudeN~=zShiftAmplitude) then zShiftAmplitude=zShiftAmplitudeN zShift = 2*(math.random()-0.5) * zShiftAmplitude end objectAbsolutePosition = sim.getObjectPosition(ref, -1) -- Now add some noise to make it more realistic: objectAbsolutePosition[1] = objectAbsolutePosition[1] + 2*(math.random()-0.5) * xNoiseAmplitude+xShift objectAbsolutePosition[2] = objectAbsolutePosition[2] + 2*(math.random()-0.5) * yNoiseAmplitude+yShift objectAbsolutePosition[3] = objectAbsolutePosition[3] + 2*(math.random()-0.5) * zNoiseAmplitude+zShift -- sim.tubeWrite(gpsCommunicationTube,sim.packFloatTable(objectAbsolutePosition)) -- simSetUIButtonLabel(ui,3,string.format("X-pos: %.4f",objectAbsolutePosition[1])) -- simSetUIButtonLabel(ui,4,string.format("Y-pos: %.4f",objectAbsolutePosition[2])) -- simSetUIButtonLabel(ui,5,string.format("Z-pos: %.4f",objectAbsolutePosition[3])) -- To read data from this GPS in another script, use following code: -- -- gpsCommunicationTube=sim.tubeOpen(0,'gpsData'..sim.getNameSuffix(nil),1) -- put this in the initialization phase -- data=sim.tubeRead(gpsCommunicationTube) -- if (data) then -- gpsPosition=sim.unpackFloatTable(data) -- end -- -- If the script in which you read the gps has a different suffix than the GPS suffix, -- then you will have to slightly adjust the code, e.g.: -- gpsCommunicationTube=sim.tubeOpen(0,'gpsData#') -- if the GPS script has no suffix -- or -- gpsCommunicationTube=sim.tubeOpen(0,'gpsData#0') -- if the GPS script has a suffix 0 -- or -- gpsCommunicationTube=sim.tubeOpen(0,'gpsData#1') -- if the GPS script has a suffix 1 -- etc. -- -- -- You can of course also use global variables (not elegant and not scalable), e.g.: -- In the GPS script: -- sim.setFloatSignal('gpsX',objectAbsolutePosition[1]) -- sim.setFloatSignal('gpsY',objectAbsolutePosition[2]) -- sim.setFloatSignal('gpsZ',objectAbsolutePosition[3]) -- -- And in the script that needs the data: -- positionX=sim.getFloatSignal('gpsX') -- positionY=sim.getFloatSignal('gpsY') -- positionZ=sim.getFloatSignal('gpsZ') -- -- In addition to that, there are many other ways to have 2 scripts exchange data. Check the documentation for more details end
apache-2.0
sqow/strap-on
example/conf.lua
1
2201
function love.conf(t) t.identity = nil -- The name of the save directory (string) t.version = '0.9.2' -- The LÖVE version this game was made for (string) t.console = false -- Attach a console (boolean, Windows only) t.window.title = 'Dummy' -- The window title (string) t.window.icon = nil -- Filepath to an image to use as the windows icon (string) t.window.width = 800 -- The window width (number) t.window.height = 600 -- The window height (number) t.window.borderless = false -- Remove all border visuals from the window (boolean) t.window.resizable = false -- Let the window be user-resizable (boolean) t.window.minwidth = 800 -- Minimum window width if the window is resizable (number) t.window.minheight = 600 -- Minimum window height if the window is resizable (number) t.window.fullscreen = false -- Enable fullscreen (boolean) t.window.fullscreentype = 'normal' -- Standard fullscreen or desktop fullscreen mode (string) t.window.vsync = true -- Enable vertical sync (boolean) t.window.fsaa = 0 -- The number of samples to use with multi-sampled antialiasing (number) t.window.display = 1 -- Index of the monitor to show the window in (number) t.modules.audio = true -- Enable the audio module (boolean) t.modules.event = true -- Enable the event module (boolean) t.modules.graphics = true -- Enable the graphics module (boolean) t.modules.image = true -- Enable the image module (boolean) t.modules.joystick = true -- Enable the joystick module (boolean) t.modules.keyboard = true -- Enable the keyboard module (boolean) t.modules.math = true -- Enable the math module (boolean) t.modules.mouse = true -- Enable the mouse module (boolean) t.modules.physics = true -- Enable the physics module (boolean) t.modules.sound = true -- Enable the sound module (boolean) t.modules.system = true -- Enable the system module (boolean) t.modules.timer = true -- Enable the timer module (boolean) t.modules.window = true -- Enable the window module (boolean) end
mit
nasomi/darkstar
scripts/zones/Meriphataud_Mountains/npcs/qm1.lua
17
1385
----------------------------------- -- Area: Meriphataud Mountains -- NPC: qm1 (???) -- Involved in Quest: The Holy Crest -- @pos 641 -15 7 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Meriphataud_Mountains/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1159,1) and trade:getItemCount() == 1) then if (player:getVar("TheHolyCrest_Event") == 4) then player:startEvent(0x0038); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_FOUND); 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 == 0x0038) then player:tradeComplete(); player:setVar("TheHolyCrest_Event",5); player:startEvent(0x0021); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Pagisalis.lua
17
2933
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pagisalis -- Involved In Quest: Enveloped in Darkness -- @zone 231 -- @pos ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,UNDYING_FLAMES) == QUEST_ACCEPTED) then if (trade:hasItemQty(913,2) and trade:getItemCount() == 2) then -- Trade Lump of Beeswax player:startEvent(0x0233); end end if (player:hasKeyItem(OLD_POCKET_WATCH) and player:hasKeyItem(OLD_BOOTS) == false) then if (trade:hasItemQty(828,1) and trade:getItemCount() == 1) then -- Trade Velvet Cloth player:startEvent(0x0025); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) sanFame = player:getFameLevel(SANDORIA); undyingFlames = player:getQuestStatus(SANDORIA,UNDYING_FLAMES); if (player:hasKeyItem(OLD_POCKET_WATCH)) then player:startEvent(0x0030); elseif (player:hasKeyItem(OLD_BOOTS)) then player:startEvent(0x003A); elseif (sanFame >= 2 and undyingFlames == QUEST_AVAILABLE) then player:startEvent(0x0232); elseif (undyingFlames == QUEST_ACCEPTED) then player:startEvent(0x0235); elseif (undyingFlames == QUEST_COMPLETED) then player:startEvent(0x0236); else player:startEvent(0x0234) 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 == 0x0232 and option == 0) then player:addQuest(SANDORIA,UNDYING_FLAMES); elseif (csid == 0x0233) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13211); -- Friars Rope else player:tradeComplete(); player:addTitle(FAITH_LIKE_A_CANDLE); player:addItem(13211); player:messageSpecial(ITEM_OBTAINED,13211); -- Friars Rope player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,UNDYING_FLAMES); end elseif (csid == 0x0025) then player:tradeComplete(); player:delKeyItem(OLD_POCKET_WATCH); player:addKeyItem(OLD_BOOTS); player:messageSpecial(KEYITEM_OBTAINED,OLD_BOOTS); end end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/cyanviolet_fish_3.meta.lua
16
1896
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 80, light_colors = { "51 204 0 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/baka47_shot_8.meta.lua
2
2773
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 120, light_colors = { "255 128 0 255", "244 213 156 255", "72 71 71 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = -17, y = 7 }, rotation = 0 }, shell_spawn = { pos = { x = 3, y = -2 }, rotation = -75.963760375976562 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -33, y = 1 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
mortezamosavy999/index
bot/seedbot.lua
1
9621
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban" }, sudo_users = {67255537,0,tonumber(our_id)},--Sudo users disabled_channels = {}, realm = {data = 'data/moderation.json'},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[index v1 An advance Administration bot based on yagop/telegram-bot https://github.com/morteza999/index Admins @black_hat_admin02 [Manager] @black_hat_admin03 [Assistant1] @black_hat_2 [Assistant2] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @Indexzedspm [English-persian] ]], 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 ########################### !lock [member|name|bots] Locks [member|name|bots] ########################### !unlock [member|name|photo|bots] Unlocks [member|name|photo|bots] ########################### !set rules <text>😆 Set <text> as rules ########################### !set about <text>😄 Set <text> as about ########################### !settings Returns group settings ########################### !newlink😂 create/revoke your group link ########################### !link returns group link ########################### !owner😇 returns group owner id ########################### !setowner [id] Will set id as owner ########################### !setflood [value]😈 Set [value] as flood sensitivity ########################### !stats Simple message statistics ########################### !save [value] <text>😠 Save <text> as [value] ########################### !get [value] Returns text of [value] ########################### !clean [modlist|rules|about]😵 Will clear [modlist|rules|about] and set it to nil ########################### !res [username] returns user id "!res @username" ########################### !log😨 will return group logs ########################### !banlist will return group ban list **U can use both "/" and "!" *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 @indexzedspm ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\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
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Crilde.lua
36
1372
----------------------------------- -- Area: Port San d'Oria -- NPC: Crilde -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_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(0x239); 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
nasomi/darkstar
scripts/zones/Windurst_Woods/npcs/Valeriano.lua
36
1752
----------------------------------- -- Area: Windurst_Woods -- NPC: Valeriano -- Standard Merchant NPC -- Working 100% -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,VALERIANO_SHOP_DIALOG); stock = { 0x112A, 10, --Ginger Cookie 0x43C1, 43, --Flute 0x43C3, 990, --Piccolo 0x1399, 585, --Scroll of Scop's Operetta 0x139A, 16920, --Scroll of Puppet's Operetta 0x1395, 2916, --Scroll of Fowl Aubade 0x13A3, 2059, --Scroll of Advancing March 0x13D0, 90000, --Scroll of Goddess's Hymnus 0x13B9, 27140, --Scroll of Earth Carol II 0x13BB, 28520, --Scroll of Water Carol II 0x1384,123880 --Scroll of Mage's Ballad III } showShop(player, WINDURST, stock); 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
kerr-huang/SL4A
lua/luasocket/etc/get.lua
58
4133
----------------------------------------------------------------------------- -- Little program to download files from URLs -- LuaSocket sample files -- Author: Diego Nehab -- RCS ID: $Id: get.lua,v 1.25 2007/03/12 04:08:40 diego Exp $ ----------------------------------------------------------------------------- local socket = require("socket") local http = require("socket.http") local ftp = require("socket.ftp") local url = require("socket.url") local ltn12 = require("ltn12") -- formats a number of seconds into human readable form function nicetime(s) local l = "s" if s > 60 then s = s / 60 l = "m" if s > 60 then s = s / 60 l = "h" if s > 24 then s = s / 24 l = "d" -- hmmm end end end if l == "s" then return string.format("%5.0f%s", s, l) else return string.format("%5.2f%s", s, l) end end -- formats a number of bytes into human readable form function nicesize(b) local l = "B" if b > 1024 then b = b / 1024 l = "KB" if b > 1024 then b = b / 1024 l = "MB" if b > 1024 then b = b / 1024 l = "GB" -- hmmm end end end return string.format("%7.2f%2s", b, l) end -- returns a string with the current state of the download local remaining_s = "%s received, %s/s throughput, %2.0f%% done, %s remaining" local elapsed_s = "%s received, %s/s throughput, %s elapsed " function gauge(got, delta, size) local rate = got / delta if size and size >= 1 then return string.format(remaining_s, nicesize(got), nicesize(rate), 100*got/size, nicetime((size-got)/rate)) else return string.format(elapsed_s, nicesize(got), nicesize(rate), nicetime(delta)) end end -- creates a new instance of a receive_cb that saves to disk -- kind of copied from luasocket's manual callback examples function stats(size) local start = socket.gettime() local last = start local got = 0 return function(chunk) -- elapsed time since start local current = socket.gettime() if chunk then -- total bytes received got = got + string.len(chunk) -- not enough time for estimate if current - last > 1 then io.stderr:write("\r", gauge(got, current - start, size)) io.stderr:flush() last = current end else -- close up io.stderr:write("\r", gauge(got, current - start), "\n") end return chunk end end -- determines the size of a http file function gethttpsize(u) local r, c, h = http.request {method = "HEAD", url = u} if c == 200 then return tonumber(h["content-length"]) end end -- downloads a file using the http protocol function getbyhttp(u, file) local save = ltn12.sink.file(file or io.stdout) -- only print feedback if output is not stdout if file then save = ltn12.sink.chain(stats(gethttpsize(u)), save) end local r, c, h, s = http.request {url = u, sink = save } if c ~= 200 then io.stderr:write(s or c, "\n") end end -- downloads a file using the ftp protocol function getbyftp(u, file) local save = ltn12.sink.file(file or io.stdout) -- only print feedback if output is not stdout -- and we don't know how big the file is if file then save = ltn12.sink.chain(stats(), save) end local gett = url.parse(u) gett.sink = save gett.type = "i" local ret, err = ftp.get(gett) if err then print(err) end end -- determines the scheme function getscheme(u) -- this is an heuristic to solve a common invalid url poblem if not string.find(u, "//") then u = "//" .. u end local parsed = url.parse(u, {scheme = "http"}) return parsed.scheme end -- gets a file either by http or ftp, saving as <name> function get(u, name) local fout = name and io.open(name, "wb") local scheme = getscheme(u) if scheme == "ftp" then getbyftp(u, fout) elseif scheme == "http" then getbyhttp(u, fout) else print("unknown scheme" .. scheme) end end -- main program arg = arg or {} if table.getn(arg) < 1 then io.write("Usage:\n lua get.lua <remote-url> [<local-file>]\n") os.exit(1) else get(arg[1], arg[2]) end
apache-2.0
nasomi/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/Hurr_the_Betrayer.lua
19
3375
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Hurr the Betrayer -- Type: Involved in the "Sahagin Key Quest" -- @zone: 176 -- @pos 305.882 26.768 234.279 -- ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("SahaginKeyItems") == 1) then --If player was told to use 3 Mythril Beastcoins if (trade:hasItemQty(749,3) and trade:hasItemQty(1135,1)) then player:startEvent(0x006b); end elseif (player:getVar("SahaginKeyItems") == 2) then --If player was told to use a Gold Beastcoin if (trade:hasItemQty(748,1) and trade:hasItemQty(1135,1) and trade:getItemCount() == 2) then player:startEvent(0x006b); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("SahaginKeyProgress") == 2 and player:hasItem(1197) == false) then --If player has never before finished the quest player:startEvent(0x0069); player:setVar("SahaginKeyItems",1); elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 0 and player:hasItem(1197) == false) then rand = math.random(2); --Setup random variable to determine which item will be required. if (rand == 1) then player:startEvent(0x0069); --Requires 3 Mythril Beastcoins and a Norg Shell player:setVar("SahaginKeyItems",1); elseif (rand == 2) then player:startEvent(0x006a); --Requires Gold Beastcoin and a Norg Shell player:setVar("SahaginKeyItems",2); end elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 1) then player:startEvent(0x0069); --If player was told to use 3 Mythril Beastcoins elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 2) then player:startEvent(0x006a); --If player was told to use a Gold Beastcoin elseif (player:getVar("SahaginKeyProgress") == 2 and player:hasItem(1197) == true) then player:startEvent(0x0068); --Doesn't offer the key again if the player has one else player:startEvent(0x0068); --Doesn't offer the key if the player hasn't spoken to the first 2 NPCs 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 == 0x006b and player:getVar("SahaginKeyProgress") == 2) then player:tradeComplete(); player:setVar("SahaginKeyProgress",3); --Mark the quest progress player:setVar("SahaginKeyItems",0); player:addItem(1197); -- Sahagin Key player:messageSpecial(ITEM_OBTAINED, 1197); elseif (csid == 0x006b and player:getVar("SahaginKeyProgress") == 3) then player:tradeComplete(); player:setVar("SahaginKeyItems",0); player:addItem(1197); -- Sahagin Key player:messageSpecial(ITEM_OBTAINED, 1197); end end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/metropolis_torso_knife_prim_3.meta.lua
2
2588
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -13, y = 6 }, rotation = -18.434947967529297 }, head = { pos = { x = -1, y = 2 }, rotation = -5 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 56, y = 21 }, rotation = -25 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 17, y = 13 }, rotation = 140.44032287597656 }, shoulder = { pos = { x = 1, y = -17 }, rotation = 180 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
haka-security/haka
src/haka/test/payload.lua
2
1329
-- Basic test that play with function sub, left and right local ipv4 = require('protocol/ipv4' ) haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) pkt.payload:sub(0, 40):setstring("0123456789abcdeABCDE0123456789abcdeABCDE01234567") local left = pkt.payload:sub(0, 50):asstring() print("V=", left) end } haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) pkt.payload:sub(0, 48):setfixedstring("0123456789abcdefghijklmnopqrstuvwxyz0123456789AB") local left = pkt.payload:sub(0, 50):asstring() print("V=", left) end } haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) local substring = pkt.payload:sub(40, 16):asstring() print("V=", substring) end } haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) local right = pkt.payload:sub(48):asstring() print("V=", right) end } haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) pkt.payload:sub(40, 8):erase() local remain = pkt.payload:sub(40, 8):asstring() print("V=", remain) end } haka.rule { on = haka.dissectors.ipv4.events.receive_packet, eval = function (pkt) pkt.payload:sub(0, 40):erase() local remain = pkt.payload:sub(0):asstring() print("V=", remain) end }
mpl-2.0
nasomi/darkstar
scripts/globals/items/yagudo_cherry.lua
35
1200
----------------------------------------- -- ID: 4445 -- Item: yagudo_cherry -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -3 -- Intelligence 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,300,4445); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/plate_of_crab_sushi_+1.lua
35
1377
----------------------------------------- -- ID: 5722 -- Item: plate_of_crab_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Vitality 1 -- Defense 10 -- Accuracy % 13 ----------------------------------------- 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,3600,5722); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 2); target:addMod(MOD_DEF, 15); target:addMod(MOD_FOOD_ACCP, 14); target:addMod(MOD_FOOD_ACC_CAP, 999); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 2); target:delMod(MOD_DEF, 15); target:delMod(MOD_FOOD_ACCP, 14); target:delMod(MOD_FOOD_ACC_CAP, 999); end;
gpl-3.0
fegimanam/zus
plugins/botphoto.lua
6
1239
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end end return { patterns = { "^[!/](setbotphoto)$", "%[(photo)%]" }, run = run, } —Writen By @MostafaEsZ ;) —For recive more Plugins Come Yo @TeamusCh :)
gpl-2.0
nasomi/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fg.lua
34
1106
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Titan's Gate -- @pos 100 -34 -71 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
Hello23-Ygopro/ygopro-ds
expansions/script/c27004118.lua
1
1136
--BT4-105_SPR Temporal Darkness Demigra local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,CHARACTER_DEMIGRA,SPECIAL_TRAIT_DEMON_GOD) ds.AddPlayProcedure(c,COLOR_COLORLESS,0,7) --dark over realm ds.EnableDarkOverRealm(c,7,4) --to warp ds.AddSingleAutoPlay(c,0,nil,scard.twtg,scard.twop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=1 scard.twtg=ds.ChooseCardFunction(PLAYER_PLAYER,ds.BattleAreaFilter(),0,DS_LOCATION_BATTLE,0,1,DS_HINTMSG_TOWARP) function scard.plfilter(c,e) return c:IsBattle() and c:IsEnergyBelow(4) and c:IsCanBeSkillTarget(e) end function scard.twop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToSkill(e) then Duel.SendtoWarp(tc,DS_REASON_SKILL) end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_PLAY) local g=Duel.SelectMatchingCard(tp,ds.TheWarpFilter(scard.plfilter),tp,DS_LOCATION_WARP,0,0,1,nil,e) if g:GetCount()==0 then return end Duel.BreakEffect() Duel.SetTargetCard(g) Duel.Play(g,0,tp,tp,false,false,DS_POS_FACEUP_ACTIVE) end
gpl-3.0
Dayyan1212/mlPet
main.lua
1
9696
vector = require 'vector' bump = require 'bump' function lerp(a,b,t) return (1-t)*a + t*b end function love.gamepadpressed( joystick, button ) press(button) end function love.gamepadreleased( joystick, button ) release(button) end function love.keypressed( key, scancode, isrepeat ) press(key) end function love.keyreleased( key, scancode, isrepeat ) release(key) end GameObject = { velocity = vector(0,0), nextVelocity = vector(0, 0), position = nil, sprite = nil, color = {255, 255, 255}, mass = 0, physical = true, typeID = nil } function GameObject:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function GameObject:draw() love.graphics.setColor(self.color) tiles:add(ascii[self.sprite], math.floor(self.position.x), math.floor(self.position.y)) end function GameObject:update(dt) --make sure no infinite bouncing at some point self.velocity = self.nextVelocity:clone() local actualX, actualY, cols, len = world:move(self, self.position.x + self.velocity.x*dt, self.position.y + self.velocity.y*dt, projectileFilter) for i=1, len do if (cols[i].normal.x < 0 and self.nextVelocity.x > 0) or (cols[i].normal.x > 0 and self.nextVelocity.x < 0) then self.nextVelocity.x = self.nextVelocity.x * -1 end if (cols[i].normal.y < 0 and self.nextVelocity.y > 0) or (cols[i].normal.y > 0 and self.nextVelocity.y < 0) then self.nextVelocity.y = self.nextVelocity.y * -1 end end self.position = vector(actualX, actualY) end Player = GameObject:new({typeID = "player", shield = false, shieldVector = vector(0,0)}) function Player:update(dt) --make sure no infinite bouncing at some point if inputTracker.shield and inputTracker.sRelease == true then self.shield = true inputTracker.sRelease = false else self.shield = false end if inputTracker.curr == "left" then self.shieldVector = vector(-1, 0) elseif inputTracker.curr == "up" then self.shieldVector = vector(0, -1) elseif inputTracker.curr == "right" then self.shieldVector = vector(1, 0) elseif inputTracker.curr == "down" then self.shieldVector = vector(0, 1) end if self.shield then local items, len = world:queryRect(self.position.x+16*self.shieldVector.x,self.position.y+16*self.shieldVector.y, 16, 16, filter) for i=1, len do if items[i].typeID == "projectile" then items[i].nextVelocity = self.shieldVector*(3*dt) end end end self.velocity = self.nextVelocity:clone() self.nextVelocity = vector(0,0) local inputVector = vector(0,0) if inputTracker.up then inputVector.y = inputVector.y-(3*dt) end if inputTracker.down then inputVector.y = inputVector.y+(3*dt) end if inputTracker.left then inputVector.x = inputVector.x-(3*dt) end if inputTracker.right then inputVector.x = inputVector.x+(3*dt) end self.velocity = self.velocity + (inputVector:trimInplace(3)) local actualX, actualY, cols, len = world:move(self, self.position.x + self.velocity.x*dt, self.position.y + self.velocity.y*dt, projectileFilter) --update self.position = vector(actualX, actualY) end function Player:draw() if self.shield then shieldSprite = 0x2B self.shield = false else shieldSprite = 0x0B end love.graphics.setColor(self.color) tiles:add(ascii[self.sprite], math.floor(self.position.x), math.floor(self.position.y)) tiles:add(ascii[shieldSprite], math.floor(self.position.x+(self.shieldVector.x*16)), math.floor(self.position.y+(self.shieldVector.y*16))) end local projectileFilter = function(item, other) if item.typeID == "projectile" and other.typeID == "wall" then return "bounce" elseif item.typeID == "player" and other.typeID == "wall" then return "slide" end end function release(key) if inputMap[key] then inputTracker[inputMap[key]] = false if inputMap[key] == "shield" then inputTracker.sRelease = true end if inputTracker[inputTracker.curr] == false then if inputTracker.left then inputTracker.curr = "left" elseif inputTracker.right then inputTracker.curr = "right" elseif inputTracker.up then inputTracker.curr = "up" elseif inputTracker.down then inputTracker.curr = "down" end end end end function press(key) if inputMap[key] then if inputTracker[inputTracker.curr] == false and (inputMap[key] == "left" or inputMap[key] == "right" or inputMap[key] == "up" or inputMap[key] == "down") then inputTracker.curr = inputMap[key] end inputTracker[inputMap[key]] = true end end function love.run() if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(arg) end -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then if not love.quit or not love.quit() then return a end end love.handlers[name](a,b,c,d,e,f) end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw if love.update then love.update(dt) end -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then love.graphics.clear(love.graphics.getBackgroundColor()) love.graphics.origin() if love.draw then love.draw() end love.graphics.present() end if love.timer then love.timer.sleep(0.001) end end end function love.load() objects = {} spriteSize = 16 love.graphics.setBackgroundColor(0, 0, 0) atlas = love.graphics.newImage("EGA16x16.png") sAtlas = love.graphics.newImage("shield16x16.png") tiles = love.graphics.newSpriteBatch(atlas) ascii = {} angles = {} for i=0, 15 do for j=0, 15 do ascii[(i*16)+j] = love.graphics.newQuad(i*spriteSize, j*spriteSize, spriteSize, spriteSize, atlas:getDimensions()) end end shield = { ["left"] = love.graphics.newQuad(0, 0, spriteSize, spriteSize, sAtlas:getDimensions()), ["up"] = love.graphics.newQuad(spriteSize, 0, spriteSize, spriteSize, sAtlas:getDimensions()), ["down"] = love.graphics.newQuad(0, spriteSize, spriteSize, spriteSize, sAtlas:getDimensions()), ["right"] = love.graphics.newQuad(spriteSize, spriteSize, spriteSize, spriteSize, sAtlas:getDimensions())} player = {["xPos"]=0, ["yPos"]=0, ["xVel"]=0, ["yVel"]=0, ["sprite"] = ascii[0x04]} inputTracker = {["curr"] = "up", ["left"] = false, ["right"] = false, ["up"] = false, ["down"] = false, ["shield"] = false, ["sRelease"] = true} inputMap = {["dpup"] = "up", ["dpdown"] = "down", ["dpleft"] = "left", ["dpright"] = "right", ["w"] = "up", ["a"] = "left", ["s"] = "down", ["d"] = "right", ["j"] = "shield"} sOffsetX = {["left"] = -spriteSize, ["up"] = 0, ["right"] = spriteSize, ["down"] = 0} sOffsetY = {["left"] = 0, ["up"] = -spriteSize, ["right"] = 0, ["down"] = spriteSize} world = bump.newWorld(16) for i = 0, 39 do local a = GameObject:new{sprite = 0x2B, position = vector(16*i, 0), typeID = "wall"} world:add(a, 16*i, 0, 16, 16) table.insert(objects, a) local a = GameObject:new{sprite = 0x2B, position = vector(16*i, 29*16), typeID = "wall"} world:add(a, 16*i, 29*16, 16, 16) table.insert(objects, a) end for i = 1, 28 do local a = GameObject:new{sprite = 0x2B, position = vector(0, 16*i), typeID = "wall"} world:add(a, 0, 16*i, 16, 16) table.insert(objects, a) local a = GameObject:new{sprite = 0x2B, position = vector(39*16, 16*i), typeID = "wall"} world:add(a, 39*16, i*16, 16, 16) table.insert(objects, a) end projectile = GameObject:new{sprite = 0x90, position = vector(100, 100), velocity = vector(2,4), typeID = "projectile", nextVelocity = vector(1, 2), mass = 1} world:add(projectile, projectile.position.x, projectile.position.y, 16, 16) table.insert(objects, projectile) player = Player:new{sprite = 0x04, position = vector(100, 200), typeID = "player"} world:add(player, player.position.x, player.position.y, 16, 16) table.insert(objects, player) end function love.update() dt = love.timer.getDelta()/(1/60) for key,value in pairs(objects) do value:update(dt) end --[[handle inputs if inputTracker.up then player.yVel = player.yVel-(1*dt) end if inputTracker.down then player.yVel = player.yVel+(1*dt) end if inputTracker.left then player.xVel = player.xVel-(1*dt) end if inputTracker.right then player.xVel = player.xVel+(1*dt) end --update player position player.xPos = player.xPos + player.xVel player.yPos = player.yPos + player.yVel --update player.xVel = 0 player.yVel = 0 --]] end function love.draw() for key,value in pairs(objects) do value:draw() end love.graphics.draw(tiles,0,0) tiles:clear() --[[ tiles:add(player.sprite, math.floor(player.xPos), math.floor(player.yPos)) love.graphics.draw(tiles, 0, 0) love.graphics.draw(sAtlas, shield[inputTracker.curr], math.floor(player.xPos+sOffsetX[inputTracker.curr]), math.floor(player.yPos+sOffsetY[inputTracker.curr])) --]] love.graphics.print("FPS: "..tostring(love.timer.getFPS( )), 20, 20) end --[[ function nearestValue(table, number) local smallestSoFar, smallestIndex for i, y in ipairs(table) do if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then smallestSoFar = math.abs(number-y) smallestIndex = i end end return table[smallestIndex] end --]]
mit
kenyh0926/DBProxy
lib/analyze-query.lua
4
12748
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, 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%$ --]] local commands = require("proxy.commands") local tokenizer = require("proxy.tokenizer") local auto_config = require("proxy.auto-config") --- -- configuration -- -- SET GLOBAL analyze_query.auto_filter = 0 if not proxy.global.config.analyze_query then proxy.global.config.analyze_query = { analyze_queries = true, -- track all queries auto_explain = false, -- execute a EXPLAIN on SELECT queries after we logged auto_processlist = false, -- execute a SHOW FULL PROCESSLIST after we logged min_queries = 1000, -- start logging after evaluating 1000 queries min_query_time = 1000, -- don't log queries less then 1ms query_cutoff = 160, -- only show the first 160 chars of the query log_slower_queries = false -- log the query if it is slower than the queries of the same kind } end --- dump the result-set to stdout -- -- @param inj "packet.injection" function resultset_to_string( res ) local s = "" local fields = res.fields if not fields then return "" end local field_count = #fields local row_count = 0 for row in res.rows do local o local cols = {} for i = 1, field_count do if not o then o = "" else o = o .. ", " end if not row[i] then o = o .. "NULL" -- TODO check if the indexes are in range elseif fields[i].type == proxy.MYSQL_TYPE_STRING or fields[i].type == proxy.MYSQL_TYPE_VAR_STRING or fields[i].type == proxy.MYSQL_TYPE_LONG_BLOB or fields[i].type == proxy.MYSQL_TYPE_MEDIUM_BLOB then o = o .. string.format("%q", row[i]) else -- print(" [".. i .."] field-type: " .. fields[i].type) o = o .. row[i] end end s = s .. (" ["..row_count.."]{ " .. o .. " }\n") row_count = row_count + 1 end return s end function math.rolling_avg_init() return { count = 0, value = 0, sum_value = 0 } end function math.rolling_stddev_init() return { count = 0, value = 0, sum_x = 0, sum_x_sqr = 0 } end function math.rolling_avg(val, tbl) tbl.count = tbl.count + 1 tbl.sum_value = tbl.sum_value + val tbl.value = tbl.sum_value / tbl.count return tbl.value end function math.rolling_stddev(val, tbl) tbl.sum_x = tbl.sum_x + val tbl.sum_x_sqr = tbl.sum_x_sqr + (val * val) tbl.count = tbl.count + 1 tbl.value = math.sqrt((tbl.count * tbl.sum_x_sqr - (tbl.sum_x * tbl.sum_x)) / (tbl.count * (tbl.count - 1))) return tbl.value end --- -- init query counters -- -- the normalized queries are if not proxy.global.queries then proxy.global.queries = { } end if not proxy.global.baseline then proxy.global.baseline = { avg = math.rolling_avg_init(), stddev = math.rolling_stddev_init() } end function read_query(packet) local cmd = commands.parse(packet) local r = auto_config.handle(cmd) if r then return r end -- analyzing queries is disabled, just pass them on if not proxy.global.config.analyze_query.analyze_queries then return end -- we only handle normal queries if cmd.type ~= proxy.COM_QUERY then return end tokens = tokenizer.tokenize(cmd.query) norm_query = tokenizer.normalize(tokens) -- create a id for this query query_id = ("%s.%s.%s"):format( proxy.connection.backend_ndx, proxy.connection.client.default_db ~= "" and proxy.connection.client.default_db or "(null)", norm_query) -- handle the internal data if norm_query == "SELECT * FROM `histogram` . `queries` " then proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = { { type = proxy.MYSQL_TYPE_STRING, name = "query" }, { type = proxy.MYSQL_TYPE_LONG, name = "COUNT(*)" }, { type = proxy.MYSQL_TYPE_DOUBLE, name = "AVG(qtime)" }, { type = proxy.MYSQL_TYPE_DOUBLE, name = "STDDEV(qtime)" }, } } } local rows = {} if proxy.global.queries then local cutoff = proxy.global.config.analyze_query.query_cutoff for k, v in pairs(proxy.global.queries) do local q = v.query if cutoff and cutoff < #k then q = k:sub(1, cutoff) .. "..." end rows[#rows + 1] = { q, v.avg.count, string.format("%.2f", v.avg.value), v.stddev.count > 1 and string.format("%.2f", v.stddev.value) or nil } end end proxy.response.resultset.rows = rows return proxy.PROXY_SEND_RESULT elseif norm_query == "DELETE FROM `histogram` . `queries` " then proxy.response = { type = proxy.MYSQLD_PACKET_OK, } proxy.global.queries = {} return proxy.PROXY_SEND_RESULT end -- we are connection-global baseline = nil log_query = false --- -- do we want to analyse this query ? -- -- local queries = proxy.global.queries if not queries[query_id] then queries[query_id] = { db = proxy.connection.client.default_db, query = norm_query, avg = math.rolling_avg_init(), stddev = math.rolling_stddev_init() } end if queries[query_id].do_analyze then -- wrap the query in SHOW SESSION STATUS -- -- note: not used yet proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW SESSION STATUS", { resultset_is_needed = true }) proxy.queries:append(1, packet, { resultset_is_needed = true }) -- FIXME: this should work without it being set (inj.resultset.query_status) proxy.queries:append(3, string.char(proxy.COM_QUERY) .. "SHOW SESSION STATUS", { resultset_is_needed = true }) else proxy.queries:append(1, packet, { resultset_is_needed = true }) -- FIXME: this one too end return proxy.PROXY_SEND_QUERY end --- -- normalize a timestamp into a string -- -- @param ts time in microseconds -- @return a string with a useful suffix function normalize_time(ts) local suffix = "us" if ts > 10000 then ts = ts / 1000 suffix = "ms" end if ts > 10000 then ts = ts / 1000 suffix = "s" end return string.format("%.2f", ts) .. " " .. suffix end function read_query_result(inj) local res = assert(inj.resultset) local config = proxy.global.config.analyze_query if inj.id == 1 then log_query = false if not res.query_status or res.query_status == proxy.MYSQLD_PACKET_ERR then -- the query failed, let's clean the queue -- proxy.queries:reset() end -- get the statistics values for the query local bl = proxy.global.baseline local avg_query_time = math.rolling_avg( inj.query_time, bl.avg) local stddev_query_time = math.rolling_stddev(inj.query_time, bl.stddev) local st = proxy.global.queries[query_id] local q_avg_query_time = math.rolling_avg( inj.query_time, st.avg) local q_stddev_query_time = math.rolling_stddev(inj.query_time, st.stddev) o = "# " .. os.date("%Y-%m-%d %H:%M:%S") .. " [".. proxy.connection.server.thread_id .. "] user: " .. proxy.connection.client.username .. ", db: " .. proxy.connection.client.default_db .. "\n" .. " Query: " .. string.format("%q", inj.query:sub(2)) .. "\n" .. " Norm_Query: " .. string.format("%q", norm_query) .. "\n" .. " query_time: " .. normalize_time(inj.query_time) .. "\n" .. " global(avg_query_time): " .. normalize_time(avg_query_time) .. "\n" .. " global(stddev_query_time): " .. normalize_time(stddev_query_time) .. "\n" .. " global(count): " .. bl.avg.count .. "\n" .. " query(avg_query_time): " .. normalize_time(q_avg_query_time) .. "\n" .. " query(stddev_query_time): " .. normalize_time(q_stddev_query_time) .. "\n" .. " query(count): " .. st.avg.count .. "\n" -- we need a min-query-time to filter out if inj.query_time >= config.min_query_time then -- this query is slower than 95% of the average if bl.avg.count > config.min_queries and inj.query_time > avg_query_time + 5 * stddev_query_time then o = o .. " (qtime > global-threshold)\n" log_query = true end -- this query was slower than 95% of its kind if config.log_slower_queries and st.avg.count > config.min_queries and inj.query_time > q_avg_query_time + 5 * q_stddev_query_time then o = o .. " (qtime > query-threshold)\n" log_query = true end end if log_query and config.auto_processlist then proxy.queries:append(4, string.char(proxy.COM_QUERY) .. "SHOW FULL PROCESSLIST", { resultset_is_needed = true }) end if log_query and config.auto_explain then if tokens[1] and tokens[1].token_name == "TK_SQL_SELECT" then proxy.queries:append(5, string.char(proxy.COM_QUERY) .. "EXPLAIN " .. inj.query:sub(2), { resultset_is_needed = true }) end end elseif inj.id == 2 then -- the first SHOW SESSION STATUS baseline = {} for row in res.rows do -- 1 is the key, 2 is the value baseline[row[1]] = row[2] end elseif inj.id == 3 then local delta_counters = { } for row in res.rows do if baseline[row[1]] then local num1 = tonumber(baseline[row[1]]) local num2 = tonumber(row[2]) if row[1] == "Com_show_status" then num2 = num2 - 1 elseif row[1] == "Questions" then num2 = num2 - 1 elseif row[1] == "Last_query_cost" then num1 = 0 end if num1 and num2 and num2 - num1 > 0 then delta_counters[row[1]] = (num2 - num1) end end end baseline = nil --- filter data -- -- we want to see queries which -- - trigger a tmp-disk-tables -- - are slower than the average -- if delta_counters["Created_tmp_disk_tables"] then log_query = true end if log_query then for k, v in pairs(delta_counters) do o = o .. ".. " .. row[1] .. " = " .. (num2 - num1) .. "\n" end end elseif inj.id == 4 then -- dump the full result-set to stdout o = o .. "SHOW FULL PROCESSLIST\n" o = o .. resultset_to_string(inj.resultset) elseif inj.id == 5 then -- dump the full result-set to stdout o = o .. "EXPLAIN <query>\n" o = o .. resultset_to_string(inj.resultset) end if log_query and proxy.queries:len() == 0 then print(o) o = nil log_query = false end -- drop all resultsets but the original one if inj.id ~= 1 then return proxy.PROXY_IGNORE_RESULT end end
gpl-2.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/resistance_torso_knife_prim_2.meta.lua
2
2781
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.40000000596046448, amplification = 100, light_colors = { "223 113 38 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -16, y = 0 }, rotation = 7.3057599067687988 }, head = { pos = { x = -2, y = 1 }, rotation = -3 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 46, y = 30 }, rotation = -25 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 7, y = 20 }, rotation = 175.48602294921875 }, shoulder = { pos = { x = 8, y = -18 }, rotation = -175.91438293457031 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Nelarius/wren
test/benchmark/method_call.lua
13
2269
-- $Id: methcall.lua,v 1.2 2004-06-12 16:19:43 bfulgham Exp $ -- http://shootout.alioth.debian.org -- contributed by Roberto Ierusalimschy -------------------------------------------------------------- -- Toggle class -------------------------------------------------------------- Toggle = {} function Toggle:value () return self.state end function Toggle:activate () self.state = not self.state return self end function Toggle:new (start_state) local o = {state = start_state} self.__index =self setmetatable(o, self) return o end -------------------------------------------------------------- -- NthToggle class -------------------------------------------------------------- NthToggle = Toggle:new() function NthToggle:activate () self.counter = self.counter + 1 if self.counter >= self.count_max then Toggle.activate(self) self.counter = 0 end return self end function NthToggle:new (start_state, max_counter) local o = Toggle.new(self, start_state) o.count_max = max_counter o.counter = 0 return o end ----------------------------------------------------------- -- main ----------------------------------------------------------- function main () local start = os.clock() local N = 100000 local val = 1 local toggle = Toggle:new(val) for i=1,N do val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() val = toggle:activate():value() end print(val and "true" or "false") val = 1 local ntoggle = NthToggle:new(val, 3) for i=1,N do val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() val = ntoggle:activate():value() end print(val and "true" or "false") io.write(string.format("elapsed: %.8f\n", os.clock() - start)) end main()
mit
luanorlandi/SwiftSpaceBattle
src/ship/ship.lua
2
8700
require "shot/shot" require "effect/blend" require "effect/explosion" require "ship/player" require "ship/enemies" require "ship/enemyType1" require "ship/enemyType2" require "ship/enemyType3" require "ship/enemyType4" require "ship/enemyType5" local muzzleflashSize = Vector:new(10 * window.scale, 10 * window.scale) local muzzleflash = MOAIGfxQuad2D.new() muzzleflash:setTexture("texture/effect/muzzleflash.png") muzzleflash:setRect(-muzzleflashSize.x, -muzzleflashSize.y, muzzleflashSize.x, muzzleflashSize.y) -- Ship ------------------------------ Ship = {} Ship.__index = Ship function Ship:new(deck, pos) local S = {} setmetatable(S, Ship) S.name = "Ship" S.type = 0 S.sprite = MOAIProp2D.new() changePriority(S.sprite, "ship") S.sprite:setDeck(deck) S.deck = deck S.deckDmg = deck S.hp = 100 S.maxHp = 100 S.dmgLast = gameTime -- last time that receive damage S.regenRate = 20 -- hp regeneration per second S.regenCd = 2.5 -- cooldown to start regenerating hp S.status = "alive" S.pos = pos S.spd = Vector:new(0, 0) S.acc = Vector:new(0, 0) S.maxAcc = 0.1 * window.scale S.dec = S.maxAcc / 3 S.maxSpd = 2 * window.scale S.minSpd = S.maxAcc / 5 S.area = Area:new(Vector:new(0, 0)) S.shotType = ShotLaserBlue S.shotSpd = 8 * window.scale S.fireLast = gameTime S.fireRate = 0.4 S.aim = Vector:new(0, 1) S.wpn = {} -- positions of where the shots appear S.flaDuration = 0.08 S.fla = {} -- positions of where the muzzle flashs appear S.spawning = true S.spawned = true S.spawnTime = gameTime S.spawnDuration = 1 S.destroy = false S.expType = ExplosionType1 S.expDuration = 0.8 S.score = 100 S.rot = S.sprite:moveRot(0, 0.1) -- table with the threads created by the object, so can be resumed S.threads = {} -- table with the sprites created by the threads, so can be removed S.threadsSprites = {} S.sprite:setLoc(S.pos.x, S.pos.y) window.layer:insertProp(S.sprite) return S end function Ship:move() -- define acceleration if self.acc.x == 0 and self.spd.x > 0 then self.acc.x = -self.dec end if self.acc.x == 0 and self.spd.x < 0 then self.acc.x = self.dec end if self.acc.y == 0 and self.spd.y > 0 then self.acc.y = -self.dec end if self.acc.y == 0 and self.spd.y < 0 then self.acc.y = self.dec end -- check if exceed maximum acceleration if self.acc:norm() > self.maxAcc then self.acc:normalize() self.acc.x = self.acc.x * self.maxAcc self.acc.y = self.acc.y * self.maxAcc end -- define speed self.spd:sum(self.acc) -- check if speed is almost zero if self.spd.x < self.minSpd and self.spd.x > -self.minSpd then self.spd.x = 0 end if self.spd.y < self.minSpd and self.spd.y > -self.minSpd then self.spd.y = 0 end -- check if exceed maximum speed if self.spd:norm() > self.maxSpd then self.spd:normalize() self.spd.x = self.spd.x * self.maxSpd self.spd.y = self.spd.y * self.maxSpd end -- define position self.pos:sum(self.spd) -- check if exceed the window size Ship.moveLimit(self) self.sprite:setLoc(self.pos.x, self.pos.y) end function Ship:moveLimit() -- fix ship position if self.pos.x > window.width/2 - self.area.size.size.x then self.pos.x = window.width/2 - self.area.size.size.x self.spd.x = 0 elseif self.pos.x < -window.width/2 + self.area.size.size.x then self.pos.x = -window.width/2 + self.area.size.size.x self.spd.x = 0 end end function Ship:shoot(shots) if not self.rot:isActive() and not self.spawning and self.spawned and gameTime - self.fireLast >= self.fireRate then for i = 1, #self.wpn, 1 do Ship.newShot(self, shots, self.wpn[i]) end local muzzleflashThread = coroutine.create(function() self:muzzleflash() end) coroutine.resume(muzzleflashThread) table.insert(self.threads, muzzleflashThread) self.fireLast = gameTime end end function Ship:newShot(shots, pos) local shot = self.shotType:new(Vector:new(self.pos.x + pos.x, self.pos.y + self.aim.y * pos.y)) shot.spd.x = self.aim.x * self.shotSpd shot.spd.y = self.aim.y * self.shotSpd table.insert(shots, shot) end function Ship:destroy() -- remove ship sprite window.layer:removeProp(self.sprite) -- remove all sprite effects created by his threads for i = 1, #self.threadsSprites, 1 do window.layer:removeProp(self.threadsSprites[1]) table.remove(self.threadsSprites, 1) end if self.name == "Player" then end end function Ship:spawnSize() self.sprite:moveScl(-1, -1, 0) local resizing = self.sprite:moveScl(1, 1, self.spawnDuration) while resizing:isActive() do coroutine.yield() end self.spawning = false end function Ship:damaged(dmg) -- receive a damage, create a animation effect for the hit self.hp = self.hp - dmg self.dmgLast = gameTime local damageThread = coroutine.create(function() self.sprite:setDeck(self.deckDmg) for i = 0, dmg, 20 do coroutine.yield() end self.sprite:setDeck(self.deck) end) table.insert(self.threads, damageThread) if self.hp <= 0 then self.status = "dead" end end function Ship:explode() self.spawned = false self.sprite:moveScl(-1, -1, self.expDuration/2) local explosion = self.expType:new(Vector:new(self.pos.x, self.pos.y), self.expDuration) table.insert(self.threadsSprites, explosion) explosion.anim:start() while explosion.anim:isActive() do coroutine.yield() end window.layer:removeProp(explosion.sprite) self.destroy = true end function Ship:muzzleflashType1() local mf = {} for i = 1, #self.fla, 1 do local flash = MOAIProp2D.new() changePriority(flash, "effect") table.insert(self.threadsSprites, flash) flash:setDeck(muzzleflash) flash:setLoc(self.pos.x + self.fla[i].x, self.pos.y + self.aim.y * self.fla[i].y) flash:moveScl(-1, -1, self.flaDuration) window.layer:insertProp(flash) table.insert(mf, flash) end local start = gameTime while gameTime - start < self.flaDuration do coroutine.yield() for i = 1, #mf, 1 do mf[i]:setLoc(self.pos.x + self.fla[i].x, self.pos.y + self.aim.y * self.fla[i].y) end end while #mf ~= 0 do window.layer:removeProp(mf[1]) table.remove(mf, 1) end end function Ship:muzzleflashType2(deck) local flash = MOAIProp2D.new() changePriority(flash, "effect") table.insert(self.threadsSprites, flash) flash:setDeck(deck) flash:setLoc(self.pos.x, self.pos.y) if self.aim.y < 0 then flash:moveRot(180, 0) end local blendThread = coroutine.create(function() blendOut(flash, self.flaDuration) end) coroutine.resume(blendThread) window.layer:insertProp(flash) local start = gameTime while gameTime - start < self.flaDuration and coroutine.status(blendThread) ~= "dead" do coroutine.yield() coroutine.resume(blendThread) flash:setLoc(self.pos.x, self.pos.y) end window.layer:removeProp(flash) end function Ship:hpRegen() local lastRegen = gameTime while self.status ~= "dead" do coroutine.yield() if gameTime > self.dmgLast + self.regenCd and self.hp < self.maxHp then local hpHeal = self.regenRate * (gameTime - lastRegen) self.hp = self.hp + hpHeal if self.hp > self.maxHp then -- check for overheal self.hp = self.maxHp end end lastRegen = gameTime end end function newEnemy(type, pos) table.insert(enemies, type:new(pos)) end function shipsMove() player:move() for i = 1, #enemies, 1 do enemies[i]:move() end end function enemiesShoot() for i = 1, #enemies, 1 do enemies[i]:shoot() end end function shipsCheckStatus() -- check if the player died if player.status == "dead" then if player.spawned then local explodeThread = coroutine.create(function() Ship.explode(player) end) table.insert(player.threads, explodeThread) end end -- check if an enemy died local e = 1 while e <= #enemies do local ship = enemies[e] if ship.status ~= "dead" then e = e + 1 else table.remove(enemies, e) table.insert(deadShips, ship) playerData:scoreEnemy(ship.score, ship.pos) spawner:decrease(ship.type, ship.pos.y) local explodeThread = coroutine.create(function() Ship.explode(ship) end) table.insert(ship.threads, explodeThread) end end -- check if the player exploded if player.destroy then Ship.destroy(player) playerData:dead() end -- check if any enemy dead has exploded local d = 1 while d <= #deadShips do local ship = deadShips[d] if ship.destroy then Ship.destroy(ship) table.remove(deadShips, d) else d = d + 1 end end end function shipsClear() Ship.destroy(player) for i = 1, #enemies, 1 do Ship.destroy(enemies[1]) table.remove(enemies, 1) end for i = 1, #deadShips, 1 do Ship.destroy(deadShips[1]) table.remove(deadShips, 1) end end
gpl-3.0
elihugarret/Xquic
uj.lua
1
1372
ix = Rx.CooperativeScheduler.create() local _prog = prog() local beat = x.new{ 0, 2, 2, 3, {0, 1}, 2, 2, _, 0, 4, _, 2, {0, 1}, _, 3, _, 0, _, 2, _, {0, 1}, 2, _, 3, 0, 6, 4, _, {0, 1}, 3, 2, 6, 0, 2, _, 2, {0, 1}, _, 3, 2, 0, _, 2, 4, {0, 1}, 2, 2, _, 0, 2, 2, _, {0, 1}, 3, _, 2, 0, 2, _, _, {0, 1}, 2, 2, _, } --:replace({0}, {2}) local synth = x.new{ 0, 7, _, _, {0, 3, 12}, _, 7, 3, 0, 7, 7, 3, 0, _, 7, _, 0, 3, 7, 12, 0, _, _, 2, _, _, 7, _, _, 7, 7, _, 0, 3, _, _, {0, 2, 12}, 7, 7, _, 0, _, 7, _, _, _, 7, _, 0, _, 7, _, 0, _, 7, 7, 0, 2, 7, _, 0, 12, _, 7, } local piano = x.new{ 0, _, 0, _, {0, 3, 7}, _, 2, 0, 5, 0, _, _, 0, 2, _, _, 0, _, 0, _, {0, 3, 7}, _, 2, 0, 5, 0, 12, _, 0, 2, 12, _, 0, _, 0, _, {0, 5, 7}, _, _, 0, _, 0, 12, _, 12, _, 12, _, {0, 3, 7}, _, _, _, {0, 5, 7}, _, _, _, {-2, 3}, _, _, _, {-2, 3, 12}, _, _, _, }--:fill() beat.channel = 4 beat.root = 48 synth.channel = 2 synth.root = 60 + _prog piano.channel = 0 piano.root = 60 + _prog ix:schedule(function () beat:play() end, timer_resolution) ix:schedule(function () synth:play() end, timer_resolution) ix:schedule(function () piano:play() end, timer_resolution) repeat ix:update(timer_resolution) if ix.currentTime > 64/16 then break end x.sleep(1/8) until false --os.exit()
mit
nasomi/darkstar
scripts/globals/mobskills/Thundris_Shriek.lua
13
1405
--------------------------------------------- -- Thundris Shriek -- -- Description: Deals heavy lightning damage to targets in area of effect. Additional effect: Terror -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown -- Notes: Players will begin to be intimidated by the dvergr after this attack. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1840) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 15); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_THUNDER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nicholas-leonard/nn
Squeeze.lua
20
1316
local Squeeze, parent = torch.class('nn.Squeeze', 'nn.Module') function Squeeze:__init(dim, numInputDims) parent.__init(self) self.dim = dim self:setNumInputDims(numInputDims) end function Squeeze:setNumInputDims(numInputDims) self.numInputDims = numInputDims return self end function Squeeze:updateOutput(input) assert(input and torch.isTensor(input), 'Squeeze only works on tensors') local dim = self.dim local addone = false if self.numInputDims and input:dim()==(self.numInputDims+1) then if dim then dim = dim + 1 elseif input:size(1) == 1 then addone = true -- in case of minibatch of size 1. end end self.output:set(dim and input:squeeze(dim) or input:squeeze()) if addone then local s = self.output:size():totable{} table.insert(s, 1, 1) self.output:set(self.output:view(torch.LongStorage(s))) end return self.output end function Squeeze:updateGradInput(input, gradOutput) assert(input and torch.isTensor(input), 'Squeeze only works on tensors') assert(gradOutput and torch.isTensor(gradOutput), 'Squeeze only works on tensors') assert(input:nElement() == gradOutput:nElement()) self.gradInput:set(gradOutput:view(input:size())) return self.gradInput end
bsd-3-clause
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Khoi_Gamduhla.lua
34
1038
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Khoi Gamduhla -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x034F); 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
coolflyreg/gs
server/lualib/servers/gameserver.lua
1
3314
local skynet = require "skynet" local gateserver = require "servers.gateserver" local syslog = require "syslog" local protoloader = require "protoloader" local gameserver_handler = require "agent.gameserver_handler" local md5 = require "md5" require("framework") local sessiond skynet.init(function() sessiond = skynet.uniqueservice("sessiond") end) ----------------------------------------------------- local REQUEST = {} local RESPONSE = {} gameserver_handler:register({ REQUEST = REQUEST, RESPONSE = RESPONSE }) ----------------------------------------------------- local gameserver = {} local pending_msg = {} function gameserver.forward (fd, agent) gateserver.forward (fd, agent) end function gameserver.kick (fd) gateserver.close_client (fd) end function gameserver.start (gamed) local handler = {} local host, send_request = protoloader.load (protoloader.LOGIN) function handler.open (source, conf) return gamed.open (conf) end function handler.connect (fd, addr) syslog.noticef ("connect from %s (fd = %d)", addr, fd) gateserver.open_client (fd) end function handler.disconnect (fd) syslog.noticef ("fd (%d) disconnected", fd) end local function do_login (fd, msg, sz) local type, name, args, response, err_response = host:dispatch (msg, sz) assert (type == "REQUEST") -- assert (name == "gameserver_login") -- assert (args.username and args.serverId) -- local session = md5String(md5.sum(args.username.."-"..args.serverId))--tonumber (args.session) or error () -- local account = gamed.auth (session, args.token) or error () -- assert (account) -- return account local f = REQUEST[name] if (f) then -- profile.start() local result = f(args) -- local time = profile.stop() -- log.debugf("Cost %s seconds", time) if result.errno then -- local msg = err_response(result) -- send_msg(fd, msg) error() else -- local msg = response(result) -- send_msg(fd, msg) return result end end end local traceback = debug.traceback function handler.message (fd, msg, sz) local queue = pending_msg[fd] if queue then table.insert (queue, { msg = msg, sz = sz }) else pending_msg[fd] = {} local ok, login_result = xpcall (do_login, traceback, fd, msg, sz) if ok then syslog.noticef ("account %d login success", login_result.uid) local agent = gamed.login (fd, login_result) queue = pending_msg[fd] for _, t in pairs (queue) do syslog.noticef ("forward pending message to agent %d", agent) skynet.rawcall(agent, "client", t.msg, t.sz) end else syslog.warningf ("%s login failed : %s", addr, account) gateserver.close_client (fd) end pending_msg[fd] = nil end end local CMD = {} function CMD.token (id, secret) local id = tonumber (id) login_token[id] = secret skynet.timeout (10 * 100, function () if login_token[id] == secret then syslog.noticef ("account %d token timeout", id) login_token[id] = nil end end) end function handler.command (cmd, ...) local f = CMD[cmd] if f then return f (...) else return gamed.command_handler (cmd, ...) end end return gateserver.start (handler) end return gameserver
gpl-2.0
nasomi/darkstar
scripts/zones/Fort_Ghelsba/Zone.lua
28
1666
----------------------------------- -- -- Zone: Fort_Ghelsba (141) -- ----------------------------------- package.loaded["scripts/zones/Fort_Ghelsba/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Fort_Ghelsba/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) UpdateTreasureSpawnPoint(17355008); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(219.949,-86.032,19.489,128); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
nasomi/darkstar
scripts/zones/San_dOria-Jeuno_Airship/npcs/Nigel.lua
19
2055
----------------------------------- -- Area: San d'Oria-Jeuno Airship -- NPC: Nigel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/San_dOria-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/San_dOria-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 3 do vHour = vHour - 6; end local message = WILL_REACH_SANDORIA; if (vHour == -3) then if (vMin >= 10) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -2) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -1) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == 0) then if (vMin <= 11) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == 1) then vHour = 2; elseif (vHour == 2) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 11 - vMin; else -- WILL_REACH_SANDORIA vMinutes = (vHour * 60) + 10 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_SANDORIA) then message = IN_SANDORIA_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); 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
Hello23-Ygopro/ygopro-ds
expansions/script/c27001110.lua
1
1381
--BT1-095 Elite Force Captain Ginyu local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,SPECIAL_TRAIT_GINYU_FORCE,CHARACTER_GINYU) ds.AddPlayProcedure(c,COLOR_YELLOW,3,3) --give skill ds.AddSingleAutoPlay(c,0,nil,scard.sktg,scard.skop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.skfilter(c) return c:IsSpecialTrait(SPECIAL_TRAIT_GINYU_FORCE) end function scard.sktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(DS_LOCATION_BATTLE) and chkc:IsControler(tp) and ds.BattleAreaFilter(scard.skfilter)(chkc) end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) local ct=Duel.GetMatchingGroupCount(ds.BattleAreaFilter(scard.skfilter),tp,DS_LOCATION_BATTLE,0,nil) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TARGET) Duel.SelectTarget(tp,ds.BattleAreaFilter(scard.skfilter),tp,DS_LOCATION_BATTLE,0,ct,ct,nil) end function scard.skop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) if not g then return end local sg=g:Filter(Card.IsRelateToSkill,nil,e) local c=e:GetHandler() for tc in aux.Next(sg) do --power up ds.GainSkillUpdatePower(c,tc,1,10000) --double strike ds.GainSkillDoubleStrike(c,tc,2) end end
gpl-3.0
nasomi/darkstar
scripts/globals/magiantrials.lua
33
9671
------------------------------------------- -- Magian trial functions, vars, tables ------------------------------------------- ----------------------------------- -- getTrialInfo ----------------------------------- -- once fully filled out, these info tables might get large enough to need their own file, we'll see... function getTrialInfo(ItemID) local TrialInfo = {}; if (ItemID == 19327) then -- Pugilists TrialInfo.t1 = 68; TrialInfo.t2 = 82; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19332) then -- Peeler TrialInfo.t1 = 2; TrialInfo.t2 = 16; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19337) then -- Side-sword TrialInfo.t1 = 150; TrialInfo.t2 = 164; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19342) then -- Break Blade TrialInfo.t1 = 216; TrialInfo.t2 = 230; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19347) then -- Chopper TrialInfo.t1 = 282; TrialInfo.t2 = 296; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19352) then -- Lumberjack TrialInfo.t1 = 364; TrialInfo.t2 = 378; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19357) then -- Farmhand TrialInfo.t1 = 512; TrialInfo.t2 = 526; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19362) then -- Ranseur TrialInfo.t1 = 430; TrialInfo.t2 = 444; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19367) then -- KibaShiri TrialInfo.t1 = 578; TrialInfo.t2 = 592; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19372) then -- Donto TrialInfo.t1 = 644; TrialInfo.t2 = 658; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19377) then -- Stenz TrialInfo.t1 = 710; TrialInfo.t2 = 724; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19382) then -- Crook TrialInfo.t1 = 776; TrialInfo.t2 = 790; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19387) then -- Sparrow TrialInfo.t1 = 0; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 19392) then -- Thunderstick TrialInfo.t1 = 941; TrialInfo.t2 = 891; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; -- elsif -- else -- Not a valid Item, return zeros for all. TrialInfo.t1 = 0; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; end end; ----------------------------------- -- getEmoteTrialInfo ----------------------------------- function getEmoteTrialInfo(ItemID) local TrialInfo = {}; if (ItemID == 11988) then -- Fighter's Torque TrialInfo.t1 = 4424; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11989) then -- Temple Torque TrialInfo.t1 = 4425; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11990) then -- Healer's Torque TrialInfo.t1 = 4426; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11991) then -- Wizard's Torque TrialInfo.t1 = 4427; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11992) then -- Warlock's Torque TrialInfo.t1 = 4428; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11993) then -- Rogue's Torque TrialInfo.t1 = 4429; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11994) then -- Gallant Torque TrialInfo.t1 = 4430; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11995) then -- Chaos Torque TrialInfo.t1 = 4431; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11996) then -- Beast Torque TrialInfo.t1 = 4432; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11997) then -- Choral Torque TrialInfo.t1 = 4433; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11998) then -- Hunter's Torque TrialInfo.t1 = 4434; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 11999) then -- Myochin Shusa TrialInfo.t1 = 4435; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12000) then -- Ninja Shusa TrialInfo.t1 = 4436; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12001) then -- Drachen Torque TrialInfo.t1 = 4437; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12002) then -- Evoker's Torque TrialInfo.t1 = 4438; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12003) then -- Magus Torque TrialInfo.t1 = 4439; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12004) then -- Corsair's Torque TrialInfo.t1 = 4440; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12005) then -- Puppetry Torque TrialInfo.t1 = 4441; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12006) then -- Dancer's Torque TrialInfo.t1 = 4442; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; elseif (ItemID == 12007) then -- Scholar's Torque TrialInfo.t1 = 4443; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; else -- Not a valid Item, return zeros for all. TrialInfo.t1 = 0; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; end end; ----------------------------------- -- getRelicTrialInfo ----------------------------------- function getRelicTrialInfo(ItemID) local TrialInfo = {}; if (ItemID == 19327) then -- TrialInfo.t1 = 0; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; else -- Not a valid Item, return zeros for all. TrialInfo.t1 = 0; TrialInfo.t2 = 0; TrialInfo.t3 = 0; TrialInfo.t4 = 0; return TrialInfo; end end; ----------------------------------- -- magianOrangeEventUpdate ----------------------------------- function magianOrangeEventUpdate(player,ItemID,csid,option) -- DO NOT try to convert into "elseif" ! -- Probably need to table all this too, for now I'm just mapping it out. if (csid == 10124 and option == 4456449) then local ReqItemAugFlag = 2; -- 2 = ON, anything else = OFF. local ReqItemAug1 = 1; local ReqItemAug2 = 1; local ReqItem = 19332; local TrialID = 9; player:updateEvent(ReqItemAugFlag, ReqItemAug1, ReqItemAug2, ReqItem, 0, 0, TrialID); end if (csid == 10124 and option == 4456450) then local TotalObjectives = 11; player:updateEvent(TotalObjectives); end if (csid == 10124 and option == 4456451) then local RewardAugFlag = 2; -- 2 = ON, anything else = OFF. local RewardAug1 = 1; local RewardAug2 = 1; local RewardItem = 19328; player:updateEvent(RewardAugFlag, RewardAug1, RewardAug2, RewardItem); end if (csid == 10124 and option == 4456452) then local ResultTrial1 = 69; local ResultTrial2 = 0; local ResultTrial3 = 0; local ResultTrial4 = 0; local PrevTrial = 0; player:updateEvent(ResultTrial1, ResultTrial2, ResultTrial3, ResultTrial4, PrevTrial); end end; ----------------------------------- -- magianGreenEventUpdate ----------------------------------- function magianGreenEventUpdate(player,ItemID,csid,option) end; ----------------------------------- -- magianBlueEventUpdate ----------------------------------- function magianBlueEventUpdate(player,ItemID,csid,option) end;
gpl-3.0
thesabbir/luci
applications/luci-app-radvd/luasrc/model/cbi/radvd/rdnss.lua
61
2115
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - RDNSS"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "rdnss" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("RDNSS Configuration")) s.addremove = false -- -- General -- o = s:option(Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:option(Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:option(DynamicList, "addr", translate("Addresses"), translate("Advertised IPv6 RDNSS. If empty, the current IPv6 address of the interface is used")) o.optional = false o.rmempty = true o.datatype = "ip6addr" o.placeholder = translate("default") function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "addr") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:option(Value, "AdvRDNSSLifetime", translate("Lifetime"), translate("Specifies the maximum duration how long the RDNSS entries are used for name resolution.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 1200 return m
apache-2.0
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/_1ee.lua
34
1045
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Door: Kokba Hostel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(0x0046); 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
coolflyreg/gs
server/lualib/agent/socials_handler.lua
1
1185
local skynet = require("skynet") local handler = require("agent.handler") local errorcode = require("protocols.errorcode") local validator = require("protocols.validator") local databases = require("db.databases") local REQUEST = {} handler = handler.new(REQUEST) function REQUEST.social_all() error("<Request.social_all> Not Implemented") end function REQUEST.social_searchFriend(args) error("<Request.social_searchFriend> Not Implemented") end function REQUEST.social_connect(args) error("<Request.social_connect> Not Implemented") end function REQUEST.social_disconnect(args) error("<Request.social_disconnect> Not Implemented") end function REQUEST.social_combatReport(args) error("<Request.social_combatReport> Not Implemented") end function REQUEST.social_chatList(args) error("<Request.social_chatList> Not Implemented") end function REQUEST.social_chatSend(args) error("<Request.social_chatSend> Not Implemented") end function REQUEST.social_friendRequest(args) error("<Request.social_friendRequest> Not Implemented") end function REQUEST.social_playerPK(args) error("<Request.social_playerPK> Not Implemented") end return handler
gpl-2.0
appaquet/torch-android
src/3rdparty/nn/Euclidean.lua
17
5685
local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module') function Euclidean:__init(inputSize,outputSize) parent.__init(self) self.weight = torch.Tensor(inputSize,outputSize) self.gradWeight = torch.Tensor(inputSize,outputSize) -- state self.gradInput:resize(inputSize) self.output:resize(outputSize) self.fastBackward = true self:reset() end function Euclidean:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(1)) end if nn.oldSeed then for i=1,self.weight:size(2) do self.weight:select(2, i):apply(function() return torch.uniform(-stdv, stdv) end) end else self.weight:uniform(-stdv, stdv) end end local function view(res, src, ...) local args = {...} if src:isContiguous() then res:view(src, table.unpack(args)) else res:reshape(src, table.unpack(args)) end end function Euclidean:updateOutput(input) -- lazy initialize buffers self._input = self._input or input.new() self._weight = self._weight or self.weight.new() self._expand = self._expand or self.output.new() self._expand2 = self._expand2 or self.output.new() self._repeat = self._repeat or self.output.new() self._repeat2 = self._repeat2 or self.output.new() local inputSize, outputSize = self.weight:size(1), self.weight:size(2) -- y_j = || w_j - x || = || x - w_j || if input:dim() == 1 then view(self._input, input, inputSize, 1) self._expand:expandAs(self._input, self.weight) self._repeat:resizeAs(self._expand):copy(self._expand) self._repeat:add(-1, self.weight) self.output:norm(self._repeat, 2, 1) self.output:resize(outputSize) elseif input:dim() == 2 then local batchSize = input:size(1) view(self._input, input, batchSize, inputSize, 1) self._expand:expand(self._input, batchSize, inputSize, outputSize) -- make the expanded tensor contiguous (requires lots of memory) self._repeat:resizeAs(self._expand):copy(self._expand) self._weight:view(self.weight, 1, inputSize, outputSize) self._expand2:expandAs(self._weight, self._repeat) if torch.type(input) == 'torch.CudaTensor' then -- requires lots of memory, but minimizes cudaMallocs and loops self._repeat2:resizeAs(self._expand2):copy(self._expand2) self._repeat:add(-1, self._repeat2) else self._repeat:add(-1, self._expand2) end self.output:norm(self._repeat, 2, 2) self.output:resize(batchSize, outputSize) else error"1D or 2D input expected" end return self.output end function Euclidean:updateGradInput(input, gradOutput) if not self.gradInput then return end self._div = self._div or input.new() self._output = self._output or self.output.new() self._gradOutput = self._gradOutput or input.new() self._expand3 = self._expand3 or input.new() if not self.fastBackward then self:updateOutput(input) end local inputSize, outputSize = self.weight:size(1), self.weight:size(2) --[[ dy_j -2 * (w_j - x) x - w_j ---- = --------------- = ------- dx 2 || w_j - x || y_j --]] -- to prevent div by zero (NaN) bugs self._output:resizeAs(self.output):copy(self.output):add(0.0000001) view(self._gradOutput, gradOutput, gradOutput:size()) self._div:cdiv(gradOutput, self._output) if input:dim() == 1 then self._div:resize(1, outputSize) self._expand3:expandAs(self._div, self.weight) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand3):copy(self._expand3) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand3) end self.gradInput:sum(self._repeat2, 2) self.gradInput:resizeAs(input) elseif input:dim() == 2 then local batchSize = input:size(1) self._div:resize(batchSize, 1, outputSize) self._expand3:expand(self._div, batchSize, inputSize, outputSize) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand3):copy(self._expand3) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand3) end self.gradInput:sum(self._repeat2, 3) self.gradInput:resizeAs(input) else error"1D or 2D input expected" end return self.gradInput end function Euclidean:accGradParameters(input, gradOutput, scale) local inputSize, outputSize = self.weight:size(1), self.weight:size(2) scale = scale or 1 --[[ dy_j 2 * (w_j - x) w_j - x ---- = --------------- = ------- dw_j 2 || w_j - x || y_j --]] -- assumes a preceding call to updateGradInput if input:dim() == 1 then self.gradWeight:add(-scale, self._repeat2) elseif input:dim() == 2 then self._sum = self._sum or input.new() self._sum:sum(self._repeat2, 1) self._sum:resize(inputSize, outputSize) self.gradWeight:add(-scale, self._sum) else error"1D or 2D input expected" end end function Euclidean:type(type) if type then -- prevent premature memory allocations self._input = nil self._output = nil self._gradOutput = nil self._weight = nil self._div = nil self._sum = nil self._expand = nil self._expand2 = nil self._expand3 = nil self._repeat = nil self._repeat2 = nil end return parent.type(self, type) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Jugner_Forest/npcs/Chaplion_RK.lua
28
3127
----------------------------------- -- Area: Jugner Forest -- NPC: Chaplion, R.K. -- Outpost Conquest Guards -- @pos 54 0 -11 104 ------------------------------------- package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Jugner_Forest/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = NORVALLEN; local 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 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
EnjoyHacking/nn
MultiCriterion.lua
26
1170
local MultiCriterion, parent = torch.class('nn.MultiCriterion', 'nn.Criterion') function MultiCriterion:__init() parent.__init(self) self.criterions = {} self.weights = torch.DoubleStorage() end function MultiCriterion:add(criterion, weight) weight = weight or 1 table.insert(self.criterions, criterion) self.weights:resize(#self.criterions, true) self.weights[#self.criterions] = weight return self end function MultiCriterion:updateOutput(input, target) self.output = 0 for i=1,#self.criterions do self.output = self.output + self.weights[i]*self.criterions[i]:updateOutput(input, target) end return self.output end function MultiCriterion:updateGradInput(input, target) self.gradInput = nn.utils.recursiveResizeAs(self.gradInput, input) nn.utils.recursiveFill(self.gradInput, 0) for i=1,#self.criterions do nn.utils.recursiveAdd(self.gradInput, self.weights[i], self.criterions[i]:updateGradInput(input, target)) end return self.gradInput end function MultiCriterion:type(type) for i,criterion in ipairs(self.criterions) do criterion:type(type) end return parent.type(self, type) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Dynamis-Jeuno/bcnms/dynamis_jeuno.lua
16
1155
----------------------------------- -- Area: Dynamis Jeuno -- Name: Dynamis Jeuno ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaJeuno]UniqueID",player:getDynamisUniqueID(1283)); SetServerVariable("[DynaJeuno]Boss_Trigger",0); SetServerVariable("[DynaJeuno]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaJeuno]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then GetNPCByID(17547510):setStatus(2); SetServerVariable("[DynaJeuno]UniqueID",0); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/QuBia_Arena/npcs/Burning_Circle.lua
17
2534
----------------------------------- -- Area: Qu'Bia Arena -- NPC: Burning Circle -- @pos -221 -24 19 206 ------------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/QuBia_Arena/TextIDs"); ------------------------------------- -- 0: The Ruins of Fei'Yin, Darkness Rising, The Final Seal (Rank 5 Mission) -- 1: Come Into My Parlor -- 2: E-vase-ive Action -- 3: Infernal Swarm -- 4: The Heir to the Light -- 5: Shattering Stars (Paladin) -- 6: Shattering Stars (Dark Knight) -- 7: Shattering Stars (Bard) -- 8: Demolition Squad -- 9: Die By the Sword -- 10: Let Sleeping Dogs Die -- 11: Brothers D'Aurphe -- 12: Undying Promise -- 13: Factory Rejects -- 14: Idol Thoughts -- 15: An Awful Autopsy -- 16: Celery -- 17: Mirror Images -- 18: A Furious Finale (Dancer) -- 19: Clash of the Comrades -- 20: Those Who Lurk in the Shadows (III) -- 21: Beyond Infinity ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- if (player:hasKeyItem(MARK_OF_SEED) and player:getCurrentMission(ACP) == THOSE_WHO_LURK_IN_SHADOWS_II) then --player:startEvent(0x005); --elseif (EventTriggerBCNM(player,npc)) then -- Temp disabled pending fixes for the BCNM mobs. if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (csid == 0x005) then player:completeMission(ACP,THOSE_WHO_LURK_IN_SHADOWS_II); player:addMission(ACP,THOSE_WHO_LURK_IN_SHADOWS_III); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0