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 |
|---|---|---|---|---|---|
jeffchao/hedgewars-accessible | Hedgewars.app/Contents/Resources/hedgewars/Data/Maps/TrophyRace/map.lua | 2 | 4024 | -- Hedgewars - Roperace for 2+ Players
loadfile(GetDataPath() .. "Scripts/Locale.lua")()
-- store number of hedgehogs
local numhhs = 0
-- store hedgehog gears
local hhs = {}
-- store best time per team
local clantimes = {}
-- store best times
local times = {}
-- in milisseconds
local maxtime = 99000
-- define start area (left, top, width, height)
local start_area = {1606, 498, 356, 80}
-- define goal area (left, top, width, height)
local goal_area = {2030, 300, 56, 280}
-- last active hog
local lasthog = nil
-- active hog reached the goal?
local reached = false
-- hog with best time
local besthog = nil
-- hog with worst time (per round)
local worsthog = nil
-- best time
local besttime = maxtime + 1
-- worst time (per round)
local worsttime = 0
function onGameInit()
GameFlags = gfSolidLand + gfInvulnerable
TurnTime = maxtime
CaseFreq = 0
MinesNum = 0
Explosives = 0
Delay = 500
SuddenDeathTurns = 99999 -- "disable" sudden death
Theme = 'Olympics'
end
function onGameStart()
ShowMission(loc("TrophyRace"), "", loc("Use your rope to get from start to finish as fast as you can!"), -amRope, 0)
started = true
p=1820
for i = 0, numhhs - 1 do
p = p + 50
SetGearPosition(hhs[i], p, 0)
end
for i=0, ClansCount-1 do
clantimes[i] = 0
end
end
function onAmmoStoreInit()
SetAmmo(amRope, 9, 2, 0)
end
function onGameTick()
if TurnTimeLeft == 1 and CurrentHedgehog ~= nil then
SetHealth(CurrentHedgehog, 0)
x, y = GetGearPosition(CurrentHedgehog)
AddGear(x, y, gtAmmo_Grenade, 0, 0, 0, 0)
worsttime = 99999
worsthog = nil
elseif TurnTimeLeft == maxtime - 1 and CurrentHedgehog ~= nil then
if lasthog ~= nil then
SetGearPosition(lasthog, p , 0)
end
reached = false
SetGearPosition(CurrentHedgehog, start_area[1] + start_area[3] / 2, start_area[2] + start_area[4] / 2)
elseif CurrentHedgehog ~= nil then
x, y = GetGearPosition(CurrentHedgehog)
if not reached and x > goal_area[1] and x < goal_area[1] + goal_area[3] and y > goal_area[2] and y < goal_area[2] + goal_area[4] then -- hog is within goal rectangle
reached = true
local ttime = maxtime - TurnTimeLeft
--give it a sound;)
if ttime < besttime then
PlaySound (sndHomerun)
else
PlaySound (sndHellish)
end
for i = 0, numhhs - 1 do
if hhs[i] == CurrentHedgehog then
times[numhhs] = ttime
end
end
local hscore = "| |"
local clan = GetHogClan(CurrentHedgehog)
if ttime < clantimes[clan] or clantimes[clan] == 0 then
clantimes[clan] = ttime
end
if ttime < besttime then
besttime = ttime
besthog = CurrentHedgehog
hscore = hscore .. loc("NEW fastest lap: ")
else
hscore = hscore .. loc("Fastest lap: ")
end
if ttime > worsttime then
worsttime = ttime
worsthog = CurrentHedgehog
end
hscore = hscore .. GetHogName(besthog) .. " - " .. (besttime / 1000) .. " s | |" .. loc("Best laps per team: ")
if clan == ClansCount -1 then
-- Time for elimination - worst hog is out and the worst hog vars are reset.
SetHealth(worsthog, 0)
--Place a grenade to make inactive slowest hog active
x, y = GetGearPosition(worsthog)
AddGear(x, y, gtShell, 0, 0, 0, 0)
worsttime = 0
worsthog = nil
end
for i=0, ClansCount -1 do
local tt = "" .. (clantimes[i] / 1000) .. " s"
if clantimes[i] == 0 then
tt = "--"
end
hscore = hscore .. "|" .. string.format(loc("Team %d: "), i+1) .. tt
end
ShowMission(loc("TrophyRace"), "", loc("You've reached the goal!| |Time: ") .. (ttime / 1000) .. " s" .. hscore, 0, 0)
TurnTimeLeft = 0
end
end
end
function onGearAdd(gear)
if GetGearType(gear) == gtHedgehog then
hhs[numhhs] = gear
times[numhhs] = 0
numhhs = numhhs + 1
elseif GetGearType(gear) == gtRope then -- rope is shot
end
end
function onGearDelete(gear)
if GetGearType(gear) == gtRope then -- rope deletion - hog didn't manage to rerope
--TurnTimeLeft = 0 -- end turn or not? hm...
lasthog = CurrentHedgehog
end
end
| gpl-2.0 |
jthomasbarry/aafmt | archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/lib/Storage.lua | 3 | 3268 | -- Copyright 2012 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/lib/Storage.lua,v 1.4 2013/12/20 14:44:46 tantau Exp $
---
-- A storage is an object that, as the name suggests, allows you to
-- ``store stuff concerning objects.'' Basically, it behaves like
-- table having weak keys, which means that once the objects for which
-- you ``store stuff'' go out of scope, they are also removed from the
-- storage. Also, you can specify that for each object of the storage
-- you store a table. In this case, there is no need to initialize
-- this table for each object; rather, when you write into such a
-- table and it does not yet exist, it is created ``on the fly''.
--
-- The typical way you use storages is best explained with the
-- following example: Suppose you want to write a depth-first search
-- algorithm for a graph. This algorithm might wish to mark all nodes
-- it has visisted. It could just say |v.marked = true|, but this might
-- clash with someone else also using the |marked| key. The solution is
-- to create a |marked| storage. The algorithm can first say
--\begin{codeexample}[code only, tikz syntax=false]
--local marked = Storage.new()
--\end{codeexample}
-- and then say
--\begin{codeexample}[code only, tikz syntax=false]
--marked[v] = true
--\end{codeexample}
-- to mark its objects. The |marked| storage object does not need to
-- be created locally inside a function, you can declare it as a local
-- variable of the whole file; nevertheless, the entries for vertices
-- no longer in use get removed automatically. You can also make it a
-- member variable of the algorithm class, which allows you make the
-- information about which objects are marked globally
-- accessible.
--
-- Now suppose the algorithm would like to store even more stuff in
-- the storage. For this, we might use a table and can use the fact
-- that a storage will automatically create a table when necessary:
--\begin{codeexample}[code only, tikz syntax=false]
--local info = Storage.newTableStorage()
--
--info[v].marked = true -- the "info[v]" table is
-- -- created automatically here
--
--info[v].foo = "bar"
--\end{codeexample}
-- Again, once |v| goes out of scope, both it and the info table will
-- removed.
local Storage = {}
-- Namespace
require("pgf.gd.lib").Storage = Storage
-- The simple metatable
local SimpleStorageMetaTable = { __mode = "k" }
-- The adcanved metatable for table storages:
local TableStorageMetaTable = {
__mode = "k",
__index =
function(t, k)
local new = {}
rawset(t, k, new)
return new
end
}
---
-- Create a new storage object.
--
-- @return A new |Storage| instance.
function Storage.new()
return setmetatable({}, SimpleStorageMetaTable)
end
---
-- Create a new storage object which will install a table for every
-- entry automatilly.
--
-- @return A new |Storage| instance.
function Storage.newTableStorage()
return setmetatable({}, TableStorageMetaTable)
end
-- Done
return Storage | gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Port_San_dOria/npcs/Deguerendars.lua | 17 | 2163 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Deguerendars
-- Only sells when San d'Oria contrls Tavnazian Archipelago
-- Only available to those with CoP Ch. 4.1 or higher
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/conquest");
require("scripts/globals/quests");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local RegionOwner = GetRegionOwner(TAVNAZIANARCH);
cop = 40; --player:getVar("chainsOfPromathiaMissions");
if (cop >= 40) then
if (RegionOwner ~= NATION_SANDORIA) then
player:showText(npc,DEGUERENDARS_CLOSED_DIALOG);
else
player:showText(npc,DEGUERENDARS_OPEN_DIALOG);
local stock = {0x05f3,290, --Apple Mint
0x142c,1945, --Ground Wasabi
0x426d,99, --Lufaise Fly
0x144b,233} --Misareaux Parsley
showShop(player,SANDORIA,stock);
end
else
player:showText(npc,DEGUERENDARS_COP_NOT_COMPLETED);
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 |
majidhp888/Hack | plugins/moderation.lua | 336 | 9979 | 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 have been promoted as moderator for this 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 is already added.'
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 'Group has been added, and @'..username..' has been promoted as moderator for this group.'
end
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- 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 'Group has been added.'
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been 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, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function 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 as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
elseif mod_cmd == 'adminprom' 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 is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message .. '- '..v..' [' ..k.. '] \n'
end
return message
end
local function 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 admin available.'
end
local message = 'List for Bot admins:\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 works on 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] == 'promote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can promote"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
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] == 'adminprom' then
if not is_admin(msg) then
return "Only sudo can promote user as 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 promote user as 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 'Admin only!'
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 = "Moderation plugin",
usage = {
moderator = {
"!promote <username> : Promote user as moderator",
"!demote <username> : Demote user from moderator",
"!modlist : List of moderators",
},
admin = {
"!modadd : Add group to moderation list",
"!modrem : Remove group from moderation list",
},
sudo = {
"!adminprom <username> : Promote user as admin (must be done from a group)",
"!admindem <username> : Demote user from admin (must be done from a group)",
},
},
patterns = {
"^!(modadd)$",
"^!(modrem)$",
"^!(promote) (.*)$",
"^!(demote) (.*)$",
"^!(modlist)$",
"^!(adminprom) (.*)$", -- sudoers only
"^!(admindem) (.*)$", -- sudoers only
"^!(adminlist)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_created)$",
},
run = run,
}
end
| gpl-2.0 |
ashang/koreader | frontend/ui/wikipedia.lua | 1 | 2406 | local JSON = require("json")
local DEBUG = require("dbg")
--[[
-- Query wikipedia using Wikimedia Web API.
-- http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&redirects=&titles=hello
--]]
local Wikipedia = {
wiki_server = "http://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_params = {
action = "query",
prop = "extracts",
format = "json",
exintro = "",
explaintext = "",
redirects = "",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain)
local socket = require('socket')
local url = require('socket.url')
local http = require('socket.http')
local https = require('ssl.https')
local ltn12 = require('ltn12')
local request, sink = {}, {}
local query = ""
self.wiki_params.exintro = intro and "" or nil
self.wiki_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_params) do
query = query .. k .. '=' .. v .. '&'
end
local parsed = url.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. url.escape(text)
-- HTTP request
request['url'] = url.build(parsed)
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
DEBUG("request", request)
http.TIMEOUT, https.TIMEOUT = 10, 10
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
-- raise error message when network is unavailable
if headers == nil then
error("Network is unreachable")
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
DEBUG("wiki result", result)
return result
else
DEBUG("error:", result)
end
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result then
local query = result.query
if query then
return query.pages
end
end
end
return Wikipedia
| agpl-3.0 |
tommo/mock | mock/physics/2D/PhysicsShape.lua | 1 | 7685 | module 'mock'
--------------------------------------------------------------------
CLASS: PhysicsShape ( mock.Component )
:MODEL{
-- Field 'edit' :action('editShape') :meta{ icon='edit', style='tool'};
Field 'active' :boolean();
Field 'tag' :string();
Field 'loc' :type('vec2') :getset('Loc') :label('Loc');
Field 'material' :asset_pre( 'physics_material' ) :getset( 'Material' );
}
:META{
category = 'physics'
}
function PhysicsShape:__init()
self.active = true
self.tag = false
self.materialPath = false
self.material = false
self.loc = { 0,0 }
self.shape = false
self.parentBody = false
end
function PhysicsShape:clone(original)
original = original or self
-- make copy from derived class
local copy = self.__class()
copy:setMaterial(original:getMaterial())
copy.loc = { original.loc[1], original.loc[2] }
return copy
end
function PhysicsShape:getTag()
return self.tag
end
function PhysicsShape:setTag( tag )
self.tag = tag
if self.shape then
self.shape.tag = self.tag
end
end
function PhysicsShape:setLoc( x,y )
self.loc = { x or 0, y or 0 }
self:updateShape()
end
function PhysicsShape:getLoc()
return unpack( self.loc )
end
function PhysicsShape:getBox2DWorld()
return self:getScene():getBox2DWorld()
end
function PhysicsShape:findBody()
local body = self._entity:getComponent( PhysicsBody )
return body
end
function PhysicsShape:getBody()
return self.parentBody
end
function PhysicsShape:getBodyTag()
return self.parentBody:getTag()
end
function PhysicsShape:affirmMaterial()
local material = self.material
if not material then
material = self:getDefaultMaterial():clone()
self.material = material
end
return material
end
function PhysicsShape:isSensor()
if self.material then
return self.material.isSensor
end
return false
end
function PhysicsShape:setSensor( sensor )
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
material.isSensor = sensor or false
shape:setSensor( sensor or false )
self.parentBody:updateMass()
end
function PhysicsShape:getDensity()
if self.material then
return self.material.density
end
return false
end
function PhysicsShape:setDensity( density )
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
material.density = density or 1
shape:setDensity( density )
self.parentBody:updateMass()
end
function PhysicsShape:getFriction()
if self.material then
return self.material.friction
end
return false
end
function PhysicsShape:setFriction( friction )
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
material.friction = friction or 1
shape:setFriction( friction )
end
function PhysicsShape:getRestitution()
if self.material then
return self.material.restitution
end
return false
end
function PhysicsShape:setRestitution( restitution )
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
material.restitution = restitution or 1
shape:setRestitution( restitution )
end
function PhysicsShape:getMaterial()
return self.materialPath
end
function PhysicsShape:setMaterial( path )
self.materialPath = path
if path then
local material = loadAsset( path )
self.sourceMaterial = material
self.material = material:clone()
else
self.material = false
end
self:updateMaterial()
end
function PhysicsShape:resetMaterial()
if not self.sourceMaterial then
self.material = false
else
self.material = self.sourceMaterial:clone()
end
return self:updateMaterial()
end
function PhysicsShape:getMaterialTag()
return self.material and self.material.tag
end
function PhysicsShape:getDefaultMaterial()
return self.parentBody and self.parentBody:getDefaultMaterial() or getDefaultPhysicsMaterial()
end
function PhysicsShape:updateMaterial()
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
shape:setDensity ( material.density )
shape:setFriction ( material.friction )
shape:setRestitution ( material.restitution )
shape:setSensor ( material.isSensor )
-- print('categoryBits: ', bit.tohex(material.categoryBits), ' maskBits: ', bit.tohex(material.maskBits))
shape:setFilter (
material.categoryBits or 1,
material.maskBits or 0xffffffff,
material.group or 0
)
self.parentBody:updateMass()
shape.materialTag = material.tag
end
function PhysicsShape:getFilter()
local material = self:affirmMaterial()
return material.categoryBits, material.maskBits, material.group
end
function PhysicsShape:setFilter( categoryBits, maskBits, group )
local shape = self.shape
if not shape then return end
local material = self:affirmMaterial()
shape:setSensor ( material.isSensor )
shape:setFilter(
categoryBits or material.categoryBits or 1,
maskBits or material.maskBits or 0xffff,
group or material.group or 0 )
-- update owned copy of material as well
material.categoryBits = categoryBits
material.maskBits = maskBits
material.group = group
end
function PhysicsShape:resetFilter()
local sourceMaterial = self.sourceMaterial
if sourceMaterial then
self:setFilter(
sourceMaterial.categoryBits or 1,
sourceMaterial.maskBits or 0xffff,
sourceMaterial.group or 0
)
end
end
function PhysicsShape:onAttach( entity )
if not self.parentBody then
for com in pairs( entity:getComponents() ) do
if isInstance( com, PhysicsBody ) then
if com.body then
self:updateParentBody( com )
end
break
end
end
end
end
function PhysicsShape:onDetach( entity )
if not self.shape then return end
if self.parentBody and self.parentBody.body then
self.shape:destroy()
self.shape.component = nil
self.shape = false
end
end
function PhysicsShape:updateParentBody( body )
self.parentBody = body
self:updateShape()
end
function PhysicsShape:getParentBody()
return self.parentBody
end
function PhysicsShape:updateShape()
if not self.active then return end
local shape = self.shape
if shape then
shape.component = nil
shape:destroy()
self.shape = false
end
local parentBody = self.parentBody
if not parentBody then return end
local body = parentBody.body
shape = self:createShape( body )
-- back reference to the component
shape.component = self
self.shape = shape
shape.tag = self.tag
--apply material
--TODO
self:updateMaterial()
self:updateCollisionHandler()
end
function PhysicsShape:createShape( body )
local shape = body:addCircle( 0,0, 100 )
return shape
end
function PhysicsShape:setCollisionHandler(handler, phaseMask, categoryMask)
self.handlerData = {
func = handler,
phaseMask = phaseMask,
categoryMask = categoryMask
}
return self:updateCollisionHandler()
end
function PhysicsShape:updateCollisionHandler()
if not self.shape then return end
if not self.handlerData then return end
self.shape:setCollisionHandler(
self.handlerData.func,
self.handlerData.phaseMask,
self.handlerData.categoryMask
)
end
function PhysicsShape:getCollisionHandler()
if self.handlerData then
return self.handlerData.func, self.handlerData.phaseMask, self.handlerData.categoryMask
end
end
function PhysicsShape:getLocalVerts( steps )
return {}
end
function PhysicsShape:getGlobalVerts( steps )
local localVerts = self:getLocalVerts( steps )
local globalVerts = {}
local ent = self:getEntity()
local count = #localVerts/2
ent:forceUpdate()
for i = 0, count - 1 do
local x = localVerts[ i * 2 + 1 ]
local y = localVerts[ i * 2 + 2 ]
local x, y = ent:modelToWorld( x, y )
table.append( globalVerts, x, y )
end
return globalVerts
end
| mit |
petoju/awesome | tests/examples/wibox/container/arcchart/bg.lua | 5 | 1062 | --DOC_HIDE_ALL
--DOC_GEN_IMAGE
local parent = ...
local wibox = require( "wibox" )
local beautiful = require( "beautiful" )
local l = wibox.layout.fixed.horizontal()
l.spacing = 10
parent:add(l)
for _, v in ipairs {"", "#00ff00", "#0000ff"} do
l:add(wibox.widget {
{
text = v~="" and v or "nil",
align = "center",
valign = "center",
widget = wibox.widget.textbox,
},
colors = {
beautiful.bg_normal,
beautiful.bg_highlight,
beautiful.border_color,
},
values = {
1,
2,
3,
},
max_value = 10,
min_value = 0,
rounded_edge = false,
bg = v~="" and v or nil,
border_width = 0.5,
border_color = "#000000",
widget = wibox.container.arcchart
})
end
return nil, 60
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
petoju/awesome | lib/naughty/widget/title.lua | 3 | 2581 | ----------------------------------------------------------------------------
--- A notification title.
--
-- This widget is a specialized `wibox.widget.textbox` with the following extra
-- features:
--
-- * Honor the `beautiful` notification variables.
-- * React to the `naughty.notification` object title changes.
--
--@DOC_wibox_nwidget_title_simple_EXAMPLE@
--
-- @author Emmanuel Lepage Vallee <elv1313@gmail.com>
-- @copyright 2017 Emmanuel Lepage Vallee
-- @widgetmod naughty.widget.title
-- @see wibox.widget.textbox
----------------------------------------------------------------------------
local textbox = require("wibox.widget.textbox")
local gtable = require("gears.table")
local beautiful = require("beautiful")
local markup = require("naughty.widget._markup").set_markup
local title = {}
--- The attached notification.
-- @property notification
-- @tparam naughty.notification notification
-- @propemits true false
function title:set_notification(notif)
if self._private.notification == notif then return end
if self._private.notification then
self._private.notification:disconnect_signal("property::message",
self._private.title_changed_callback)
self._private.notification:disconnect_signal("property::fg",
self._private.title_changed_callback)
end
markup(self, notif.title, notif.fg, notif.font)
self._private.notification = notif
self._private.title_changed_callback()
notif:connect_signal("property::title", self._private.title_changed_callback)
notif:connect_signal("property::fg" , self._private.title_changed_callback)
self:emit_signal("property::notification", notif)
end
--- Create a new naughty.widget.title.
-- @tparam table args
-- @tparam naughty.notification args.notification The notification.
-- @constructorfct naughty.widget.title
-- @usebeautiful beautiful.notification_fg
-- @usebeautiful beautiful.notification_font
local function new(args)
args = args or {}
local tb = textbox()
tb:set_wrap("word")
tb:set_font(beautiful.notification_font)
gtable.crush(tb, title, true)
function tb._private.title_changed_callback()
markup(
tb,
tb._private.notification.title,
tb._private.notification.fg,
tb._private.notification.font
)
end
if args.notification then
tb:set_notification(args.notification)
end
return tb
end
--@DOC_widget_COMMON@
--@DOC_object_COMMON@
return setmetatable(title, {__call = function(_, ...) return new(...) end})
| gpl-2.0 |
openwrt-es/openwrt-luci | modules/luci-mod-admin-mini/luasrc/controller/mini/index.lua | 74 | 1261 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.mini.index", package.seeall)
function index()
local root = node()
if not root.lock then
root.target = alias("mini")
root.index = true
end
entry({"about"}, template("about"))
local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10)
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.index = true
entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true
entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true
entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10)
entry({"mini", "index", "logout"}, call("action_logout"), _("Logout"))
end
function action_logout()
local dsp = require "luci.dispatcher"
local utl = require "luci.util"
if dsp.context.authsession then
utl.ubus("session", "destroy", {
ubus_rpc_session = dsp.context.authsession
})
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| apache-2.0 |
majidhp888/Hack | plugins/id.lua | 355 | 2795 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
--local chat_id = "chat#id"..result.id
local chat_id = result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local receiver = cb_extra.receiver
local qusername = cb_extra.qusername
local text = 'User '..qusername..' not found in this group!'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == qusername then
text = 'ID for username\n'..vusername..' : '..v.id
end
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id
if is_chat_msg(msg) then
text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
else
if not is_chat_msg(msg) then
return "Only works in group"
end
local qusername = string.gsub(matches[1], "@", "")
local chat = get_receiver(msg)
chat_info(chat, username_id, {receiver=receiver, qusername=qusername})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id <username> : Return the id from username given."
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (.*)$"
},
run = run
}
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Arrapago_Reef/mobs/Zareehkl_the_Jubilant.lua | 23 | 1703 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: Zareehkl the Jubilant
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob, target)
local swapTimer = mob:getLocalVar("swapTime");
if (os.time() > swapTimer) then
if (mob:AnimationSub() == 1) then -- swap from fists to second weapon
mob:AnimationSub(2);
mob:setLocalVar("swapTime", os.time() + 60)
elseif (mob:AnimationSub() == 2) then -- swap from second weapon to fists
mob:AnimationSub(1);
mob:setLocalVar("swapTime", os.time() + 60)
end
end
end;
-----------------------------------
-- onCriticalHit
-----------------------------------
function onCriticalHit(mob)
if (math.random(100) < 5) then -- Wiki seems to imply that this thing's weapon is harder to break...
if (mob:AnimationSub() == 0) then -- first weapon
mob:AnimationSub(1);
mob:setLocalVar("swapTime", os.time() + 60) -- start the timer for swapping between fists and the second weapon
elseif (mob:AnimationSub() == 2) then -- second weapon
mob:AnimationSub(3);
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Norg/npcs/Chiyo.lua | 3 | 1298 | -----------------------------------
-- Area: Norg
-- NPC: Chiyo
-- Type: Tenshodo Merchant
-- !pos 5.801 0.020 -18.739 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60422,9,23,7)) then
player:showText(npc, CHIYO_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
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 |
RebootRevival/FFXI_Test | scripts/globals/items/angler_stewpot.lua | 12 | 1879 | -----------------------------------------
-- ID: 5611
-- Item: Angler's Stewpot
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% (cap 200)
-- MP +10
-- HP Recoverd while healing 5
-- MP Recovered while healing 1
-- Accuracy +15% Cap 15
-- Ranged Accuracy 15% Cap 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5611);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 200);
target:addMod(MOD_MP, 10);
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_FOOD_ACCP, 15);
target:addMod(MOD_FOOD_ACC_CAP, 15);
target:addMod(MOD_FOOD_RACCP, 15);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 200);
target:delMod(MOD_MP, 10);
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_FOOD_ACCP, 15);
target:delMod(MOD_FOOD_ACC_CAP, 15);
target:delMod(MOD_FOOD_RACCP, 15);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
openwrt-es/openwrt-luci | protocols/luci-proto-qmi/luasrc/model/cbi/admin_network/proto_qmi.lua | 17 | 1270 | -- Copyright 2016 David Thornley <david.thornley@touchstargroup.com>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, apn, pincode, username, password
local auth, ipv6
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/cdc-wdm*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
apn = section:taboption("general", Value, "apn", translate("APN"))
pincode = section:taboption("general", Value, "pincode", translate("PIN"))
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
auth = section:taboption("general", Value, "auth", translate("Authentication Type"))
auth:value("", translate("-- Please choose --"))
auth:value("both", "PAP/CHAP (both)")
auth:value("pap", "PAP")
auth:value("chap", "CHAP")
auth:value("none", "NONE")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation"))
ipv6.default = ipv6.disabled
end
| apache-2.0 |
SinisterRectus/Discordia | libs/voice/VoiceSocket.lua | 1 | 4238 | local uv = require('uv')
local class = require('class')
local timer = require('timer')
local enums = require('enums')
local WebSocket = require('client/WebSocket')
local logLevel = enums.logLevel
local format = string.format
local setInterval, clearInterval = timer.setInterval, timer.clearInterval
local wrap = coroutine.wrap
local time = os.time
local unpack = string.unpack -- luacheck: ignore
local ENCRYPTION_MODE = 'xsalsa20_poly1305'
local PADDING = string.rep('\0', 70)
local IDENTIFY = 0
local SELECT_PROTOCOL = 1
local READY = 2
local HEARTBEAT = 3
local DESCRIPTION = 4
local SPEAKING = 5
local HEARTBEAT_ACK = 6
local RESUME = 7
local HELLO = 8
local RESUMED = 9
local function checkMode(modes)
for _, mode in ipairs(modes) do
if mode == ENCRYPTION_MODE then
return mode
end
end
end
local VoiceSocket = class('VoiceSocket', WebSocket)
for name in pairs(logLevel) do
VoiceSocket[name] = function(self, fmt, ...)
local client = self._client
return client[name](client, format('Voice : %s', fmt), ...)
end
end
function VoiceSocket:__init(state, connection, manager)
WebSocket.__init(self, manager)
self._state = state
self._manager = manager
self._client = manager._client
self._connection = connection
self._session_id = state.session_id
end
function VoiceSocket:handleDisconnect()
-- TODO: reconnecting and resuming
self._connection:_cleanup()
end
function VoiceSocket:handlePayload(payload)
local manager = self._manager
local d = payload.d
local op = payload.op
self:debug('WebSocket OP %s', op)
if op == HELLO then
self:info('Received HELLO')
self:startHeartbeat(d.heartbeat_interval * 0.75) -- NOTE: hotfix for API bug
self:identify()
elseif op == READY then
self:info('Received READY')
local mode = checkMode(d.modes)
if mode then
self._mode = mode
self._ssrc = d.ssrc
self:handshake(d.ip, d.port)
else
self:error('No supported encryption mode available')
self:disconnect()
end
elseif op == RESUMED then
self:info('Received RESUMED')
elseif op == DESCRIPTION then
if d.mode == self._mode then
self._connection:_prepare(d.secret_key, self)
else
self:error('%q encryption mode not available', self._mode)
self:disconnect()
end
elseif op == HEARTBEAT_ACK then
manager:emit('heartbeat', nil, self._sw.milliseconds) -- TODO: id
elseif op == SPEAKING then
return -- TODO
elseif op == 12 or op == 13 then
return -- ignore
elseif op then
self:warning('Unhandled WebSocket payload OP %i', op)
end
end
local function loop(self)
return wrap(self.heartbeat)(self)
end
function VoiceSocket:startHeartbeat(interval)
if self._heartbeat then
clearInterval(self._heartbeat)
end
self._heartbeat = setInterval(interval, loop, self)
end
function VoiceSocket:stopHeartbeat()
if self._heartbeat then
clearInterval(self._heartbeat)
end
self._heartbeat = nil
end
function VoiceSocket:heartbeat()
self._sw:reset()
return self:_send(HEARTBEAT, time())
end
function VoiceSocket:identify()
local state = self._state
return self:_send(IDENTIFY, {
server_id = state.guild_id,
user_id = state.user_id,
session_id = state.session_id,
token = state.token,
}, true)
end
function VoiceSocket:resume()
local state = self._state
return self:_send(RESUME, {
server_id = state.guild_id,
session_id = state.session_id,
token = state.token,
})
end
function VoiceSocket:handshake(server_ip, server_port)
local udp = uv.new_udp()
self._udp = udp
self._ip = server_ip
self._port = server_port
udp:recv_start(function(err, data)
assert(not err, err)
udp:recv_stop()
local client_ip = unpack('xxxxz', data)
local client_port = unpack('<I2', data, -2)
return wrap(self.selectProtocol)(self, client_ip, client_port)
end)
return udp:send(PADDING, server_ip, server_port)
end
function VoiceSocket:selectProtocol(address, port)
return self:_send(SELECT_PROTOCOL, {
protocol = 'udp',
data = {
address = address,
port = port,
mode = self._mode,
}
})
end
function VoiceSocket:setSpeaking(speaking)
return self:_send(SPEAKING, {
speaking = speaking,
delay = 0,
ssrc = self._ssrc,
})
end
return VoiceSocket
| mit |
RebootRevival/FFXI_Test | scripts/zones/Northern_San_dOria/npcs/Mevaloud.lua | 17 | 1452 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Mevaloud
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0295);
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 |
rafradek/wire | lua/entities/gmod_wire_expression2/core/number.lua | 9 | 17049 | -- these upvalues (locals in an enclosing scope) are faster to access than globals.
local delta = wire_expression2_delta
local math = math
local random = math.random
local pi = math.pi
local exp = math.exp
local log = math.log
local log10 = math.log10
local sqrt = math.sqrt
local floor = math.floor
local ceil = math.ceil
local Round = math.Round
local sin = math.sin
local cos = math.cos
local tan = math.tan
local acos = math.acos
local asin = math.asin
local atan = math.atan
local atan2 = math.atan2
local sinh = math.sinh
local cosh = math.cosh
local tanh = math.tanh
--[[************************************************************************]]--
-- Numeric support
--[[************************************************************************]]--
registerType("normal", "n", 0,
nil,
nil,
function(retval)
if !isnumber(retval) then error("Return value is not a number, but a "..type(retval).."!",0) end
end,
function(v)
return !isnumber(v)
end
)
E2Lib.registerConstant("PI", pi)
E2Lib.registerConstant("E", exp(1))
E2Lib.registerConstant("PHI", (1+sqrt(5))/2)
--[[************************************************************************]]--
__e2setcost(2)
registerOperator("ass", "n", "n", function(self, args)
local op1, op2, scope = args[2], args[3], args[4]
local rv2 = op2[1](self, op2)
self.Scopes[scope][op1] = rv2
self.Scopes[scope].vclk[op1] = true
return rv2
end)
__e2setcost(1.5)
registerOperator("inc", "n", "", function(self, args)
local op1, scope = args[2], args[3]
self.Scopes[scope][op1] = self.Scopes[scope][op1] + 1
self.Scopes[scope].vclk[op1] = true
end)
registerOperator("dec", "n", "", function(self, args)
local op1, scope = args[2], args[3]
self.Scopes[scope][op1] = self.Scopes[scope][op1] - 1
self.Scopes[scope].vclk[op1] = true
end)
--[[************************************************************************]]--
__e2setcost(1.5)
registerOperator("eq", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if rvd <= delta && -rvd <= delta
then return 1 else return 0 end
end)
registerOperator("neq", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if rvd > delta || -rvd > delta
then return 1 else return 0 end
end)
__e2setcost(1.25)
registerOperator("geq", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if -rvd <= delta
then return 1 else return 0 end
end)
registerOperator("leq", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if rvd <= delta
then return 1 else return 0 end
end)
registerOperator("gth", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if rvd > delta
then return 1 else return 0 end
end)
registerOperator("lth", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rvd = op1[1](self, op1) - op2[1](self, op2)
if -rvd > delta
then return 1 else return 0 end
end)
--[[************************************************************************]]--
__e2setcost(5)
registerOperator("dlt", "n", "n", function(self, args)
local op1, scope = args[2], args[3]
return self.Scopes[scope][op1] - self.Scopes[scope]["$" .. op1]
end)
__e2setcost(0.5) -- approximation
registerOperator("neg", "n", "n", function(self, args)
local op1 = args[2]
return -op1[1](self, op1)
end)
__e2setcost(1)
registerOperator("add", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) + op2[1](self, op2)
end)
registerOperator("sub", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) - op2[1](self, op2)
end)
registerOperator("mul", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) * op2[1](self, op2)
end)
registerOperator("div", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) / op2[1](self, op2)
end)
registerOperator("exp", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) ^ op2[1](self, op2)
end)
registerOperator("mod", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
return op1[1](self, op1) % op2[1](self, op2)
end)
--[[************************************************************************]]--
-- TODO: select, average
-- TODO: is the shifting correct for rounding arbitrary decimals?
__e2setcost(1)
registerFunction("min", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
if rv1 < rv2 then return rv1 else return rv2 end
end)
registerFunction("min", "nnn", "n", function(self, args)
local op1, op2, op3 = args[2], args[3], args[4]
local rv1, rv2, rv3 = op1[1](self, op1), op2[1](self, op2), op3[1](self, op3)
local val
if rv1 < rv2 then val = rv1 else val = rv2 end
if rv3 < val then return rv3 else return val end
end)
registerFunction("min", "nnnn", "n", function(self, args)
local op1, op2, op3, op4 = args[2], args[3], args[4], args[5]
local rv1, rv2, rv3, rv4 = op1[1](self, op1), op2[1](self, op2), op3[1](self, op3), op4[1](self, op4)
local val
if rv1 < rv2 then val = rv1 else val = rv2 end
if rv3 < val then val = rv3 end
if rv4 < val then return rv4 else return val end
end)
registerFunction("max", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
if rv1 > rv2 then return rv1 else return rv2 end
end)
registerFunction("max", "nnn", "n", function(self, args)
local op1, op2, op3 = args[2], args[3], args[4]
local rv1, rv2, rv3 = op1[1](self, op1), op2[1](self, op2), op3[1](self, op3)
local val
if rv1 > rv2 then val = rv1 else val = rv2 end
if rv3 > val then return rv3 else return val end
end)
registerFunction("max", "nnnn", "n", function(self, args)
local op1, op2, op3, op4 = args[2], args[3], args[4], args[5]
local rv1, rv2, rv3, rv4 = op1[1](self, op1), op2[1](self, op2), op3[1](self, op3), op4[1](self, op4)
local val
if rv1 > rv2 then val = rv1 else val = rv2 end
if rv3 > val then val = rv3 end
if rv4 > val then return rv4 else return val end
end)
--[[************************************************************************]]--
__e2setcost(2) -- approximation
e2function number abs(value)
if value >= 0 then return value else return -value end
end
--- rounds towards +inf
e2function number ceil(rv1)
return ceil(rv1)
end
e2function number ceil(value, decimals)
local shf = 10 ^ floor(decimals + 0.5)
return ceil(value * shf) / shf
end
--- rounds towards -inf
e2function number floor(rv1)
return floor(rv1)
end
e2function number floor(value, decimals)
local shf = 10 ^ floor(decimals + 0.5)
return floor(value * shf) / shf
end
--- rounds to the nearest integer
e2function number round(rv1)
return floor(rv1 + 0.5)
end
e2function number round(value, decimals)
local shf = 10 ^ floor(decimals + 0.5)
return floor(value * shf + 0.5) / shf
end
--- rounds towards zero
e2function number int(rv1)
if rv1 >= 0 then return floor(rv1) else return ceil(rv1) end
end
--- returns the fractional part. (frac(-1.5) == 0.5 & frac(3.2) == 0.2)
e2function number frac(rv1)
if rv1 >= 0 then return rv1 % 1 else return rv1 % -1 end
end
-- TODO: what happens with negative modulo?
registerFunction("mod", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
if rv1 >= 0 then return rv1 % rv2 else return rv1 % -rv2 end
end)
-- TODO: change to a more suitable name? (cyclic modulo?)
-- add helpers for wrap90 wrap180, wrap90r wrap180r? or pointless?
-- wrap90(Pitch), wrap(Pitch, 90)
-- should be added...
registerFunction("wrap", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return (rv1 + rv2) % (rv2 * 2) - rv2
end)
registerFunction("clamp", "nnn", "n", function(self, args)
local op1, op2, op3 = args[2], args[3], args[4]
local rv1, rv2, rv3 = op1[1](self, op1), op2[1](self, op2), op3[1](self, op3)
if rv1 < rv2 then return rv2 elseif rv1 > rv3 then return rv3 else return rv1 end
end)
--- Returns 1 if <value> is in the interval [<min>; <max>], 0 otherwise.
e2function number inrange(value, min, max)
if value < min then return 0 end
if value > max then return 0 end
return 1
end
registerFunction("sign", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
if rv1 > delta then return 1
elseif rv1 < -delta then return -1
else return 0 end
end)
--[[************************************************************************]]--
__e2setcost(2) -- approximation
registerFunction("random", "", "n", function(self, args)
return random()
end)
registerFunction("random", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return random() * rv1
end)
registerFunction("random", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return rv1 + random() * (rv2 - rv1)
end)
registerFunction("randint", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return random(rv1)
end)
registerFunction("randint", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
local temp = rv1
if (rv1 > rv2) then rv1 = rv2 rv2 = temp end
return random(rv1, rv2)
end)
--[[************************************************************************]]--
__e2setcost(2) -- approximation
registerFunction("sqrt", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return rv1 ^ (1 / 2)
end)
registerFunction("cbrt", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return rv1 ^ (1 / 3)
end)
registerFunction("root", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return rv1 ^ (1 / rv2)
end)
local const_e = exp(1)
registerFunction("e", "", "n", function(self, args)
return const_e
end)
registerFunction("exp", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return exp(rv1)
end)
registerFunction("ln", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return log(rv1)
end)
local const_log2 = log(2)
registerFunction("log2", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return log(rv1) / const_log2
end)
registerFunction("log10", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return log10(rv1)
end)
registerFunction("log", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return log(rv1) / log(rv2)
end)
--[[************************************************************************]]--
__e2setcost(2) -- approximation
local deg2rad = pi / 180
local rad2deg = 180 / pi
registerFunction("pi", "", "n", function(self, args)
return pi
end)
registerFunction("toRad", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return rv1 * deg2rad
end)
registerFunction("toDeg", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return rv1 * rad2deg
end)
registerFunction("acos", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return acos(rv1) * rad2deg
end)
registerFunction("asin", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return asin(rv1) * rad2deg
end)
registerFunction("atan", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return atan(rv1) * rad2deg
end)
registerFunction("atan", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return atan2(rv1, rv2) * rad2deg
end)
registerFunction("cos", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return cos(rv1 * deg2rad)
end)
registerFunction("sec", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/cos(rv1 * deg2rad)
end)
registerFunction("sin", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return sin(rv1 * deg2rad)
end)
registerFunction("csc", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/sin(rv1 * deg2rad)
end)
registerFunction("tan", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return tan(rv1 * deg2rad)
end)
registerFunction("cot", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/tan(rv1 * deg2rad)
end)
registerFunction("cosh", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return cosh(rv1)
end)
registerFunction("sech", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/cosh(rv1)
end)
registerFunction("sinh", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return sinh(rv1)
end)
registerFunction("csch", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/sinh(rv1)
end)
registerFunction("tanh", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return tanh(rv1)
end)
registerFunction("coth", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/tanh(rv1)
end)
registerFunction("acosr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return acos(rv1)
end)
registerFunction("asinr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return asin(rv1)
end)
registerFunction("atanr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return atan(rv1)
end)
registerFunction("atanr", "nn", "n", function(self, args)
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self, op1), op2[1](self, op2)
return atan2(rv1, rv2)
end)
registerFunction("cosr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return cos(rv1)
end)
registerFunction("secr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/cos(rv1)
end)
registerFunction("sinr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return sin(rv1)
end)
registerFunction("cscr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/sin(rv1)
end)
registerFunction("tanr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return tan(rv1)
end)
registerFunction("cotr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/tan(rv1)
end)
registerFunction("coshr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return cosh(rv1)
end)
registerFunction("sechr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/cosh(rv1)
end)
registerFunction("sinhr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return sinh(rv1)
end)
registerFunction("cschr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/sinh(rv1)
end)
registerFunction("tanhr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return tanh(rv1)
end)
registerFunction("cothr", "n", "n", function(self, args)
local op1 = args[2]
local rv1 = op1[1](self, op1)
return 1/tanh(rv1)
end)
--[[************************************************************************]]--
__e2setcost(15) -- approximation
e2function string toString(number number)
return tostring(number)
end
e2function string number:toString()
return tostring(this)
end
__e2setcost(25) -- approximation
local function tobase(number, base, self)
local ret = ""
if base < 2 or base > 36 or number == 0 then return "0" end
if base == 10 then return tostring(number) end
local chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local loops = 0
while number > 0 do
loops = loops + 1
number, d = math.floor(number/base),(number%base)+1
ret = string.sub(chars,d,d)..ret
if (loops > 32000) then break end
end
self.prf = self.prf + loops
return ret
end
e2function string toString(number number, number base)
return tobase(number, base, self)
end
e2function string number:toString(number base)
return tobase(this, base, self)
end
| apache-2.0 |
petoju/awesome | lib/awful/client/focus.lua | 3 | 7160 | ---------------------------------------------------------------------------
--- Keep track of the focused clients.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @submodule client
---------------------------------------------------------------------------
local grect = require("gears.geometry").rectangle
local capi =
{
screen = screen,
client = client,
}
-- We use a metatable to prevent circular dependency loops.
local screen
do
screen = setmetatable({}, {
__index = function(_, k)
screen = require("awful.screen")
return screen[k]
end,
__newindex = error -- Just to be sure in case anything ever does this
})
end
local client
do
client = setmetatable({}, {
__index = function(_, k)
client = require("awful.client")
return client[k]
end,
__newindex = error -- Just to be sure in case anything ever does this
})
end
local focus = {history = {list = {}}}
local function get_screen(s)
return s and capi.screen[s]
end
--- Remove a client from the focus history
--
-- @tparam client c The client that must be removed.
-- @function awful.client.focus.history.delete
function focus.history.delete(c)
for k, v in ipairs(focus.history.list) do
if v == c then
table.remove(focus.history.list, k)
break
end
end
end
--- Focus a client by its relative index.
--
-- @function awful.client.focus.byidx
-- @param i The index.
-- @tparam[opt] client c The client.
-- @request client activate client.focus.byidx granted When `awful.focus.byidx`
-- is called.
function focus.byidx(i, c)
local target = client.next(i, c)
if target then
target:emit_signal("request::activate", "client.focus.byidx",
{raise=true})
end
end
--- Filter out window that we do not want handled by focus.
-- This usually means that desktop, dock and splash windows are
-- not registered and cannot get focus.
--
-- @tparam client c A client.
-- @return The same client if it's ok, nil otherwise.
-- @function awful.client.focus.filter
function focus.filter(c)
if c.type == "desktop"
or c.type == "dock"
or c.type == "splash"
or not c.focusable then
return nil
end
return c
end
--- Update client focus history.
--
-- @tparam client c The client that has been focused.
-- @function awful.client.focus.history.add
function focus.history.add(c)
-- Remove the client if its in stack
focus.history.delete(c)
-- Record the client has latest focused
table.insert(focus.history.list, 1, c)
end
--- Get the latest focused client for a screen in history.
--
-- @tparam int|screen s The screen to look for.
-- @tparam int idx The index: 0 will return first candidate,
-- 1 will return second, etc.
-- @tparam function filter An optional filter. If no client is found in the
-- first iteration, `awful.client.focus.filter` is used by default to get any
-- client.
-- @treturn client.object A client.
-- @function awful.client.focus.history.get
function focus.history.get(s, idx, filter)
s = get_screen(s)
-- When this counter is equal to idx, we return the client
local counter = 0
local vc = client.visible(s, true)
for _, c in ipairs(focus.history.list) do
if get_screen(c.screen) == s then
if not filter or filter(c) then
for _, vcc in ipairs(vc) do
if vcc == c then
if counter == idx then
return c
end
-- We found one, increment the counter only.
counter = counter + 1
break
end
end
end
end
end
-- Argh nobody found in history, give the first one visible if there is one
-- that passes the filter.
filter = filter or focus.filter
if counter == 0 then
for _, v in ipairs(vc) do
if filter(v) then
return v
end
end
end
end
--- Focus the previous client in history.
-- @function awful.client.focus.history.previous
-- @request client activate client.focus.history.previous granted When
-- `awful.focus.history.previous` is called.
function focus.history.previous()
local sel = capi.client.focus
local s = sel and sel.screen or screen.focused()
local c = focus.history.get(s, 1)
if c then
c:emit_signal("request::activate", "client.focus.history.previous",
{raise=false})
end
end
--- Focus a client by the given direction.
--
-- @tparam string dir The direction, can be either
-- `"up"`, `"down"`, `"left"` or `"right"`.
-- @tparam[opt] client c The client.
-- @tparam[opt=false] boolean stacked Use stacking order? (top to bottom)
-- @function awful.client.focus.bydirection
-- @request client activate client.focus.bydirection granted When
-- `awful.focus.bydirection` is called.
function focus.bydirection(dir, c, stacked)
local sel = c or capi.client.focus
if sel then
local cltbl = client.visible(sel.screen, stacked)
local geomtbl = {}
for i,cl in ipairs(cltbl) do
geomtbl[i] = cl:geometry()
end
local target = grect.get_in_direction(dir, geomtbl, sel:geometry())
-- If we found a client to focus, then do it.
if target then
cltbl[target]:emit_signal("request::activate",
"client.focus.bydirection", {raise=false})
end
end
end
--- Focus a client by the given direction. Moves across screens.
--
-- @param dir The direction, can be either "up", "down", "left" or "right".
-- @tparam[opt] client c The client.
-- @tparam[opt=false] boolean stacked Use stacking order? (top to bottom)
-- @function awful.client.focus.global_bydirection
-- @request client activate client.focus.global_bydirection granted When
-- `awful.client.focus.global_bydirection` is called.
function focus.global_bydirection(dir, c, stacked)
local sel = c or capi.client.focus
local scr = get_screen(sel and sel.screen or screen.focused())
-- change focus inside the screen
focus.bydirection(dir, sel)
-- if focus not changed, we must change screen
if sel == capi.client.focus then
screen.focus_bydirection(dir, scr)
if scr ~= get_screen(screen.focused()) then
local cltbl = client.visible(screen.focused(), stacked)
local geomtbl = {}
for i,cl in ipairs(cltbl) do
geomtbl[i] = cl:geometry()
end
local target = grect.get_in_direction(dir, geomtbl, scr.geometry)
if target then
cltbl[target]:emit_signal("request::activate",
"client.focus.global_bydirection",
{raise=false})
end
end
end
end
return focus
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/RoMaeve/npcs/Qu_Hau_Spring.lua | 3 | 2537 | -----------------------------------
-- Qu_Hau_Spring
-- Area: Ro'Maeve
-----------------------------------
package.loaded["scripts/zones/RoMaeve/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RoMaeve/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local DMfirst = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT);
local DMRepeat = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT_REPEAT);
local Hour = VanadielHour();
if ((Hour >= 18 or Hour < 6) and IsMoonFull() == true) then
if (DMfirst == QUEST_ACCEPTED or DMRepeat == QUEST_ACCEPTED) then -- allow for Ark Pentasphere on both first and repeat quests
if (trade:hasItemQty(1408,1) and trade:hasItemQty(917,1) and trade:getItemCount() == 2) then
player:startEvent(7,917,1408); -- Ark Pentasphere Trade
elseif (DMRepeat == QUEST_ACCEPTED and trade:hasItemQty(1261,1) and trade:getItemCount() == 1 and player:hasKeyItem(MOONLIGHT_ORE) == false) then
player:startEvent(8); -- Moonlight Ore trade
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(WINDURST);
local MissionStatus = player:getVar("MissionStatus");
if (CurrentMission == VAIN and MissionStatus >= 1) then
player:startEvent(2);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 7) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1550);
else
player:addItem(1550);
player:messageSpecial(ITEM_OBTAINED,1550);
player:tradeComplete();
end
elseif (csid == 8) then
player:tradeComplete();
player:addKeyItem(MOONLIGHT_ORE);
player:messageSpecial(KEYITEM_OBTAINED,MOONLIGHT_ORE);
elseif (csid == 2 and player:getCurrentMission(WINDURST) == VAIN) then
player:setVar("MissionStatus",2);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Metalworks/npcs/Romero.lua | 3 | 1798 | -----------------------------------
-- Area: Metalworks
-- NPC: Romero
-- Type: Smithing Synthesis Image Support
-- !pos -106.336 2.000 26.117 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,8);
local SkillCap = getCraftSkillCap(player,SKILL_SMITHING);
local SkillLevel = player:getSkillLevel(SKILL_SMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then
player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),0,0,0);
else
player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),7127,0,0);
end
else
player:startEvent(0x0069); -- 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 == 0x0069 and option == 1) then
player:messageSpecial(SMITHING_SUPPORT,0,2,2);
player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
openwrt-es/openwrt-luci | applications/luci-app-simple-adblock/luasrc/model/cbi/simpleadblock.lua | 9 | 2652 | m = Map("simple-adblock", translate("Simple AdBlock Settings"))
s = m:section(NamedSection, "config", "simple-adblock")
-- General options
e = s:option(Flag, "enabled", translate("Start Simple Adblock service"))
e.rmempty = false
function e.write(self, section, value)
if value ~= "1" then
luci.sys.init.stop("simple-adblock")
end
return Flag.write(self, section, value)
end
o2 = s:option(ListValue, "verbosity", translate("Output Verbosity Setting"),translate("Controls system log and console output verbosity"))
o2:value("0", translate("Suppress output"))
o2:value("1", translate("Some output"))
o2:value("2", translate("Verbose output"))
o2.rmempty = false
o2.default = 2
o3 = s:option(ListValue, "force_dns", translate("Force Router DNS"), translate("Forces Router DNS use on local devices, also known as DNS Hijacking"))
o3:value("0", translate("Let local devices use their own DNS servers if set"))
o3:value("1", translate("Force Router DNS server to all local devices"))
o3.rmempty = false
o3.default = 1
local sysfs_path = "/sys/class/leds/"
local leds = {}
if nixio.fs.access(sysfs_path) then
leds = nixio.util.consume((nixio.fs.dir(sysfs_path)))
end
if #leds ~= 0 then
o3 = s:option(Value, "led", translate("LED to indicate status"), translate("Pick the LED not already used in")
.. [[ <a href="]] .. luci.dispatcher.build_url("admin/system/leds") .. [[">]]
.. translate("System LED Configuration") .. [[</a>]])
o3.rmempty = true
o3:value("", translate("none"))
for k, v in ipairs(leds) do
o3:value(v)
end
end
s2 = m:section(NamedSection, "config", "simple-adblock")
-- Whitelisted Domains
d1 = s2:option(DynamicList, "whitelist_domain", translate("Whitelisted Domains"), translate("Individual domains to be whitelisted"))
d1.addremove = false
d1.optional = false
-- Blacklisted Domains
d3 = s2:option(DynamicList, "blacklist_domain", translate("Blacklisted Domains"), translate("Individual domains to be blacklisted"))
d3.addremove = false
d3.optional = false
-- Whitelisted Domains URLs
d2 = s2:option(DynamicList, "whitelist_domains_url", translate("Whitelisted Domain URLs"), translate("URLs to lists of domains to be whitelisted"))
d2.addremove = false
d2.optional = false
-- Blacklisted Domains URLs
d4 = s2:option(DynamicList, "blacklist_domains_url", translate("Blacklisted Domain URLs"), translate("URLs to lists of domains to be blacklisted"))
d4.addremove = false
d4.optional = false
-- Blacklisted Hosts URLs
d5 = s2:option(DynamicList, "blacklist_hosts_url", translate("Blacklisted Hosts URLs"), translate("URLs to lists of hosts to be blacklisted"))
d5.addremove = false
d5.optional = false
return m
| apache-2.0 |
rafradek/wire | lua/wire/client/wire_filebrowser.lua | 10 | 18931 | // A file browser panel, used by the sound browser.
// Can be used for any file type, recommend for huge file numbers.
// Made by Grocel.
local PANEL = {}
AccessorFunc( PANEL, "m_strRootName", "RootName" ) // name of the root Root
AccessorFunc( PANEL, "m_strRootPath", "RootPath" ) // path of the root Root
AccessorFunc( PANEL, "m_strWildCard", "WildCard" ) // "GAME", "DATA" etc.
AccessorFunc( PANEL, "m_tFilter", "FileTyps" ) // "*.wav", "*.mdl", {"*.vmt", "*.vtf"} etc.
AccessorFunc( PANEL, "m_strOpenPath", "OpenPath" ) // open path
AccessorFunc( PANEL, "m_strOpenFile", "OpenFile" ) // open path+file
AccessorFunc( PANEL, "m_strOpenFilename", "OpenFilename" ) // open file
AccessorFunc( PANEL, "m_nListSpeed", "ListSpeed" ) // how many items to list an once
AccessorFunc( PANEL, "m_nMaxItemsPerPage", "MaxItemsPerPage" ) // how may items per page
AccessorFunc( PANEL, "m_nPage", "Page" ) // Page to show
local invalid_chars = {
["\n"] = "",
["\r"] = "",
["\\"] = "/",
["//"] = "/",
//["/.svn"] = "", // Disallow access to .svn folders. (Not needed.)
//["/.git"] = "", // Disallow access to .git folders. (Not needed.)
}
local function ConnectPathes(path1, path2)
local path = ""
if (isstring(path1) and path1 ~= "") then
path = path1
if (isstring(path2) and path2 ~= "") then
path = path1.."/"..path2
end
else
if (isstring(path2) and path2 ~= "") then
path = path2
end
end
return path
end
local function PathFilter(Folder, TxtPanel, Root)
if (!isstring(Folder) or Folder == "") then return end
local ValidFolder = Folder
//local ValidFolder = string.lower(Folder) // for .svn and .git filters.
for k, v in pairs(invalid_chars) do
for i = 1, #string.Explode(k, ValidFolder) do
if (!string.match(ValidFolder, k)) then break end
ValidFolder = string.gsub(ValidFolder, k, v)
end
end
ValidFolder = string.Trim(ValidFolder)
/*if (string.sub(ValidFolder, 0, 4) == ".svn") then // Disallow access to .svn folders. (Not needed.)
ValidFolder = string.sub(ValidFolder, -4)
if (ValidFolder == ".svn") then
ValidFolder = ""
end
end*/
/*if (string.sub(ValidFolder, 0, 4) == ".git") then // Disallow access to .git folders. (Not needed.)
ValidFolder = string.sub(ValidFolder, -4)
if (ValidFolder == ".git") then
ValidFolder = ""
end
end*/
ValidFolder = string.Trim(ValidFolder, "/")
if (IsValid(TxtPanel)) then
TxtPanel:SetText(ValidFolder)
end
local Dirs = #string.Explode("/", ValidFolder)
for i = 1, Dirs do
if (!file.IsDir(ConnectPathes(Root, ValidFolder), "GAME")) then
ValidFolder = string.GetPathFromFilename(ValidFolder)
ValidFolder = string.Trim(ValidFolder, "/")
end
end
ValidFolder = string.Trim(ValidFolder, "/")
if (ValidFolder == "") then return end
return ValidFolder
end
local function EnableButton(button, bool)
button:SetEnabled(bool)
button:SetMouseInputEnabled(bool)
end
local function BuildFileList(path, filter, wildcard)
local files = {}
if (istable(filter)) then
for k, v in ipairs(filter) do
table.Add(files, file.Find(ConnectPathes(path, v), wildcard or "GAME"))
end
else
table.Add(files, file.Find(ConnectPathes(path, tostring(filter)), wildcard or "GAME"))
end
table.sort(files)
return files
end
local function NavigateToFolder(self, path)
if (!IsValid(self)) then return end
path = ConnectPathes(self.m_strRootPath, path)
local root = self.Tree:Root()
if (!IsValid(root)) then return end
if (!IsValid(root.ChildNodes)) then return end
local nodes = root.ChildNodes:GetChildren()
local lastnode = nil
local nodename = ""
self.NotUserPressed = true
local dirs = string.Explode("/", path)
for k, v in ipairs(dirs) do
if (nodename == "") then
nodename = string.lower(v)
else
nodename = nodename .. "/" .. string.lower(v)
if (!IsValid(lastnode)) then continue end
if (!IsValid(lastnode.ChildNodes)) then continue end
nodes = lastnode.ChildNodes:GetChildren()
end
local found = false
for _, node in pairs(nodes) do
if (!IsValid(node)) then continue end
local path = string.lower(node.m_strFolder)
if ( nodename == "" ) then break end
if ( path ~= nodename or found) then
node:SetExpanded(false)
continue
end
if (k == #dirs) then // just select the last one
self.Tree:SetSelectedItem(node)
end
node:SetExpanded(true)
lastnode = node
found = true
end
end
self.NotUserPressed = false
end
local function ShowFolder(self, path)
if (!IsValid(self)) then return end
self.m_strOpenPath = path
path = ConnectPathes(self.m_strRootPath, path)
self.oldpage = nil
self.Files = BuildFileList(path, self.m_tFilter, self.m_strWildCard)
self.m_nPage = 0
self.m_nPageCount = math.ceil(#self.Files / self.m_nMaxItemsPerPage)
self.PageMode = self.m_nPageCount > 1
self.PageChoosePanel:SetVisible(self.PageMode)
if (self.m_nPageCount <= 0 or !self.PageMode) then
self.m_nPageCount = 1
self:SetPage(1)
return
end
self.PageChooseNumbers:Clear(true)
self.PageChooseNumbers.Buttons = {}
for i=1, self.m_nPageCount do
self.PageChooseNumbers.Buttons[i] = self.PageChooseNumbers:Add("DButton")
local button = self.PageChooseNumbers.Buttons[i]
button:SetWide(self.PageButtonSize)
button:Dock(LEFT)
button:SetText(tostring(i))
button:SetVisible(false)
button:SetToolTip("Page " .. i .. " of " .. self.m_nPageCount)
button.DoClick = function(panel)
self:SetPage(i)
self:LayoutPages(true)
end
end
self:SetPage(1)
end
--[[---------------------------------------------------------
Name: Init
-----------------------------------------------------------]]
function PANEL:Init()
self.TimedpairsName = "wire_filebrowser_items_" .. tostring({})
self.PageButtonSize = 20
self:SetListSpeed(6)
self:SetMaxItemsPerPage(200)
self.m_nPageCount = 1
self.m_strOpenPath = nil
self.m_strOpenFile = nil
self.m_strOpenFilename = nil
self:SetDrawBackground(false)
self.FolderPathPanel = self:Add("DPanel")
self.FolderPathPanel:DockMargin(0, 0, 0, 3)
self.FolderPathPanel:SetTall(20)
self.FolderPathPanel:Dock(TOP)
self.FolderPathPanel:SetDrawBackground(false)
self.FolderPathText = self.FolderPathPanel:Add("DTextEntry")
self.FolderPathText:DockMargin(0, 0, 3, 0)
self.FolderPathText:Dock(FILL)
self.FolderPathText.OnEnter = function(panel)
self:SetOpenPath(panel:GetValue())
end
self.RefreshIcon = self.FolderPathPanel:Add("DImageButton") // The Folder Button.
self.RefreshIcon:SetImage("icon16/arrow_refresh.png")
self.RefreshIcon:SetWide(20)
self.RefreshIcon:Dock(RIGHT)
self.RefreshIcon:SetToolTip("Refresh")
self.RefreshIcon:SetStretchToFit(false)
self.RefreshIcon.DoClick = function()
self:Refresh()
end
self.FolderPathIcon = self.FolderPathPanel:Add("DImageButton") // The Folder Button.
self.FolderPathIcon:SetImage("icon16/folder_explore.png")
self.FolderPathIcon:SetWide(20)
self.FolderPathIcon:Dock(RIGHT)
self.FolderPathIcon:SetToolTip("Open Folder")
self.FolderPathIcon:SetStretchToFit(false)
self.FolderPathIcon.DoClick = function()
self.FolderPathText:OnEnter()
end
self.NotUserPressed = false
self.Tree = vgui.Create( "DTree" )
self.Tree:SetClickOnDragHover(false)
self.Tree.OnNodeSelected = function( parent, node )
local path = node.m_strFolder
if ( !path ) then return end
path = string.sub(path, #self.m_strRootPath+1)
path = string.Trim(path, "/")
if (!self.NotUserPressed) then
self.FolderPathText:SetText(path)
end
if (self.m_strOpenPath == path) then return end
ShowFolder(self, path)
end
self.PagePanel = vgui.Create("DPanel")
self.PagePanel:SetDrawBackground(false)
self.PageChoosePanel = self.PagePanel:Add("DPanel")
self.PageChoosePanel:DockMargin(0, 0, 0, 0)
self.PageChoosePanel:SetTall(self.PageButtonSize)
self.PageChoosePanel:Dock(BOTTOM)
self.PageChoosePanel:SetDrawBackground(false)
self.PageChoosePanel:SetVisible(false)
self.PageLastLeftButton = self.PageChoosePanel:Add("DButton")
self.PageLastLeftButton:SetWide(self.PageButtonSize)
self.PageLastLeftButton:Dock(LEFT)
self.PageLastLeftButton:SetText("<<")
self.PageLastLeftButton.DoClick = function(panel)
self:SetPage(1)
end
self.PageLastRightButton = self.PageChoosePanel:Add("DButton")
self.PageLastRightButton:SetWide(self.PageButtonSize)
self.PageLastRightButton:Dock(RIGHT)
self.PageLastRightButton:SetText(">>")
self.PageLastRightButton.DoClick = function(panel)
self:SetPage(self.m_nPageCount)
end
self.PageLeftButton = self.PageChoosePanel:Add("DButton")
self.PageLeftButton:SetWide(self.PageButtonSize)
self.PageLeftButton:Dock(LEFT)
self.PageLeftButton:SetText("<")
self.PageLeftButton.DoClick = function(panel)
if (self.m_nPage <= 1 or !self.PageMode) then
self.m_nPage = 1
return
end
self:SetPage(self.m_nPage - 1)
end
self.PageRightButton = self.PageChoosePanel:Add("DButton")
self.PageRightButton:SetWide(self.PageButtonSize)
self.PageRightButton:Dock(RIGHT)
self.PageRightButton:SetText(">")
self.PageRightButton.DoClick = function(panel)
if (self.m_nPage >= self.m_nPageCount or !self.PageMode) then
self.m_nPage = self.m_nPageCount
return
end
self:SetPage(self.m_nPage + 1)
end
self.PageChooseNumbers = self.PageChoosePanel:Add("DPanel")
self.PageChooseNumbers:DockMargin(0, 0, 0, 0)
self.PageChooseNumbers:SetSize(self.PageChoosePanel:GetWide()-60, self.PageChoosePanel:GetTall())
self.PageChooseNumbers:Center()
self.PageChooseNumbers:SetDrawBackground(false)
self.PageLoadingProgress = self.PagePanel:Add("DProgress")
self.PageLoadingProgress:DockMargin(0, 0, 0, 0)
self.PageLoadingProgress:SetTall(self.PageButtonSize)
self.PageLoadingProgress:Dock(BOTTOM)
self.PageLoadingProgress:SetVisible(false)
self.PageLoadingLabel = self.PageLoadingProgress:Add("DLabel")
self.PageLoadingLabel:SizeToContents()
self.PageLoadingLabel:Center()
self.PageLoadingLabel:SetText("")
self.PageLoadingLabel:SetPaintBackground(false)
self.PageLoadingLabel:SetDark(true)
self.List = self.PagePanel:Add( "DListView" )
self.List:Dock( FILL )
self.List:SetMultiSelect(false)
local Column = self.List:AddColumn("Name")
Column:SetMinWidth(150)
Column:SetWide(200)
self.List.OnRowSelected = function(parent, id, line)
local name = line.m_strFilename
local path = line.m_strPath
local file = line.m_strFile
self.m_strOpenFilename = name
self.m_strOpenFile = file
self:DoClick(file, path, name, parent, line)
end
self.List.DoDoubleClick = function(parent, id, line)
local name = line.m_strFilename
local path = line.m_strPath
local file = line.m_strFile
self.m_strOpenFilename = name
self.m_strOpenFile = file
self:DoDoubleClick(file, path, name, parent, line)
end
self.List.OnRowRightClick = function(parent, id, line)
local name = line.m_strFilename
local path = line.m_strPath
local file = line.m_strFile
self.m_strOpenFilename = name
self.m_strOpenFile = file
self:DoRightClick(file, path, name, parent, line)
end
self.SplitPanel = self:Add( "DHorizontalDivider" )
self.SplitPanel:Dock( FILL )
self.SplitPanel:SetLeft(self.Tree)
self.SplitPanel:SetRight(self.PagePanel)
self.SplitPanel:SetLeftWidth(200)
self.SplitPanel:SetLeftMin(150)
self.SplitPanel:SetRightMin(300)
self.SplitPanel:SetDividerWidth(3)
end
function PANEL:Refresh()
local file = self:GetOpenFile()
local page = self:GetPage()
self.bSetup = self:Setup()
self:SetOpenFile(file)
self:SetPage(page)
end
function PANEL:UpdatePageToolTips()
self.PageLeftButton:SetToolTip("Previous Page (" .. self.m_nPage - 1 .. " of " .. self.m_nPageCount .. ")")
self.PageRightButton:SetToolTip("Next Page (" .. self.m_nPage + 1 .. " of " .. self.m_nPageCount .. ")")
self.PageLastRightButton:SetToolTip("Last Page (" .. self.m_nPageCount .. " of " .. self.m_nPageCount .. ")")
self.PageLastLeftButton:SetToolTip("First Page (1 of " .. self.m_nPageCount .. ")")
end
function PANEL:LayoutPages(forcelayout)
if (!self.PageChoosePanel:IsVisible()) then
self.oldpage = nil
return
end
local x, y = self.PageRightButton:GetPos()
local Wide = x - self.PageLeftButton:GetWide()-40
if (Wide <= 0 or forcelayout) then
self.oldpage = nil
self:InvalidateLayout()
return
end
if (self.oldpage == self.m_nPage and self.oldpage and self.m_nPage) then return end
self.oldpage = self.m_nPage
if (self.m_nPage >= self.m_nPageCount) then
EnableButton(self.PageLeftButton, true)
EnableButton(self.PageRightButton, false)
EnableButton(self.PageLastLeftButton, true)
EnableButton(self.PageLastRightButton, false)
elseif (self.m_nPage <= 1) then
EnableButton(self.PageLeftButton, false)
EnableButton(self.PageRightButton, true)
EnableButton(self.PageLastLeftButton, false)
EnableButton(self.PageLastRightButton, true)
else
EnableButton(self.PageLeftButton, true)
EnableButton(self.PageRightButton, true)
EnableButton(self.PageLastLeftButton, true)
EnableButton(self.PageLastRightButton, true)
end
local ButtonCount = math.ceil(math.floor(Wide/self.PageButtonSize)/2)
local pagepos = math.Clamp(self.m_nPage, ButtonCount, self.m_nPageCount-ButtonCount+1)
local VisibleButtons = 0
for i=1, self.m_nPageCount do
local button = self.PageChooseNumbers.Buttons[i]
if (!IsValid(button)) then continue end
if (pagepos < i+ButtonCount and pagepos >= i-ButtonCount+1) then
button:SetVisible(true)
EnableButton(button, true)
VisibleButtons = VisibleButtons + 1
else
button:SetVisible(false)
EnableButton(button, false)
end
button.Depressed = false
end
local SelectButton = self.PageChooseNumbers.Buttons[self.m_nPage]
if (IsValid(SelectButton)) then
SelectButton.Depressed = true
SelectButton:SetMouseInputEnabled(false)
end
self.PageChooseNumbers:SetWide(VisibleButtons*self.PageButtonSize)
self.PageChooseNumbers:Center()
end
function PANEL:AddColumns(...)
local Column = {}
for k, v in ipairs({...}) do
Column[k] = self.List:AddColumn(v)
end
return Column
end
function PANEL:Think()
if (self.SplitPanel:GetDragging()) then
self.oldpage = nil
self:InvalidateLayout()
end
if ( !self.bSetup ) then
self.bSetup = self:Setup()
end
end
function PANEL:PerformLayout()
self:LayoutPages()
self.Tree:InvalidateLayout()
self.List:InvalidateLayout()
local minw = self:GetWide() - self.SplitPanel:GetRightMin() - self.SplitPanel:GetDividerWidth()
local oldminw = self.SplitPanel:GetLeftWidth(minw)
if (oldminw > minw) then
self.SplitPanel:SetLeftWidth(minw)
end
//Fixes scrollbar glitches on resize
self.Tree:OnMouseWheeled(0)
self.List:OnMouseWheeled(0)
if (!self.PageLoadingProgress:IsVisible()) then return end
self.PageLoadingLabel:SizeToContents()
self.PageLoadingLabel:Center()
end
function PANEL:Setup()
if (!self.m_strRootName) then return false end
if (!self.m_strRootPath) then return false end
WireLib.TimedpairsStop(self.TimedpairsName)
self.m_strOpenPath = nil
self.m_strOpenFile = nil
self.m_strOpenFilename = nil
self.oldpage = nil
self.Tree:Clear(true)
if (IsValid(self.Root)) then
self.Root:Remove()
end
self.Root = self.Tree.RootNode:AddFolder( self.m_strRootName, self.m_strRootPath, self.m_strWildCard or "GAME", false)
return true
end
function PANEL:SetOpenFilename(filename)
if(!isstring(filename)) then filename = "" end
self.m_strOpenFilename = filename
self.m_strOpenFile = ConnectPathes(self.m_strOpenPath, self.m_strOpenFilename)
end
function PANEL:SetOpenPath(path)
self.Root:SetExpanded(true)
path = PathFilter(path, self.FolderPathText, self.m_strRootPath) or ""
if (self.m_strOpenPath == path) then return end
self.oldpage = nil
NavigateToFolder(self, path)
self.m_strOpenPath = path
self.m_strOpenFile = ConnectPathes(self.m_strOpenPath, self.m_strOpenFilename)
end
function PANEL:SetOpenFile(file)
if(!isstring(file)) then file = "" end
self:SetOpenPath(string.GetPathFromFilename(file))
self:SetOpenFilename(string.GetFileFromFilename("/" .. file))
end
function PANEL:SetPage(page)
if (page < 1) then return end
if (page > self.m_nPageCount) then return end
if (page == self.m_nPage) then return end
WireLib.TimedpairsStop(self.TimedpairsName)
self.List:Clear(true)
self.m_nPage = page
self:UpdatePageToolTips()
local filepage
if(self.PageMode) then
filepage = {}
for i=1, self.m_nMaxItemsPerPage do
local index = i + self.m_nMaxItemsPerPage * (page - 1)
local value = self.Files[index]
if (!value) then break end
filepage[i] = value
end
else
filepage = self.Files
end
local Fraction = 0
local FileCount = #filepage
local ShowProgress = (FileCount > self.m_nListSpeed * 5)
self.PageLoadingProgress:SetVisible(ShowProgress)
if (FileCount <= 0) then
self.PageLoadingProgress:SetVisible(false)
return
end
self.PageLoadingProgress:SetFraction(Fraction)
self.PageLoadingLabel:SetText("0 of " .. FileCount .. " files found.")
self.PageLoadingLabel:SizeToContents()
self.PageLoadingLabel:Center()
self:InvalidateLayout()
WireLib.Timedpairs(self.TimedpairsName, filepage, self.m_nListSpeed, function(id, name, self)
if (!IsValid(self)) then return false end
if (!IsValid(self.List)) then return false end
local file = ConnectPathes(self.m_strOpenPath, name)
local args, bcontinue, bbreak = self:LineData(id, file, self.m_strOpenPath, name)
if (bcontinue) then return end // continue
if (bbreak) then return false end // break
local line = self.List:AddLine(name, unpack(args or {}))
if (!IsValid(line)) then return end
line.m_strPath = self.m_strOpenPath
line.m_strFilename = name
line.m_strFile = file
if (self.m_strOpenFile == file) then
self.List:SelectItem(line)
end
self:OnLineAdded(id, line, file, self.m_strOpenPath, name)
Fraction = id / FileCount
if (!IsValid(self.PageLoadingProgress)) then return end
if (!ShowProgress) then return end
self.PageLoadingProgress:SetFraction(Fraction)
self.PageLoadingLabel:SetText(id .. " of " .. FileCount .. " files found.")
self.PageLoadingLabel:SizeToContents()
self.PageLoadingLabel:Center()
end, function(id, name, self)
if (!IsValid(self)) then return end
Fraction = 1
if (!IsValid(self.PageLoadingProgress)) then return end
if (!ShowProgress) then return end
self.PageLoadingProgress:SetFraction(Fraction)
self.PageLoadingLabel:SetText(id .. " of " .. FileCount .. " files found.")
self.PageLoadingLabel:SizeToContents()
self.PageLoadingLabel:Center()
self.PageLoadingProgress:SetVisible(false)
self:InvalidateLayout()
end, self)
end
function PANEL:DoClick(file, path, name)
-- Override
end
function PANEL:DoDoubleClick(file, path, name)
-- Override
end
function PANEL:DoRightClick(file, path, name)
-- Override
end
function PANEL:LineData(id, file, path, name)
return // to override
end
function PANEL:OnLineAdded(id, line, file, path, name)
return // to override
end
vgui.Register("wire_filebrowser", PANEL, "DPanel")
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Port_Jeuno/npcs/Purequane.lua | 3 | 1367 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Purequane
-- @zone 246
-- !pos -76 8 54
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then
player:startEvent(0x0026);
else
player:startEvent(0x002e);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0026) then
Z = player:getZPos();
if (Z >= 58 and Z <= 61) then
player:delGil(200);
end
end
end; | gpl-3.0 |
rudolfmleziva/AdministratorTeritorial | cocos2d/cocos/scripting/lua-bindings/auto/api/LayerColor.lua | 10 | 1484 |
--------------------------------
-- @module LayerColor
-- @extend Layer,BlendProtocol
-- @parent_module cc
--------------------------------
-- change width and height in Points<br>
-- since v0.8
-- @function [parent=#LayerColor] changeWidthAndHeight
-- @param self
-- @param #float w
-- @param #float h
--------------------------------
-- change height in Points
-- @function [parent=#LayerColor] changeHeight
-- @param self
-- @param #float h
--------------------------------
-- change width in Points
-- @function [parent=#LayerColor] changeWidth
-- @param self
-- @param #float w
--------------------------------
-- @overload self, color4b_table, float, float
-- @overload self
-- @overload self, color4b_table
-- @function [parent=#LayerColor] create
-- @param self
-- @param #color4b_table color
-- @param #float width
-- @param #float height
-- @return LayerColor#LayerColor ret (return value: cc.LayerColor)
--------------------------------
--
-- @function [parent=#LayerColor] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
--------------------------------
--
-- @function [parent=#LayerColor] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#LayerColor] setContentSize
-- @param self
-- @param #size_table var
return nil
| gpl-3.0 |
hmandal/loadcaffe | loadcaffe.lua | 3 | 1277 | local ffi = require 'ffi'
local C = loadcaffe.C
loadcaffe.load = function(prototxt_name, binary_name, backend)
local backend = backend or 'nn'
local handle = ffi.new('void*[1]')
-- loads caffe model in memory and keeps handle to it in ffi
local old_val = handle[1]
C.loadBinary(handle, prototxt_name, binary_name)
if old_val == handle[1] then return end
-- transforms caffe prototxt to torch lua file model description and
-- writes to a script file
local lua_name = prototxt_name..'.lua'
C.convertProtoToLua(handle, lua_name, backend)
-- executes the script, defining global 'model' module list
local model = dofile(lua_name)
-- goes over the list, copying weights from caffe blobs to torch tensor
local net = nn.Sequential()
local list_modules = model
for i,item in ipairs(list_modules) do
if item[2].weight then
local w = torch.FloatTensor()
local bias = torch.FloatTensor()
C.loadModule(handle, item[1], w:cdata(), bias:cdata())
if backend == 'ccn2' then
w = w:permute(2,3,4,1)
end
item[2].weight:copy(w)
item[2].bias:copy(bias)
end
net:add(item[2])
end
C.destroyBinary(handle)
if backend == 'cudnn' or backend == 'ccn2' then
net:cuda()
end
return net
end
| bsd-2-clause |
RebootRevival/FFXI_Test | scripts/zones/Aht_Urhgan_Whitegate/npcs/Dkhaaya.lua | 3 | 2519 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Dkhaaya
-- Type: Standard NPC
-- !pos -73.212 -1 -5.842 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local olduumQuest = player:getQuestStatus(AHT_URHGAN, OLDUUM);
local ringCheck = player:hasItem(2217);
if (olduumQuest == QUEST_AVAILABLE) then
player:startEvent(0x004);
elseif (player:hasKeyItem(ELECTROLOCOMOTIVE) or player:hasKeyItem(ELECTROPOT) or player:hasKeyItem(ELECTROCELL) and ringCheck == false) then
if (olduumQuest == QUEST_ACCEPTED) then
player:startEvent(0x006);
else
player:startEvent(0x008);
end
elseif (olduumQuest ~= QUEST_AVAILABLE and ringCheck == false) then
player:startEvent(0x005);
else
player:startEvent(0x007);
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 == 0x004) then
player:addKeyItem(DKHAAYAS_RESEARCH_JOURNAL);
player:messageSpecial(KEYITEM_OBTAINED, DKHAAYAS_RESEARCH_JOURNAL);
player:addQuest(AHT_URHGAN, OLDUUM);
elseif (csid == 0x006 or csid == 0x008) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(2217);
player:messageSpecial(ITEM_OBTAINED, 2217);
player:delKeyItem(DKHAAYAS_RESEARCH_JOURNAL);
player:delKeyItem(ELECTROLOCOMOTIVE);
player:delKeyItem(ELECTROPOT);
player:delKeyItem(ELECTROCELL);
if (csid == 0x006) then
player:completeQuest(AHT_URHGAN, OLDUUM);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 2217);
end
end
end;
| gpl-3.0 |
zzh442856860/skynet | test/testredis2.lua | 82 | 1043 | local skynet = require "skynet"
local redis = require "redis"
local db
function add1(key, count)
local t = {}
for i = 1, count do
t[2*i -1] = "key" ..i
t[2*i] = "value" .. i
end
db:hmset(key, table.unpack(t))
end
function add2(key, count)
local t = {}
for i = 1, count do
t[2*i -1] = "key" ..i
t[2*i] = "value" .. i
end
table.insert(t, 1, key)
db:hmset(t)
end
function __init__()
db = redis.connect {
host = "127.0.0.1",
port = 6300,
db = 0,
auth = "foobared"
}
print("dbsize:", db:dbsize())
local ok, msg = xpcall(add1, debug.traceback, "test1", 250000)
if not ok then
print("add1 failed", msg)
else
print("add1 succeed")
end
local ok, msg = xpcall(add2, debug.traceback, "test2", 250000)
if not ok then
print("add2 failed", msg)
else
print("add2 succeed")
end
print("dbsize:", db:dbsize())
print("redistest launched")
end
skynet.start(__init__)
| mit |
abbasgh12345/extremenew2 | plugins/location.lua | 93 | 1704 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
ciufciuf57/nodemcu-firmware | lua_examples/yet-another-dht22.lua | 65 | 2195 | ------------------------------------------------------------------------------
-- DHT11/22 query module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
--
-- Example:
-- print("DHT11", dofile("dht22.lua").read(4))
-- print("DHT22", dofile("dht22.lua").read(4, true))
-- NB: the very first read sometimes fails
------------------------------------------------------------------------------
local M
do
-- cache
local gpio = gpio
local val = gpio.read
local waitus = tmr.delay
--
local read = function(pin, dht22)
-- wait for pin value
local w = function(v)
local c = 255
while c > 0 and val(pin) ~= v do c = c - 1 end
return c
end
-- NB: we preallocate incoming data buffer
-- or precise timing in reader gets broken
local b = { 0, 0, 0, 0, 0 }
-- kick the device
gpio.mode(pin, gpio.INPUT, gpio.PULLUP)
gpio.write(pin, 1)
waitus(10)
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, 0)
waitus(20000)
gpio.write(pin, 1)
gpio.mode(pin, gpio.INPUT, gpio.PULLUP)
-- wait for device presense
if w(0) == 0 or w(1) == 0 or w(0) == 0 then
return nil, 0
end
-- receive 5 octets of data, msb first
for i = 1, 5 do
local x = 0
for j = 1, 8 do
x = x + x
if w(1) == 0 then return nil, 1 end
-- 70us for 1, 27 us for 0
waitus(30)
if val(pin) == 1 then
x = x + 1
if w(0) == 0 then return nil, 2 end
end
end
b[i] = x
end
-- check crc. NB: calculating in receiver loop breaks timings
local crc = 0
for i = 1, 4 do
crc = (crc + b[i]) % 256
end
if crc ~= b[5] then return nil, 3 end
-- convert
local t, h
-- DHT22: values in tenths of unit, temperature can be negative
if dht22 then
h = b[1] * 256 + b[2]
t = b[3] * 256 + b[4]
if t > 0x8000 then t = -(t - 0x8000) end
-- DHT11: no negative temperatures, only integers
-- NB: return in 0.1 Celsius
else
h = 10 * b[1]
t = 10 * b[3]
end
return t, h
end
-- expose interface
M = {
read = read,
}
end
return M
| mit |
padrinoo1/telegeek | plugins/cpu.lua | 244 | 1893 | function run_sh(msg)
name = get_name(msg)
text = ''
-- if config.sh_enabled == false then
-- text = '!sh command is disabled'
-- else
-- if is_sudo(msg) then
-- bash = msg.text:sub(4,-1)
-- text = run_bash(bash)
-- else
-- text = name .. ' you have no power here!'
-- end
-- end
if is_sudo(msg) then
bash = msg.text:sub(4,-1)
text = run_bash(bash)
else
text = name .. ' you have no power here!'
end
return text
end
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function on_getting_dialogs(cb_extra,success,result)
if success then
local dialogs={}
for key,value in pairs(result) do
for chatkey, chat in pairs(value.peer) do
print(chatkey,chat)
if chatkey=="id" then
table.insert(dialogs,chat.."\n")
end
if chatkey=="print_name" then
table.insert(dialogs,chat..": ")
end
end
end
send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false)
end
end
function run(msg, matches)
if not is_sudo(msg) then
return "You aren't allowed!"
end
local receiver = get_receiver(msg)
if string.match(msg.text, '!sh') then
text = run_sh(msg)
send_msg(receiver, text, ok_cb, false)
return
end
if string.match(msg.text, '!$ uptime') then
text = run_bash('uname -snr') .. ' ' .. run_bash('whoami')
text = text .. '\n' .. run_bash('top -b |head -2')
send_msg(receiver, text, ok_cb, false)
return
end
if matches[1]=="Get dialogs" then
get_dialog_list(on_getting_dialogs,{get_receiver(msg)})
return
end
end
return {
description = "shows cpuinfo",
usage = "!$ uptime",
patterns = {"^!$ uptime", "^!sh","^Get dialogs$"},
run = run
}
| gpl-2.0 |
liwenzhong/Atlas | lib/histogram.lua | 40 | 5165 | --[[ $%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 tokenizer = require("proxy.tokenizer")
local parser = require("proxy.parser")
local commands = require("proxy.commands")
local auto_config = require("proxy.auto-config")
-- init global counters
if not proxy.global.config.histogram then
proxy.global.config.histogram = {
collect_queries = true,
collect_tables = true
}
end
-- init query counters
if not proxy.global.norm_queries then
proxy.global.norm_queries = { }
end
-- init table-usage
if not proxy.global.tables then
proxy.global.tables = { }
end
function read_query(packet)
local cmd = commands.parse(packet)
local r = auto_config.handle(cmd)
if r then return r end
if cmd.type == proxy.COM_QUERY then
local tokens = assert(tokenizer.tokenize(cmd.query))
local norm_query = tokenizer.normalize(tokens)
-- print("normalized query: " .. norm_query)
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_LONG,
name = "max_query_time" },
{ type = proxy.MYSQL_TYPE_FLOAT,
name = "avg_query_time" },
}
}
}
local rows = {}
if proxy.global.norm_queries then
for k, v in pairs(proxy.global.norm_queries) do
rows[#rows + 1] = {
k,
v.count,
v.max_query_time,
v.avg_query_time,
}
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.norm_queries = {}
return proxy.PROXY_SEND_RESULT
elseif norm_query == "SELECT * FROM `histogram` . `tables` " then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING,
name = "table" },
{ type = proxy.MYSQL_TYPE_LONG,
name = "reads" },
{ type = proxy.MYSQL_TYPE_LONG,
name = "writes" },
}
}
}
local rows = {}
if proxy.global.tables then
for k, v in pairs(proxy.global.tables) do
rows[#rows + 1] = {
k,
v.reads,
v.writes,
}
end
end
proxy.response.resultset.rows = rows
return proxy.PROXY_SEND_RESULT
elseif norm_query == "DELETE FROM `histogram` . `tables` " then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
proxy.global.tables = {}
return proxy.PROXY_SEND_RESULT
end
if proxy.global.config.histogram.collect_queries or
proxy.global.config.histogram.collect_tables then
proxy.queries:append(1, packet)
return proxy.PROXY_SEND_QUERY
end
end
end
function read_query_result(inj)
local cmd = commands.parse(inj.query)
if cmd.type == proxy.COM_QUERY then
local tokens = assert(tokenizer.tokenize(cmd.query))
local norm_query = tokenizer.normalize(tokens)
if proxy.global.config.histogram.collect_queries then
if not proxy.global.norm_queries[norm_query] then
proxy.global.norm_queries[norm_query] = {
count = 0,
max_query_time = 0,
avg_query_time = 0
}
end
-- set new max if necessary
if inj.query_time > proxy.global.norm_queries[norm_query].max_query_time then
proxy.global.norm_queries[norm_query].max_query_time = inj.query_time
end
-- build rolling average
proxy.global.norm_queries[norm_query].avg_query_time =
((proxy.global.norm_queries[norm_query].avg_query_time * proxy.global.norm_queries[norm_query].count) +
inj.query_time) / (proxy.global.norm_queries[norm_query].count + 1)
proxy.global.norm_queries[norm_query].count = proxy.global.norm_queries[norm_query].count + 1
end
if proxy.global.config.histogram.collect_tables then
-- extract the tables from the queries
tables = parser.get_tables(tokens)
for table, qtype in pairs(tables) do
if not proxy.global.tables[table] then
proxy.global.tables[table] = {
reads = 0,
writes = 0
}
end
if qtype == "read" then
proxy.global.tables[table].reads = proxy.global.tables[table].reads + 1
else
proxy.global.tables[table].writes = proxy.global.tables[table].writes + 1
end
end
end
end
end
| gpl-2.0 |
gowadbd/DevDroid | plugins/ar-plugins.lua | 7 | 6398 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ☑️ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '☑️'
end
nact = nact+1
end
if not only_enabled or status == '☑️' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\n الملفات المثبته 🔨 '..nsum..'\nالملفات المفعله ️☑️'..nact..'\nغير مفعل ❌ '..nsum-nact..''
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ☑️ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '☑️'
end
nact = nact+1
end
if not only_enabled or status == '☑️' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'الملف 📁'..plugin_name..'مفعل ☑️'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return ''..plugin_name..'❌ لا يوجد ⚠️ ملف 📁 باسم'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return ''..name..'❌ لا يوجد ⚠️ ملف 📁 باسم '
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return '📁 الملف'..name..'❌ غير مفعل ⚠️👍'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == 'الملفات' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'تفعيل ملف' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'تفعيل ملف' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'تعطيل ملف' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'تعطيل ملف' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'الملفات المفعله' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^الملفات$",
"^(تفعيل ملف) ([%w_%.%-]+)$",
"^(تعطيل ملف) ([%w_%.%-]+)$",
"^(تفعيل ملف) ([%w_%.%-]+) (chat)",
"^(تعطيل ملف) ([%w_%.%-]+) (chat)",
"^(الملفات المفعله)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
luochen1990/smart-bot | src/st_30_swarm.lua | 1 | 30051 | ------------------------------ swarm server state ------------------------------
mkTaskInfo = function(opts) -- not used yet
local t = {
["type"] = opts.type,
workArea = opts.workArea,
beginPos = opts.beginPos,
estCost = opts.estCost,
requiredTools = opts.requiredTools,
command = opts.command,
state = "queuing",
createdTime = now(),
beginTime = nil,
workerId = nil,
}
assert(t.type and t.beginPos and t.estCost and t.command, "mkTaskInfo(opts) lack required field")
return t
end
mkStationInfo = function(opts)
local s = {
role = opts.role, --NOTE: role field is not very useful, just for display
pos = opts.pos,
dir = opts.dir,
deliverBar = opts.deliverBar,
deliverPriority = opts.deliverPriority,
restockBar = opts.restockBar,
restockPriority = opts.restockPriority,
itemType = opts.itemType,
itemStackLimit = opts.itemStackLimit,
stationHosterId = opts.stationHosterId,
-- states
itemCount = opts.itemCount or 0,
delivering = 0,
restocking = 0,
isVisiting = default(false)(opts.isVisiting),
currentQueueLength = default(0)(opts.currentQueueLength),
maxQueueLength = default(5)(opts.maxQueueLength),
--latestCheckTime = now() - 100,
}
assert(s.pos and ((s.deliverBar and s.deliverPriority) or (s.restockBar and s.restockPriority)), "[mkStationInfo(opts)] lacks required field")
assert(not (s.deliverBar and s.restockBar) or (s.deliverBar >= s.restockBar), "[mkStationInfo(opts)] expect s.deliverBar >= s.restockBar")
return s
end
mkWorkerInfo = function(opts) -- not used yet
local w = {
id = opts.id,
latestPos = nil,
latestReportTime = nil,
state = "idle", -- or "busy" or "interrapt"
}
return w
end
swarm = {}
swarm.config = {
asFuel = {"minecraft:charcoal", "minecraft:white_carpet"},
}
swarm._state = {
stationPool = {},
workerPool = {},
jobPool = {},
}
-------------------------------- telnet service --------------------------------
--telnetServerCo = function(ignoreDeposit)
-- local eventQueue = {}
-- local listenCo = function()
-- while true do
-- --printC(colors.gray)("[telnet] listening")
-- local senderId, msg, _ = rednet.receive("telnet")
-- --printC(colors.gray)("[telnet] received from " .. senderId .. ": " .. msg)
-- local queueTail = #eventQueue + 1
-- if ignoreDeposit then queueTail = 1 end
-- eventQueue[queueTail] = {senderId, msg}
-- end
-- end
-- local execCo = function()
-- local sleepInterval = 1
-- while true do
-- if #eventQueue == 0 then
-- sleepInterval = math.min(0.5, sleepInterval * 1.1)
-- --printC(colors.gray)("[telnet] waiting "..sleepInterval)
-- sleep(sleepInterval)
-- else -- if #eventQueue > 0 then
-- --printC(colors.gray)("[telnet] executing "..#eventQueue)
-- sleepInterval = 0.02
-- local sender, msg = unpack(table.remove(eventQueue, 1))
-- printC(colors.gray)("[telnet] exec cmd from " .. sender .. ": " .. msg)
-- if msg == "exit" then break end
-- func, err = load("return "..msg, "telnet_cmd", "t", _ENV)
-- if func then
-- ok, res = pcall(func)
-- if ok then
-- printC(colors.green)(res)
-- else
-- printC(colors.yellow)(res)
-- end
-- else
-- printC(colors.orange)(err)
-- end
-- end
-- end
-- end
-- parallel.waitForAny(listenCo, execCo)
--end
--------------------------------- swarm service --------------------------------
swarm._startService = (function()
local serviceCo = rpc.buildServer("swarm", "queuing", function(msg)
return safeEval(msg) --TODO: set proper env
end)
local findCarrierTask = function(itemType, pool)
local providers, requesters = {}, {}
for _, station in pairs(pool) do
local cnt = station.itemCount + station.restocking - station.delivering
log.verb("station: "..literal(station.role, station.itemType, station.itemCount, station.pos))
if station.restockPriority and cnt < station.restockBar then
local intent = station.deliverBar - cnt
local info = {pos = station.pos, dir = station.dir, intent = intent, priority = station.restockPriority}
table.insert(requesters, info)
end
if station.deliverPriority and cnt > station.deliverBar then
local intent = cnt - station.restockBar
local info = {pos = station.pos, dir = station.dir, intent = intent, priority = station.deliverPriority}
table.insert(providers, info)
end
end
if #providers == 0 or #requesters == 0 then
return false, "got "..(#providers).." providers and "..(#requesters).." requesters, no task found"
end
local cmp = comparator(field("priority"), field("intent"))
table.sort(providers, cmp)
table.sort(requesters, cmp)
local provider = providers[1]
local requester = requesters[1]
local priority = math.max(requester.priority, provider.priority)
if not (priority > 0) then
return false, "got provider with priority "..provider.priority.." and requester with priority "..requester.priority..", no task found"
end
local intent = math.min(provider.intent, requester.intent)
local capacity = pool[show(provider.pos)].itemStackLimit * const.turtle.backpackSlotsNum * 0.75
local task = {
provider = provider,
requester = requester,
itemCount = math.min(capacity, intent),
itemType = itemType,
}
return true, task
end
local daemonCo = function()
local carrierClient = rpc.buildClient("swarm-carrier")
sleep(20)
printC(colors.gray)("begin finding carrier task...")
while true do
for itemType, pool in pairs(swarm._state.stationPool) do
printC(colors.gray)("finding task for "..literal(itemType))
local ok, task = findCarrierTask(itemType, pool)
if ok then
printC(colors.green)("found task:", literal(task))
local carriers = carrierClient.broadcast("isIdle(), workState.pos")()
printC(colors.lime)('carriers:', literal(carriers)) -- r like {id, ok, {isIdle, pos}}
local candidates = {}
for _, r in ipairs(carriers) do
if r[2] and r[3][1] then
table.insert(candidates, {id = r[1], pos = r[3][2]})
end
end
if #candidates > 0 then
local cmpDis = function(c) return vec.manhat(c.pos - task.provider.pos) end
table.sort(candidates, comparator(cmpDis))
local carrierId = candidates[1].id
local taskResult = { carrierClient.send("carry("..literal(task.provider, task.requester, task.itemCount, task.itemType)..")()", 1000, carrierId)() }
printC(colors.lime)("Task done: ", literal(taskResult))
sleep(5)
else
printC(colors.gray)("no carrier available")
end
else
local msg = task
printC(colors.yellow)(msg)
end
end
printC(colors.gray)("finished a round...")
sleep(20)
end
end
return para_(serviceCo, daemonCo)
end)()
--swarm._startService = function()
-- local eventQueue = {}
-- local listenCo = function()
-- rednet.host("swarm", "server")
-- while true do
-- printC(colors.gray)("[swarm] listening")
-- local senderId, msg, _ = rednet.receive("swarm-service")
-- printC(colors.gray)("[swarm] received from " .. senderId .. ": " .. msg)
-- table.insert(eventQueue, {senderId, msg})
-- end
-- end
-- local execCo = function()
-- local sleepInterval = 1
-- while true do
-- if #eventQueue == 0 then
-- sleepInterval = math.min(0.5, sleepInterval * 1.1)
-- --printC(colors.gray)("[swarm] waiting "..sleepInterval)
-- sleep(sleepInterval)
-- else -- if #eventQueue > 0 then
-- --printC(colors.gray)("[swarm] executing "..#eventQueue)
-- sleepInterval = 0.02
-- local requesterId, msg = unpack(table.remove(eventQueue, 1))
-- printC(colors.gray)("[swarm] exec cmd from " .. requesterId .. "")
-- if msg == "exit" then
-- break
-- end
-- local ok, res = eval(msg)
-- local resp
-- if ok then
-- resp = literal(true, res)
-- printC(colors.green)("[swarm] response to " .. requesterId .. ": " .. resp)
-- else
-- resp = literal(false, res.msg)
-- printC(colors.yellow)("[swarm] response to " .. requesterId .. ": " .. resp)
-- end
-- rednet.send(requesterId, resp, "swarm-response")
-- end
-- end
-- end
-- parallel.waitForAny(listenCo, execCo)
--end
swarm.services = {}
swarm.services.registerStation = function(opts)
if not opts.pos then
return false, "station pos is required"
end
local station = mkStationInfo(opts)
local itemTy = opts.itemType
if not itemTy then
return false, "station itemType is required"
end
swarm._state.stationPool[itemTy] = default({})(swarm._state.stationPool[itemTy])
swarm._state.stationPool[itemTy][show(station.pos)] = station
return true, "station registered"
end
swarm.services.updateStation = function(opts)
if not opts.itemType or not opts.pos then
return false, "station pos and itemType is required"
end
local pool = swarm._state.stationPool[opts.itemType]
if not pool then
return false, "station not exist (no such type)"
end
local station = pool[show(opts.pos)]
if not station then
return false, "station not exist (no such pos)"
end
for k, v in pairs(opts) do
station[k] = v
end
return true, "station updated"
end
swarm.services.unregisterStation = function(st)
if not st.itemType or not st.pos then
return false, "station pos and itemType is required"
end
local pool = swarm._state.stationPool[st.itemType]
if pool then
pool[show(st.pos)] = nil
end
return true, "done"
end
swarm.services.requestStation = function(itemType, itemCount, startPos, fuelLeft)
local pool = swarm._state.stationPool[itemType]
if not pool then
return false, "no such station registered, please register one"
end
if type(itemCount) ~= "number" then
return false, "bad request, please provide itemCount as number"
end
if not vec.isVec(startPos) then
return false, "bad request, please provide startPos as vec"
end
if type(fuelLeft) ~= "number" then
return false, "bad request, please provide fuelLeft as number"
end
-- [[
-- There is three dimention to compare station choices:
-- 1. distance: |--->
-- 2. item count: --->|
-- 3. queue time: |--->#
--
-- (Tips about the axis:
-- * left to right, worst to best
-- * `|` is a basic bar, which means this dimention good enough to this point is required
-- * `#` is a significant bar, which means this dimention good enough to this point will make significant difference
-- )
--
-- the distance dimention has one bar, which means if farer than this distance, then fuelLeft is not enough
-- the item count dimention has one bar, which means the item count is enough for the request
-- the queue time dimention has two bar, first means the queue is full, second means the queue is empty
--
-- Our strategy is that:
-- * if all basic bar can be reached, then we try to reach more (weighted) significant bar;
-- * if not, return fail;
-- ]]
-- boolean conditions
local nearer = function(pos1, pos2) return vec.manhat(pos1 - startPos) < vec.manhat(pos2 - startPos) end
local nearEnough = function(st) return vec.manhat(st.pos - startPos) * 2 <= fuelLeft end
local itemEnough = function(st) if itemCount >= 0 then return st.itemCount >= itemCount else return st.itemCount < itemCount end end
local queueNotFull = function(st) return st.currentQueueLength < st.maxQueueLength end
-- number conditions
local dist = function(st) return vec.manhat(st.pos - startPos) end
local queEmpty = function(st) if st.currentQueueLength == 0 and st.isVisiting == false then return 0 else return 1 end end
local que = function(st) if st.isVisiting == false then return st.currentQueueLength else return st.currentQueueLength + 1 end end
--
local better = comparator(queEmpty, dist, que)
local best
for _, st in pairs(swarm._state.stationPool[itemType]) do
if nearEnough(st) and itemEnough(st) and queueNotFull(st) then
if best == nil or better(st, best) then
best = st
end
end
end
if best then
return true, best
end
return false, "no proper station now, please try latter"
end
swarm.services.requestFuelStation = function(nStep, startPos, fuelLeft)
for _, name in ipairs(swarm.config.asFuel) do
local count = math.ceil(nStep / const.fuelHeatContent[name])
local ok, res = swarm.services.requestStation(name, count, startPos, fuelLeft)
if ok then
return true, st
end
end
return false, "no fuel station available, swarm.config.asFuel = "..literal(swarm.config.asFuel)
end
--------------------------------- swarm client ---------------------------------
---- | build a service, returns an IO to start the service
---- , serviceName is for service lookup
---- , listenProtocol is for request receiving
---- , handler is a function like `function(unwrappedMsg) return ok, res end`
--rpc.buildService = function(serviceName, listenProtocol, handler, logger)
-- handler = default(safeEval)(handler)
-- logger = default({
-- --verb = function(msg) printC(colors.gray)("["..serviceName.."] "..msg) end
-- verb = function(msg) end
-- info = function(msg) printC(colors.gray)("["..serviceName.."] "..msg) end
-- succ = function(msg) printC(colors.green)("["..serviceName.."] "..msg) end
-- fail = function(msg) printC(colors.yellow)("["..serviceName.."] "..msg) end
-- warn = function(msg) printC(colors.orange)("["..serviceName.."] "..msg) end
-- })(logger)
-- local eventQueue = {}
-- local listenCo = function()
-- rednet.host(serviceName, "server")
-- while true do
-- logger.info("listening on "..literal(listenProtocol))
-- local senderId, rawMsg, _ = rednet.receive(listenProtocol)
-- logger.info("received from " .. senderId .. ": " .. rawMsg)
-- table.insert(eventQueue, {senderId, msg})
-- end
-- end
-- local handleCo = function()
-- local sleepInterval = 1
-- while true do
-- if #eventQueue == 0 then
-- sleepInterval = math.min(0.5, sleepInterval * 1.1)
-- logger.verb("waiting "..sleepInterval)
-- sleep(sleepInterval)
-- else -- if #eventQueue > 0 then
-- logger.verb("handling "..#eventQueue)
-- sleepInterval = 0.02
-- local requesterId, msg = unpack(table.remove(eventQueue, 1))
-- logger.info("exec cmd from " .. requesterId .. "")
--
-- local resp
--
-- local ok1, res1 = safeEval(rawMsg)
-- if not ok1 then
-- resp = literal(false, res.msg)
-- logger.fail("response to " .. requesterId .. ": " .. resp)
-- else
-- local responseProtocol, msg = unpack(res1)
--
-- local ok2, res = handler(msg)
-- if not ok2 then
-- resp = literal(false, res.msg)
-- logger.fail("response to " .. requesterId .. ": " .. resp)
-- else
-- resp = literal(true, res)
-- logger.succ("response to " .. requesterId .. ": " .. resp)
-- end
-- end
-- rednet.send(requesterId, resp, responseProtocol)
-- end
-- end
-- end
-- parallel.waitForAny(listenCo, handleCo)
--end
swarm.client = rpc.buildClient("swarm")
--_request = (function()
-- local _request_counter = 0
--
-- return function(swarmServerId, msg, requestProtocol, timeout)
-- local responseProtocol = requestProtocol .. "_R" .. (_request_counter)
-- _request_counter = (_request_counter + 1) % 1000
-- rednet.send(swarmServerId, literal(responseProtocol, msg), requestProtocol)
-- while true do
-- local responserId, resp = rednet.receive(responseProtocol, timeout) --TODO: reduce timeout in next loop?
-- if responserId == swarmServerId then
-- return true, resp
-- elseif not responserId then
-- return false, "request timeout"
-- else
-- log.warn("[_request] weird, send to "..swarmServerId.." but got response from "..responserId..", are we under attack?")
-- end
-- end
-- end
--end)()
--_requestSwarm = function(cmd, totalTimeout)
-- totalTimeout = default(2)(totalTimeout)
--
-- local _naiveRequestSwarm = function(timeout)
-- return mkIO(function()
-- if not workState.swarmServerId then
-- local serverId = rednet.lookup("swarm", "server")
-- if not serverId then
-- return false, "swarm server not found"
-- end
-- workState.swarmServerId = serverId
-- end
-- -- got workState.swarmServerId
--
-- local reqSucc, resp = _request(workState.swarmServerId, cmd, "swarm-service", timeout)
-- if not reqSucc then -- timeout or network error
-- workState.swarmServerId = nil
-- return false, resp
-- end
-- -- got resp
--
-- local ok, res = eval(resp)
-- if not ok then
-- log.bug("[_requestSwarm] faild to parse response: ", literal({cmd = cmd, response = res}))
-- return false, "faild to parse response"
-- end
-- -- got res
--
-- return unpack(res)
-- end)
-- end
--
-- return retryWithTimeout(totalTimeout)(_naiveRequestSwarm)()
--end
---- | interactive register complex station
--registerStation = mkIOfn(function()
--end)
--registerPassiveProvider = mkIO(function()
-- reserveOneSlot()
-- select(slot.isEmpty)()
-- suck(1)()
-- local det = turtle.getItemDetail()
-- drop(1)()
-- if not det then
-- log.bug("[registerPassiveProvider] cannot get item detail")
-- return false
-- end
-- local stationDef = {
-- pos = workState.pos,
-- dir = workState:aimingDir(),
-- itemType = det.name,
-- --restockBar = 0,
-- deliverBar = 0,
-- deliverPriority = 0, --passive provider
-- }
-- return swarm.client.request("swarm.services.registerStation("..literal(stationDef)..")")()
--end)
--serveAsFuelStation = mkIO(function()
--end)
_updateInventoryCo = function(stationDef)
local inventoryCount = {
isDirty = true,
lastReport = stationDef.itemCount,
}
local checkCo = function()
while true do
local ev = { os.pullEvent("turtle_inventory") } -- no useful information :(
inventoryCount.isDirty = true
end
end
local updateCo = function()
local info = {
pos = stationDef.pos,
dir = stationDef.dir,
itemType = stationDef.itemType,
}
while true do
sleep(5)
if inventoryCount.isDirty then
local cnt = slot.count(stationDef.itemType)
if cnt ~= inventoryCount.lastReport then
print(os.time().." current count: "..cnt)
info.itemCount = cnt
local ok, res = swarm.client.request("swarm.services.updateStation("..literal(info)..")")()
if ok then
inventoryCount.isDirty = false
printC(colors.green)("itemCount reported: "..info.itemCount)
else
log.warn("("..stationDef.itemType..") failed to report inventory info: "..literal(res))
end
end
end
end
end
return para_(checkCo, updateCo) -- return IO
end
serveAsProvider = mkIO(function()
local getAndHold
if isContainer() then -- suck items from chest
getAndHold = function(n) return suckHold(n) end
else -- dig or attack --TODO: check tool
getAndHold = function(n) return (isContainer * suckHold(n) + -isContainer * (digHold + try(attack) * suckHold(n))) end
end
local stationDef = {
role = "provider",
pos = workState.pos - workState:aimingDir(),
dir = workState:aimingDir(),
itemType = nil,
itemStackLimit = nil,
restockBar = const.turtle.backpackSlotsNum * 0.25,
deliverBar = const.turtle.backpackSlotsNum * 0.75,
deliverPriority = -9, -- passive provider
stationHosterId = os.getComputerID()
}
local registerCo = function()
printC(colors.gray)("[provider] detecting item")
local det = retry((select(slot.isNonEmpty) + getAndHold(1)) * details())()
stationDef.itemType = det.name
stationDef.itemStackLimit = det.count + turtle.getItemSpace()
stationDef.restockBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 0.25
stationDef.deliverBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 0.75
printC(colors.green)("[provider] got "..det.name)
local _reg = function()
local ok, res = swarm.client.request("swarm.services.registerStation("..literal(stationDef)..")")()
if not ok then
log.warn("[provider] failed to register station (network error): "..literal(res)..", retrying...")
return false
end
if not table.remove(res, 1) then
log.warn("[provider] failed to register station (logic error): "..literal(res)..", retrying...")
return false
end
log.info("[provider] provider of " .. stationDef.itemType .. " registered at " .. show(stationDef.pos))
return true
end
retry(_reg)()
end
local produceCo = function()
with({allowInterruption = false})(function()
while true do
-- retry to get items
local det = retry(getAndHold() * details())()
if det.name == stationDef.itemType then -- got target item
print("inventory +"..det.count)
else -- got unconcerned item
saveDir(turn.lateral * drop())()
end
sleep(0.01)
end
end)()
end
registerCo()
para_(produceCo, _updateInventoryCo(stationDef))()
end)
serveAsUnloader = mkIO(function()
local stationDef = {
role = "unloader",
pos = workState.pos - workState:aimingDir(),
dir = workState:aimingDir(),
itemType = "*anything", -- NOTE: this is a special constant value
restockBar = 0,
deliverBar = 0, -- deliver everything and keep nothing
deliverPriority = 10, -- active provider
stationHosterId = os.getComputerID(),
}
local registerCo = function()
printC(colors.gray)("[unloader] registering unload station")
local _reg = function()
local ok, res = swarm.client.request("swarm.services.registerStation("..literal(stationDef)..")")()
if not ok then
log.cry("[unloader] failed to register station (network error): "..literal(res))
return false
end
if not table.remove(res, 1) then
log.cry("[unloader] failed to register station (logic error): "..literal(res))
return false
end
log.info("[unloader] unload station registered at " .. show(stationDef.pos))
return true
end
retry(_reg)()
end
local keepDroppingCo = rep(retry(isChest * select(slot.isNonEmpty) * drop()))
registerCo()
para_(keepDroppingCo, _updateInventoryCo(stationDef))()
end)
serveAsRequester = mkIO(function()
local stationDef = {
role = "requester",
pos = workState.pos - workState:aimingDir(),
dir = workState:aimingDir(),
itemType = nil,
itemStackLimit = nil,
restockBar = const.turtle.backpackSlotsNum * 0.5,
restockPriority = 9,
deliverBar = const.turtle.backpackSlotsNum * 1.0,
stationHosterId = os.getComputerID()
}
local registerCo = function()
printC(colors.gray)("[requester] detecting item")
local det = retry((select(slot.isNonEmpty) + suckHold(1)) * details())()
stationDef.itemType = det.name
stationDef.itemStackLimit = det.count + turtle.getItemSpace()
stationDef.restockBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 0.5
stationDef.deliverBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 1.0
printC(colors.green)("[requester] got "..det.name)
local _reg = function()
local ok, res = swarm.client.request("swarm.services.registerStation("..literal(stationDef)..")")()
if not ok then
log.cry("[requester] failed to register station (network error): "..literal(res))
return false
end
if not table.remove(res, 1) then
log.cry("[requester] failed to register station (logic error): "..literal(res))
return false
end
log.info("[requester] requester of " .. stationDef.itemType .. " registered at " .. show(stationDef.pos))
return true
end
retry(_reg)()
end
local keepDroppingCo = rep(retry(isChest * select(slot.isNonEmpty) * drop()))
registerCo()
para_(keepDroppingCo, _updateInventoryCo(stationDef))()
end)
serveAsStorage = mkIO(function()
local stationDef = {
role = "storage",
pos = workState.pos - workState:aimingDir(),
dir = workState:aimingDir(),
itemType = nil,
itemStackLimit = nil,
restockBar = const.turtle.backpackSlotsNum * 0.25,
restockPriority = 1, --NOTE: lower than requester
deliverBar = const.turtle.backpackSlotsNum * 0.75,
deliverPriority = 0, --NOTE: higher than provider, but still passive
stationHosterId = os.getComputerID()
}
local registerCo = function()
printC(colors.gray)("[storage] detecting item")
local det = retry((select(slot.isNonEmpty) + suckHold(1)) * details())()
stationDef.itemType = det.name
stationDef.itemStackLimit = det.count + turtle.getItemSpace()
stationDef.restockBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 0.25
stationDef.deliverBar = stationDef.itemStackLimit * const.turtle.backpackSlotsNum * 0.75
printC(colors.green)("[storage] got "..det.name)
local _reg = function()
local ok, res = swarm.client.request("swarm.services.registerStation("..literal(stationDef)..")")()
if not ok then
log.cry("[storage] failed to register station (network error): "..literal(res))
return false
end
if not table.remove(res, 1) then
log.cry("[storage] failed to register station (logic error): "..literal(res))
return false
end
log.info("[storage] storage of " .. stationDef.itemType .. " registered at " .. show(stationDef.pos))
return true
end
retry(_reg)()
end
local keepDroppingCo = rep(retry(isChest * select(slot.isNonEmpty) * drop()))
registerCo()
para_(keepDroppingCo, _updateInventoryCo(stationDef))()
end)
serveAsCarrier = mkIO(function()
local serviceCo = rpc.buildServer("swarm-carrier", "blocking", function(msg)
workState.isRunningSwarmTask = true
local res = { safeEval(msg) } --TODO: set proper env
workState.isRunningSwarmTask = false
return unpack(res)
end)
workState.isRunningSwarmTask = false
serviceCo()
end)
--registerActiveProvider = mkIO(function()
-- local stationDef = {
-- pos = gpsPos(),
-- deliverBar = 0,
-- deliverPriority = 98, --passive provider
-- }
-- rednet.send({
-- })
--end)
--
--registerBuffer = mkIO(function()
-- local stationDef = {
-- pos = gpsPos(),
-- restockBar = 15,
-- restockPriority = 89,
-- }
-- rednet.send({
-- })
--end)
--registerRequester = mkIO(function()
-- local stationDef = {
-- pos = gpsPos(),
-- restockBar = 15,
-- restockPriority = 99,
-- }
-- rednet.send({
-- })
--end)
requestStation = mkIOfn(function(itemName, itemCount, startPos, fuelLeft)
itemCount = default(0)(itemCount)
startPos = default(workState.pos)(startPos)
fuelLeft = default(turtle.getFuelLevel())(fuelLeft)
return swarm.client.request("swarm.services.requestStation("..literal(itemName, itemCount, startPos, fuelLeft)..")")()
end)
requestFuelStation = mkIOfn(function(nStep, startPos, fuelLeft)
startPos = default(workState.pos)(startPos)
fuelLeft = default(turtle.getFuelLevel())(fuelLeft)
return swarm.client.request("swarm.services.requestFuelStation("..literal(nStep, startPos, fuelLeft)..")")()
end)
requestUnloadStation = mkIOfn(function(emptySlotRequired)
local requestSucc, res = requestStation("*anything", 0)() --TODO: calc slot number
if not requestSucc then
log.warn("[requestUnloadStation] request failed: "..res)
return false, res
else
return unpack(res)
end
end)
unregisterStation = function(st)
return swarm.client.request("swarm.services.unregisterStation("..literal({itemType = st.itemType, pos = st.pos})..")")()
end
-- | a tool to visit station robustly
-- , will unregister bad stations and try to get next
-- , will wait for user help when there is no more station available
-- , will wait for manually move when cannot reach a station
-- , argument: { reqStation, beforeLeave, beforeRetry, beforeWait, waitForUserHelp }
function _robustVisitStation(opts)
local gotoStation
gotoStation = function(triedTimes, singleTripCost)
local ok, station = opts.reqStation(triedTimes, singleTripCost)
if not ok then
return false, triedTimes, singleTripCost
end
-- got fresh station here
opts.beforeLeave(triedTimes, singleTripCost, station)
local leavePos, fuelBeforeLeave = workState.pos, turtle.getFuelLevel()
with({workArea = false, destroy = 1})(cryingVisitStation(station))()
-- arrived station here
local cost = math.max(0, fuelBeforeLeave - turtle.getFuelLevel())
local singleTripCost_ = singleTripCost + cost
if not isStation() then -- the station is not available
opts.beforeRetry(triedTimes, singleTripCost, station, cost)
unregisterStation(station)
return gotoStation(triedTimes + 1, singleTripCost_)
else
return true, triedTimes, singleTripCost_
end
end
local succ, triedTimes, singleTripCost = gotoStation(1, 0)
if not succ then
opts.beforeWait(triedTimes, singleTripCost, station)
race_(retry(delay(gotoStation, triedTimes + 1, singleTripCost)), delay(opts.waitForUserHelp, triedTimes, singleTripCost, station))()
return true
end
end
-- | turtle is idle means: repl is not running command and workState.isRunningSwarmTask = false
isIdle = mkIO(function()
--return not (_replState.isRunningCommand or workState.isRunningSwarmTask)
return not (_replState.isRunningCommand)
end)
displayVerbLog = mkIO(function()
_logPrintCo({verb = true})
end)
swarm.roles = {
["swarm-server"] = {
check = function() return true end,
daemon = function()
swarm._startService()
end,
},
["log-monitor"] = {
check = function() return true end,
daemon = function()
os.pullEvent("system-ready")
_logPrintCo()
end,
},
["debugger"] = {
check = function() return true end,
daemon = function()
os.pullEvent("system-ready")
_logPrintCo({verb = true, info = false, warn = true, cry = false, bug = true})
end,
},
["unloader"] = {
check = function() return turtle ~= nil end,
daemon = function()
os.pullEvent("turtle-posd-ready")
serveAsUnloader()
end,
},
["provider"] = {
check = function() return turtle ~= nil end,
daemon = function()
os.pullEvent("turtle-posd-ready")
serveAsProvider()
end,
},
["requester"] = {
check = function() return turtle ~= nil end,
daemon = function()
os.pullEvent("turtle-posd-ready")
serveAsRequester()
end,
},
["storage"] = {
check = function() return turtle ~= nil end,
daemon = function()
os.pullEvent("turtle-posd-ready")
serveAsStorage()
end,
},
["carrier"] = {
check = function() return turtle ~= nil end,
daemon = function()
os.pullEvent("system-ready")
serveAsCarrier()
end,
},
["blinker"] = {
check = function() return true end,
daemon = function()
os.pullEvent("system-ready")
local b = false
while true do
redstone.setOutput("front", b)
b = not b
sleep(0.5)
end
end,
},
}
| mit |
dannybloe/domoticz | dzVents/runtime/integration-tests/domoticzTestTools.lua | 6 | 18311 | package.path = package.path ..
";../?.lua;../device-adapters/?.lua;./data/?.lua;../../../scripts/dzVents/generated_scripts/?.lua;" ..
"../../../scripts/lua/?.lua"
local _ = require 'lodash'
local File = require('File')
local http = require("socket.http")
local ltn12 = require("ltn12")
local jsonParser = require('JSON')
local scriptSourcePath = './'
local scriptTargetPath = '../../../scripts/dzVents/scripts/'
local generatedScriptTargetPath = '../../../scripts/dzVents/generated_scripts/'
local dataTargetPath = '../../../scripts/dzVents/data/'
local DUMMY_HW = 15
local DUMMY_HW_ID = 2
local function DomoticzTestTools(port, debug, webroot)
if (port == nil) then port = 8080 end
local BASE_URL = 'http://localhost:' .. port
if (webroot ~= '' and webroot ~= nil) then
BASE_URL = BASE_URL .. '/' .. webroot
end
local API_URL = BASE_URL .. '/json.htm?'
local self = {
['port'] = port,
url = BASE_URL,
apiUrl = API_URL
}
function self.getScriptSourcePath(name)
return scriptSourcePath .. name
end
function self.getScriptTargetPath(name)
return scriptTargetPath .. name
end
function self.copyScript(name)
File.remove(self.getScriptTargetPath(name))
File.copy(self.getScriptSourcePath(name), self.getScriptTargetPath(name))
end
function self.removeFSScript(name)
os.remove(self.getScriptTargetPath(name))
end
function self.removeGUIScript(name)
os.remove(dataTargetPath .. name)
end
function self.removeDataFile(name)
os.remove(dataTargetPath .. name)
end
function self.doAPICall(url)
local response = {}
local _url = self.apiUrl .. url
local result, respcode, respheaders, respstatus = http.request {
method = "GET",
url = _url,
sink = ltn12.sink.table(response)
}
local _json = table.concat(response)
local json = jsonParser:decode(_json)
local ok = json.status == 'OK'
if (debug and not ok) then
_.print('--------------')
_.print(_url)
_.print(ok)
_.print(json)
_.print(debug.traceback())
_.print('--------------')
end
return ok, json, result, respcode, respheaders, respstatus
end
function self.createHardware(name, type)
local url = "param=addhardware&type=command&htype=" .. tostring(type) .. "&name=" .. name .. "&enabled=true&datatimeout=0"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local idx = json.idx
return ok, idx, json, result, respcode, respheaders, respstatus
end
function self.createDummyHardware()
local ok, dummyIdx = self.createHardware('dummy', DUMMY_HW)
return ok, dummyIdx
end
function self.createManagedCounter(name)
local url = "type=createdevice&idx=" .. DUMMY_HW_ID .."&sensorname=" .. name .. "&sensormappedtype=0xF321"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json, result, respcode, respheaders, respstatus
end
function self.createCamera()
local url = "type=command¶m=addcamera&address=192.168.192.123&port=8083&name=camera1&enabled=true&imageurl=aW1hZ2UuanBn&protocol=0"
--&username=&password=&imageurl=aW1hZ2UuanBn&protocol=0
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json, result, respcode, respheaders, respstatus
end
function self.createVirtualDevice(hw, name, type, options)
local url = "type=createvirtualsensor&idx=" .. tostring(hw) .."&sensorname=" .. name .. "&sensortype=" .. tostring(type)
if tostring(type) == "33" then
url = "type=createdevice&idx=" .. tostring(hw) .."&sensorname=" .. name .. "&sensormappedtype=0xF321"
end
if (options) then
url = url .. '&sensoroptions=1;' .. tostring(options)
end
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local idx = json.idx
return ok, idx, json, result, respcode, respheaders, respstatus
end
function self.createScene(name)
-- type=addscene&name=myScene&scenetype=0
local url = "type=addscene&name=" .. name .. "&scenetype=0"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json, result, respcode, respheaders, respstatus
end
function self.createGroup(name)
-- type=addscene&name=myGroup&scenetype=1
local url = "type=addscene&name=" .. name .. "&scenetype=1"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local idx = json.idx
return ok, idx, json, result, respcode, respheaders, respstatus
end
function self.createVariable(name, type, value)
-- todo, encode value
--type=command¶m=adduservariable&vname=myint&vtype=0&vvalue=1
local url = "param=adduservariable&type=command&vname=" .. name .."&vtype=" .. tostring(type) .. "&vvalue=" .. tostring(value)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local idx = json.idx
return ok, idx, json, result, respcode, respheaders, respstatus
end
function self.deleteDevice(idx)
-- type=deletedevice&idx=2;1;...
local url = "type=deletedevice&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.deleteGroupScene(idx)
-- type=deletescene&idx=1
local url = "type=deletescene&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.getDevice(idx)
--type=devices&rid=15
local url = "type=devices&rid=" .. idx
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
if (ok and json.result ~= nil and _.size(json.result) == 1) then
return ok, json.result[1]
end
return false, nil
end
function self.getAllDevices()
-- type=devices&displayhidden=1&displaydisabled=1&filter=all&used=all
local url = "type=devices&displayhidden=1&displaydisabled=1&filter=all&used=all"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json, result
end
function self.deleteAllDevices()
local ok, json, result = self.getAllDevices()
local res = true
if (ok) then
if (_.size(json.result) > 0) then
for i, device in pairs(json.result) do
local ok, json
if (device.Type == 'Scene' or device.Type == 'Group') then
ok, json = self.deleteGroupScene(device.idx)
else
ok, json = self.deleteDevice(device.idx)
end
if (not ok) then
print('Failed to remove device: ' .. device.Name)
res = false
end
end
end
else
return false
end
return res
end
function self.deleteVariable(idx)
--type=command¶m=deleteuservariable&idx=1
local url = "param=deleteuservariable&type=command&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.deleteAllVariables()
-- type=commandparam=onkyoeiscm=getuservariables
local url = "param=getuservariables&type=command"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local res = true
if (ok) then
if (_.size(json.result) > 0) then
for i, variable in pairs(json.result) do
local ok, json
ok, json = self.deleteVariable(variable.idx)
if (not ok) then
print('Failed to remove variable: ' .. variable.Name)
res = false
end
end
end
else
return false
end
return res
end
function self.deleteCamera(idx)
-- http://localhost:8080/json.htm?type=command¶m=deletehardware&idx=2
local url = "type=command¶m=deletecamera&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.deleteAllCameras()
local url = "type=cameras"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local res = true
if (ok) then
if (_.size(json.result) > 0) then
for i, camera in pairs(json.result) do
local ok, json = self.deleteCamera(camera.idx)
if (not ok) then
print('Failed to remove cameras: ' .. camera.Name)
res = false
end
end
end
else
return false
end
return res
end
function self.deleteHardware(idx)
-- http://localhost:8080/json.htm?type=command¶m=deletehardware&idx=2
local url = "param=deletehardware&type=command&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.deleteAllHardware()
-- http://localhost:8080/json.htm?type=hardware
local url = "type=hardware"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local res = true
if (ok) then
if (_.size(json.result) > 0) then
for i, hw in pairs(json.result) do
local ok, json = self.deleteHardware(hw.idx)
if (not ok) then
print('Failed to remove hardware: ' .. hw.Name)
res = false
end
end
end
else
return false
end
return res
end
function self.deleteScript(idx)
--type=events¶m=delete&event=1
local url = "param=delete&type=events&event=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok, json
end
function self.deleteAllScripts()
-- type=events¶m=list
local url = "param=list&type=events"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
local res = true
if (ok) then
if (_.size(json.result) > 0) then
for i, script in pairs(json.result) do
local ok, json
ok, json = self.deleteScript(script.id)
if (not ok) then
print('Failed to remove script: ' .. script.Name)
res = false
end
return true
end
end
else
return false
end
return res
end
function self.updateSwitch(idx, name, description, switchType)
--http://localhost:8080/json.htm?type=setused&idx=1&name=vdSwitch&description=des&strparam1=&strparam2=&protected=false&switchtype=0&customimage=0&used=true&addjvalue=0&addjvalue2=0&options=
local url = "type=setused&idx=" ..
tostring(idx) ..
"&name=" .. name ..
"&description=" .. description ..
"&strparam1=&strparam2=&protected=false&" ..
"switchtype=" .. tostring(switchType) .. "&customimage=0&used=true&addjvalue=0&addjvalue2=0&options="
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.switch(idx, cmd)
--type=command¶m=switchlight&idx=39&switchcmd=On&level=0&passcode=
local url = "param=switchlight&type=command&switchcmd=" .. cmd .. "&level=0&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.dimTo(idx, cmd, level)
--type=command¶m=switchlight&idx=39&switchcmd=On&level=0&passcode=
local url = "param=switchlight&type=command&switchcmd=" .. cmd .. "&level=" .. tostring(level) .. "&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.switchSelector(idx, level)
--type=command¶m=switchlight&idx=39&switchcmd=On&level=0&passcode=
local url = "param=switchlight&type=command&switchcmd=Set%20Level&level=" .. tostring(level) .. "&idx=" .. tostring(idx)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.switchGroup(idx, cmd)
--http://localhost:8080/json.htm?type=command¶m=switchscene&idx=2&switchcmd=On&passcode=
local url = "param=switchscene&type=command&idx=" .. tostring(idx) .. "&switchcmd=" .. cmd .. "&passcode="
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.addSceneDevice(sceneIdx, devIdx)
-- http://nuc:8080/json.htm?type=command¶m=addscenedevice&idx=1&isscene=false&devidx=6&command=On&level=100&color=&ondelay=0&offdelay=0
local url = "param=addscenedevice&type=command&idx=" .. tostring(sceneIdx) .. "&isscene=false&devidx=" .. tostring(devIdx) .. "&command=On&level=100&color=&ondelay=0&offdelay=0"
print (url)
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.initSettings(IFTTTEnabled)
local IFTTTEnabled = IFTTTEnabled or "%20"
local response = {}
local reqbody = "Language=en&Themes=default&Title=Domoticz&Latitude=52.278870&Longitude=5.665849&DashboardType=0&AllowWidgetOrdering=on&MobileType=0&WebUserName=&WebPassword=d41d8cd98f00b204e9800998ecf8427e&AuthenticationMethod=0&GuestUser=0&SecPassword=1&SecOnDelay=0&ProtectionPassword=d41d8cd98f00b204e9800998ecf8427e&WebLocalNetworks=127.0.0.1&RemoteSharedPort=6144&WebRemoteProxyIPs=127.0.0.1&checkforupdates=on&ReleaseChannel=0&AcceptNewHardware=on&HideDisabledHardwareSensors=on&MyDomoticzUserId=&MyDomoticzPassword=&EnableTabLights=on&EnableTabScenes=on&EnableTabTemp=on&EnableTabWeather=on&EnableTabUtility=on&EnableTabCustom=on&LightHistoryDays=30&ShortLogDays=1&ProwlAPI=&NMAAPI=&PushbulletAPI=&PushsaferAPI=&PushsaferImage=&PushoverUser=&PushoverAPI=&PushALotAPI=&ClickatellAPI=&ClickatellTo=&IFTTTAPI=thisIsnotTheRealAPI&IFTTTEnabled=" .. IFTTTEnabled ..
"&HTTPField1=&HTTPField2=&HTTPField3=&HTTPField4=&HTTPTo=&HTTPURL=https%3A%2F%2Fwww.somegateway.com%2Fpushurl.php%3Fusername%3D%23FIELD1%26password%3D%23FIELD2%26apikey%3D%23FIELD3%26from%3D%23FIELD4%26to%3D%23TO%26message%3D%23MESSAGE&HTTPPostData=&HTTPPostContentType=application%2Fjson&HTTPPostHeaders=&KodiIPAddress=224.0.0.1&KodiPort=9777&KodiTimeToLive=5&LmsPlayerMac=&LmsDuration=5&TelegramAPI=&TelegramChat=&NotificationSensorInterval=43200&NotificationSwitchInterval=0&EmailEnabled=on&EmailFrom=&EmailTo=&EmailServer=&EmailPort=25&EmailUsername=&EmailPassword=&UseEmailInNotifications=on&TempUnit=0&DegreeDaysBaseTemperature=18.0&WindUnit=0&WeightUnit=0&EnergyDivider=1000&CostEnergy=0.2149&CostEnergyT2=0.2149&CostEnergyR1=0.0800&CostEnergyR2=0.0800&GasDivider=100&CostGas=0.6218&WaterDivider=100&CostWater=1.6473&ElectricVoltage=230&CM113DisplayType=0&SmartMeterType=0&FloorplanPopupDelay=750&FloorplanAnimateZoom=on&FloorplanShowSensorValues=on&FloorplanShowSceneNames=on&FloorplanRoomColour=Blue&FloorplanActiveOpacity=25&FloorplanInactiveOpacity=5&RandomSpread=15&SensorTimeout=60&BatterLowLevel=0&LogFilter=&LogFileName=&LogLevel=0&DoorbellCommand=0&RaspCamParams=-w+800+-h+600+-t+1&UVCParams=-S80+-B128+-C128+-G80+-x800+-y600+-q100&EnableEventScriptSystem=on&LogEventScriptTrigger=on&DisableDzVentsSystem=on&DzVentsLogLevel=3"
local url = BASE_URL .. '/storesettings'
local result, respcode, respheaders, respstatus = http.request {
method = "POST",
source = ltn12.source.string(reqbody),
url = url,
headers = {
['Connection'] = 'keep-alive',
['Content-Length'] = _.size(reqbody),
['Pragma'] = 'no-cache',
['Cache-Control'] = 'no-cache',
['Origin'] = BASE_URL,
['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8',
['Accept'] = '*/*',
['X-Requested-With'] = 'XMLHttpRequest',
['DNT'] = '1',
['Referer'] = BASE_URL,
},
sink = ltn12.sink.table(response)
}
local _json = table.concat(response)
local ok = (respcode == 200)
return ok, result, respcode, respheaders, respstatus
end
function self.reset()
local ok = true
ok = ok and self.deleteAllDevices()
ok = ok and self.deleteAllVariables()
ok = ok and self.deleteAllHardware()
ok = ok and self.deleteAllScripts()
ok = ok and self.initSettings()
return ok
end
function self.installFSScripts(scripts)
for i,script in pairs(scripts) do
self.createFSScript(script)
end
end
function self.cleanupFSScripts(scripts)
for i,script in pairs(scripts) do
self.removeFSScript(script)
self.removeDataFile('__data_' .. script)
end
end
function self.setDisarmed()
-- http://localhost:8080/json.htm?type=command¶m=setsecstatus&secstatus=0&seccode=c4ca4238a0b923820dcc509a6f75849b
local url = "param=setsecstatus&type=command&secstatus=0&seccode=c4ca4238a0b923820dcc509a6f75849b"
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.addSecurityPanel(idx)
local url = "type=setused&idx=" .. tostring(idx) .. "&name=secPanel&used=true&maindeviceidx="
local ok, json, result, respcode, respheaders, respstatus = self.doAPICall(url)
return ok
end
function self.createScript(name, code)
local response = {}
local reqbody = 'name=' .. name ..'&' ..
'interpreter=dzVents&' ..
'eventtype=All&' ..
'xml=' .. tostring(code) .. '&' ..
--'xml=return%20%7B%0A%09active%20%3D%20false%2C%0A%09on%20%3D%20%7B%0A%09%09timer%20%3D%20%7B%7D%0A%09%7D%2C%0A%09execute%20%3D%20function(domoticz%2C%20device)%0A%09end%0A%7D&' ..
'logicarray=&' ..
'eventid=&' ..
'eventstatus=1&' ..
'editortheme=ace%2Ftheme%2Fxcode'
local url = BASE_URL .. '/event_create.webem'
local result, respcode, respheaders, respstatus = http.request {
method = "POST",
source = ltn12.source.string(reqbody),
url = url,
headers = {
['Connection'] = 'keep-alive',
['Pragma'] = 'no-cache',
['Cache-Control'] = 'no-cache',
['Content-Length'] = _.size(reqbody),
['Origin'] = BASE_URL,
['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8',
['Accept'] = '*/*',
['X-Requested-With'] = 'XMLHttpRequest',
['DNT'] = '1',
['Referer'] = BASE_URL,
},
sink = ltn12.sink.table(response)
}
local _json = table.concat(response)
local ok = (respcode == 200)
return ok, result, respcode, respheaders, respstatus
end
function self.createGUIScriptFromFile(name)
local stage1Script = File.read(name)
local ok, result, respcode, respheaders, respstatus = self.createScript('stage1', stage1Script)
return ok
end
function self.createFSScript(name)
self.copyScript(name)
end
function self.tableEntries(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
return self
end
return DomoticzTestTools
| gpl-3.0 |
jpmac26/PGE-Project | Engine/_resources/script/maincore_level.lua | 1 | 1602 |
-- We need to reference all placed objects with lua or the garbage collector will hit it
local __refs = {}
__refs.players = {}
__refs.npcs = {}
-- Debug stuff
local deb_i = 0
local function temp_count(t) local i = 0 for _,__ in pairs(t) do i = i + 1 end return i end
-- Debug stuff end
function onLoop()
if(Settings.isDebugInfoShown())then
deb_i = deb_i + 1
Renderer.printText("Ticks passed: "..deb_i, 100, 130, 0, 15, 0xFFFF0055)
if(npc_class_table)then
Renderer.printText(temp_count(npc_class_table).." Npc registered!", 100, 160, 0, 15, 0xFFFF0055)
else
Renderer.printText("No Npc registered!", 100, 160, 0, 15, 0xFFFF0055)
end
end
end
function __native_event(eventObj, ...)
local eventFuncToFind = "on"..eventObj.eventName:sub(0, 1):upper()..eventObj.eventName:sub(2)
-- Logger.debug(eventFuncToFind)
if(type(_G[eventFuncToFind]) == "function")then
_G[eventFuncToFind](...)
end
end
function __create_luaplayer()
local newPlayer = bases.player()
__refs.players[newPlayer] = true --Be sure that the garbage collector doesn't destory our object
return newPlayer
end
function __create_luanpc()
local newNPC = bases.npc()
__refs.npcs[newNPC] = true --Be sure that the garbage collector doesn't destory our object
return newNPC
end
function __destroy_luanpc(theNPC)
__refs.npcs[theNPC] = nil --Let the garbage collector destory our object
end
function __destroy_luaplayer(thePlayer)
__refs.players[thePlayer] = nil --Let the garbage collector destory our object
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/abilities/pets/chimera_ripper.lua | 4 | 1216 | ---------------------------------------------------
-- Chimera Ripper
---------------------------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/automatonweaponskills")
---------------------------------------------------
function onMobSkillCheck(target, automaton, skill)
local master = automaton:getMaster()
return master:countEffect(EFFECT_FIRE_MANEUVER)
end
function onPetAbility(target, automaton, skill, master, action)
local params = {
numHits = 1,
atkmulti = 1,
accBonus = 100,
weaponType = SKILL_SWD,
ftp100 = 1.5,
ftp200 = 2.0,
ftp300 = 3.0,
acc100 = 0.0,
acc200 = 0.0,
acc300 = 0.0,
str_wsc = 0.5,
dex_wsc = 0.0,
vit_wsc = 0.0,
agi_wsc = 0.0,
int_wsc = 0.0,
mnd_wsc = 0.0,
chr_wsc = 0.0
}
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 6.0
params.ftp200 = 8.5
params.ftp300 = 11.0
end
local damage = doAutoPhysicalWeaponskill(automaton, target, 0, skill:getTP(), true, action, false, params, skill, action)
return damage
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Cape_Teriggan/npcs/Voranbo-Natanbo_WW.lua | 3 | 3326 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Voranbo-Natanbo, W.W.
-- Type: Outpost Conquest Guards
-- !pos -185 7 -63 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Cape_Teriggan/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VOLLBOW;
local csid = 0x7ff7;
-----------------------------------
-- 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 |
wgallios/.ubuntu | awesome/rc.lua | 1 | 23915 | -- Standard awesome library
local gears = require("gears")
awful = require("awful")
awful.rules = require("awful.rules")
require("awful.autofocus")
-- Widget and layout library
wibox = require("wibox")
-- Theme handling library
beautiful = require("beautiful")
-- Notification library
naughty = require("naughty")
local menubar = require("menubar")
local vicious = require("vicious")
radical = require("radical")
blingbling = require("blingbling")
-- Number of CPU cores
CORES = 4
-- Load Debian menu entries
require("debian.menu")
awful.util.spawn_with_shell("xcompmgr -cfF -t-9 -l-11 -r9 -o.95 -D6 > /dev/null &")
awful.util.spawn_with_shell("echo 'pointer = 1 2 3 5 4 7 6 8 9 10 11 12' > ~/.Xmodmap && xmodmap ~/.Xmodmap &")
awful.util.spawn_with_shell("xscreensaver -nosplash &")
-- awful.util.spawn_with_shell("sh ~/.wallpaper &")
-- awful.util.spawn_with_shell("sh ~/.conky/conky-startup.sh &")
sep = wibox.widget.textbox()
spacer = wibox.widget.textbox()
sep:set_text(' / ')
spacer:set_text(' ')
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors })
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function (err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = err })
in_error = false
end)
end
-- }}}
-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
-- beautiful.init("/usr/share/awesome/themes/default/theme.lua")
beautiful.init("~/.config/awesome/themes/powerarrow-darker/theme.lua")
-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"
-- Table of layouts to cover with awful.layout.inc, order matters.
layouts = {
awful.layout.suit.floating,
-- awful.layout.suit.tile,
awful.layout.suit.tile.left,
-- awful.layout.suit.tile.bottom,
-- awful.layout.suit.tile.top,
awful.layout.suit.fair,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
awful.layout.suit.spiral.dwindle,
-- awful.layout.suit.max,
awful.layout.suit.max.fullscreen,
-- awful.layout.suit.magnifier
}
-- }}}
-- requires after theme has been loaded
require("cpu")
require("net")
require("volume")
require("calendar")
require("battery")
#require("menu")
require("java")
require("tags")
-- This is used later as the default terminal and editor to run.
terminal = "terminator"
chrome = "google-chrome"
firefox = "firefox"
fileman = "nemo --no-desktop"
-- fileman = 'thunar'
editor = os.getenv("EDITOR") or "editor"
editor_cmd = terminal .. " -e " .. editor
terminology = "terminology"
restart_cmd = "shutdown -r now"
shutdown_cmd = "shutdown now"
-- {{{ Wallpaper
if beautiful.wallpaper then
for s = 1, screen.count() do
gears.wallpaper.maximized(beautiful.wallpaper, s, true)
end
end
-- }}}
-- {{{ Tags
-- Define a tag table which hold all screen tags.
-- tags = {}
-- ter_icon = wibox.widget.imagebox()
-- www_icon = wibox.widget.imagebox()
-- gmp_icon = wibox.widget.imagebox()
-- ter_icon:set_image(beautiful.term_icon)
-- }}}
-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
{ "Manual", terminal .. " -e man awesome" },
{ "Edit Config", editor_cmd .. " " .. awesome.conffile },
{ "Reload Awesome", awesome.restart },
{ "Log Out", awesome.quit },
{ "/*_Chuck_Testa_*/", nil },
{ "Restart Computer", restart_cmd },
{ "Shutdown Computer", shutdown_cmd }
}
mymainmenu = awful.menu({ items = {
{ "Chrome", chrome, beautiful.www_icon },
{ "Terminal", terminal, beautiful.term_icon },
{ "Files", fileman, beautiful.files },
{ "Firefox", firefox, beautiful.firefox },
{ "Terminology", terminology, beautiful.term_icon },
{ "Main Menu", debian.menu.Debian_menu.Debian, beautiful.debian },
{ "Awesome", myawesomemenu, beautiful.awesome_icon }
}
})
mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon,
menu = mymainmenu })
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}
-- {{{ Arrows
arrl = wibox.widget.imagebox()
arrl:set_image(beautiful.arrl)
arrl_dl = wibox.widget.imagebox()
arrl_dl:set_image(beautiful.arrl_dl)
arrl_ld = wibox.widget.imagebox()
arrl_ld:set_image(beautiful.arrl_ld)
arrl_ld_sf = wibox.widget.imagebox()
arrl_ld_sf:set_image(beautiful.arrl_ld_sf)
-- colored arrows
arr1 = wibox.widget.imagebox()
arr1:set_image(beautiful.arr1)
arr2 = wibox.widget.imagebox()
arr2:set_image(beautiful.arr2)
arr3 = wibox.widget.imagebox()
arr3:set_image(beautiful.arr3)
arr4 = wibox.widget.imagebox()
arr4:set_image(beautiful.arr4)
arr5 = wibox.widget.imagebox()
arr5:set_image(beautiful.arr5)
arr6 = wibox.widget.imagebox()
arr6:set_image(beautiful.arr6)
arr7 = wibox.widget.imagebox()
arr7:set_image(beautiful.arr7)
arr8 = wibox.widget.imagebox()
arr8:set_image(beautiful.arr8)
arr9 = wibox.widget.imagebox()
arr9:set_image(beautiful.arr9)
-- }}}
-- {{{ Wibox
-- memory icon
memicon = wibox.widget.background()
memicon_img = wibox.widget.imagebox()
memicon_img:set_image(beautiful.widget_mem)
memicon:set_widget(memicon_img)
memicon:set_bg(beautiful.arrow_bg_3)
-- Memory Widget
memwidget_txt = wibox.widget.textbox()
memwidget = wibox.widget.background()
memwidget:set_widget(memwidget_txt)
memwidget:set_bg(beautiful.arrow_bg_3)
vicious.register(memwidget_txt, vicious.widgets.mem, "$1% $2MB ", 13)
-- Create a wibox for each screen and add it
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mystatusbar = {}
mytaglist.buttons = awful.util.table.join(
awful.button({ }, 1, awful.tag.viewonly),
awful.button({ modkey }, 1, awful.client.movetotag),
awful.button({ }, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, awful.client.toggletag),
awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end),
awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end)
)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
-- Without this, the following
-- :isvisible() makes no sense
c.minimized = false
if not c:isvisible() then
awful.tag.viewonly(c:tags()[1])
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end),
awful.button({ }, 3, function ()
if instance then
instance:hide()
instance = nil
else
instance = awful.menu.clients({
theme = { width = 250 }
})
end
end),
awful.button({ }, 4, function ()
awful.client.focus.byidx(1)
if client.focus then client.focus:raise() end
end),
awful.button({ }, 5, function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end))
for s = 1, screen.count() do
-- Create a promptbox for each screen
mypromptbox[s] = awful.widget.prompt()
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
mylayoutbox[s] = awful.widget.layoutbox(s)
mylayoutbox[s]:buttons(awful.util.table.join(
awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)))
-- Create a taglist widget
mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, mytaglist.buttons)
-- Create a tasklist widget
mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons)
-- Create the wibox
-- [[
mywibox[s] = awful.wibox({ position = "top", screen = s })
-- mystatusbar[s] = awful.wibox({ position = "bottom", screen = s })
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(mylauncher)
-- left_layout:add(menubox)
left_layout:add(mytaglist[s])
left_layout:add(mypromptbox[s])
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
if s == 1 then
right_layout:add(arrl)
right_layout:add(spacer)
right_layout:add(wibox.widget.systray())
right_layout:add(spacer)
end
right_layout:add(arr8)
right_layout:add(volicon)
right_layout:add(bvol)
-- right_layout:add(volwidget)
right_layout:add(arr6)
-- right_layout:add(spacer)
right_layout:add(baticon)
-- right_layout:add(spacer)
-- right_layout:add(spacer)
-- right_layout:add(batwidget)
-- right_layout:add(batg)
right_layout:add(arr5)
right_layout:add(cpuicon)
for i=1,CORES do
right_layout:add(cpu_graphs[i])
end
-- right_layout:add(cpuwidget)
right_layout:add(arr4)
right_layout:add(memicon)
right_layout:add(memwidget)
right_layout:add(arr3)
right_layout:add(neticon)
right_layout:add(wifiwidget)
right_layout:add(netwidget)
right_layout:add(arr2)
-- right_layout:add(volume_widget)
-- right_layout:add(mytextclock)
--
-- right_layout:add(spacer)
right_layout:add(datewidget)
-- right_layout:add(calw)
right_layout:add(arr1)
right_layout:add(mylayoutbox[s])
-- Now bring it all together (with the tasklist in the middle)
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_middle(mytasklist[s])
layout:set_right(right_layout)
mywibox[s]:set_widget(layout)
-- mystatusbar[s]:set_widget(rbox)
-- ]]--
end
-- }}}
-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}
-- {{{ Key bindings
globalkeys = awful.util.table.join(
awful.key({ modkey, }, "Left", awful.tag.viewprev ),
awful.key({ modkey, }, "Right", awful.tag.viewnext ),
awful.key({ modkey, }, "Escape", awful.tag.history.restore),
awful.key({ modkey, }, "j",
function ()
awful.client.focus.byidx( 1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "k",
function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "w", function () mymainmenu:show() end),
-- Layout manipulation
awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end),
awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end),
awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end),
awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto),
awful.key({ modkey, }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end),
-- Standard program
awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end),
awful.key({ modkey, "Control" }, "r", awesome.restart),
awful.key({ modkey, "Shift" }, "q", awesome.quit),
awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end),
awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end),
awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end),
awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end),
awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end),
awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end),
awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end),
awful.key({ modkey, "Control" }, "n", awful.client.restore),
-- Prompt
awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end),
awful.key({ modkey }, "x",
function ()
awful.prompt.run({ prompt = "Run Lua code: " },
mypromptbox[mouse.screen].widget,
awful.util.eval, nil,
awful.util.getdir("cache") .. "/history_eval")
end),
-- Menubar
awful.key({ modkey }, "p", function() menubar.show() end),
-- Brightness
awful.key({ modkey, "Shift" }, "p", function () awful.util.spawn("xbacklight -dec 5") end),
awful.key({ modkey, "Shift" }, "o", function () awful.util.spawn("xbacklight -inc 5") end),
awful.key({ modkey, "Control" }, "l", function () awful.util.spawn("xscreensaver-command -lock") end),
-- awful.key({ }, "F10", function() toggle_conky() end),
awful.key({ }, "XF86AudioRaiseVolume", function () awful.util.spawn("amixer -c 1 set Master 5%+", false) end),
awful.key({ }, "XF86AudioLowerVolume", function () awful.util.spawn("amixer -c 1 set Master 5%-", false) end),
awful.key({ }, "XF86AudioMute", function () awful.util.spawn("amixer -c 1 set Master toggle", false) end),
-- executes script to enable only primary monitor
awful.key({ modkey, "Shift" }, "Down", function () awful.util.spawn_with_shell("~/.ubuntu/scripts/ext_monitor_disconnect &", false) end),
-- executes script to enable secondary external monitor (in this case HDMI1)
awful.key({ modkey, "Shift" }, "Up", function () awful.util.spawn_with_shell("~/.ubuntu/scripts/ext_monitor_connect &", false) end)
)
clientkeys = awful.util.table.join(
awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen end),
awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ),
awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end),
awful.key({ modkey, }, "o", awful.client.movetoscreen ),
awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end),
awful.key({ modkey, }, "n",
function (c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end),
awful.key({ modkey, }, "m",
function (c)
c.maximized_horizontal = not c.maximized_horizontal
c.maximized_vertical = not c.maximized_vertical
end)
)
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
globalkeys = awful.util.table.join(globalkeys,
-- View tag only.
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = mouse.screen
local tag = awful.tag.gettags(screen)[i]
if tag then
awful.tag.viewonly(tag)
end
end),
-- Toggle tag.
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = mouse.screen
local tag = awful.tag.gettags(screen)[i]
if tag then
awful.tag.viewtoggle(tag)
end
end),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = awful.tag.gettags(client.focus.screen)[i]
if tag then
awful.client.movetotag(tag)
end
end
end),
-- Toggle tag.
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = awful.tag.gettags(client.focus.screen)[i]
if tag then
awful.client.toggletag(tag)
end
end
end))
end
clientbuttons = awful.util.table.join(
awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
awful.button({ modkey }, 1, awful.mouse.client.move),
awful.button({ modkey }, 3, awful.mouse.client.resize))
-- Set keys
root.keys(globalkeys)
-- }}}
-- {{{ Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = clientkeys,
buttons = clientbuttons } },
{ rule = { class = "MPlayer" },
properties = { floating = true } },
{ rule = { class = "pinentry" },
properties = { floating = true } },
{ rule = { class = "gimp" },
properties = { floating = true } },
-- Set Firefox to always map on tags number 2 of screen 1.
-- { rule = { class = "Firefox" },
-- properties = { tag = tags[2][1] } },
--
-- Set Firefox to always map on tags number 2 of screen 1.
-- {
-- rule = {
-- class = "Chrome"
-- },
-- properties = {
-- tag = tags[1][2]
-- }
-- },
}
-- }}}
-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c, startup)
-- Enable sloppy focus
c:connect_signal("mouse::enter", function(c)
if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
and awful.client.focus.filter(c) then
client.focus = c
end
end)
if not startup then
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- awful.client.setslave(c)
-- Put windows in a smart way, only if they does not set an initial position.
if not c.size_hints.user_position and not c.size_hints.program_position then
awful.placement.no_overlap(c)
awful.placement.no_offscreen(c)
end
end
local titlebars_enabled = false
if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then
-- buttons for the titlebar
local buttons = awful.util.table.join(
awful.button({ }, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({ }, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(awful.titlebar.widget.iconwidget(c))
left_layout:buttons(buttons)
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
right_layout:add(awful.titlebar.widget.floatingbutton(c))
right_layout:add(awful.titlebar.widget.maximizedbutton(c))
right_layout:add(awful.titlebar.widget.stickybutton(c))
right_layout:add(awful.titlebar.widget.ontopbutton(c))
right_layout:add(awful.titlebar.widget.closebutton(c))
-- The title goes in the middle
local middle_layout = wibox.layout.flex.horizontal()
local title = awful.titlebar.widget.titlewidget(c)
title:set_align("center")
middle_layout:add(title)
middle_layout:buttons(buttons)
-- Now bring it all together
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_right(right_layout)
layout:set_middle(middle_layout)
awful.titlebar(c):set_widget(layout)
awful.statusbar(c):set_widget(menubar)
end
end)
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
| mit |
SinisterRectus/Discordia | libs/iterables/ArrayIterable.lua | 1 | 1996 | --[=[
@c ArrayIterable x Iterable
@mt mem
@d Iterable class that contains objects in a constant, ordered fashion, although
the order may change if the internal array is modified. Some versions may use a
map function to shape the objects before they are accessed.
]=]
local Iterable = require('iterables/Iterable')
local ArrayIterable, get = require('class')('ArrayIterable', Iterable)
function ArrayIterable:__init(array, map)
self._array = array
self._map = map
end
function ArrayIterable:__len()
local array = self._array
if not array or #array == 0 then
return 0
end
local map = self._map
if map then -- map can return nil
return Iterable.__len(self)
else
return #array
end
end
--[=[@p first * The first object in the array]=]
function get.first(self)
local array = self._array
if not array or #array == 0 then
return nil
end
local map = self._map
if map then
for i = 1, #array, 1 do
local v = array[i]
local obj = v and map(v)
if obj then
return obj
end
end
else
return array[1]
end
end
--[=[@p last * The last object in the array]=]
function get.last(self)
local array = self._array
if not array or #array == 0 then
return nil
end
local map = self._map
if map then
for i = #array, 1, -1 do
local v = array[i]
local obj = v and map(v)
if obj then
return obj
end
end
else
return array[#array]
end
end
--[=[
@m iter
@r function
@d Returns an iterator for all contained objects in a consistent order.
]=]
function ArrayIterable:iter()
local array = self._array
if not array or #array == 0 then
return function() -- new closure for consistency
return nil
end
end
local map = self._map
if map then
local i = 0
return function()
while true do
i = i + 1
local v = array[i]
if not v then
return nil
end
v = map(v)
if v then
return v
end
end
end
else
local i = 0
return function()
i = i + 1
return array[i]
end
end
end
return ArrayIterable
| mit |
bmichalo/MoonGen | rfc2544/benchmarks/backtoback.lua | 9 | 13123 | package.path = package.path .. "rfc2544/?.lua"
local standalone = false
if master == nil then
standalone = true
master = "dummy"
end
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local ts = require "timestamping"
local filter = require "filter"
local ffi = require "ffi"
local barrier = require "barrier"
local arp = require "proto.arp"
local timer = require "timer"
local namespaces = require "namespaces"
local utils = require "utils.utils"
local tikz = require "utils.tikz"
local UDP_PORT = 42
local benchmark = {}
benchmark.__index = benchmark
function benchmark.create()
local self = setmetatable({}, benchmark)
self.initialized = false
return self
end
setmetatable(benchmark, {__call = benchmark.create})
function benchmark:init(arg)
self.granularity = arg.granularity or 100
self.duration = arg.duration or 2
self.numIterations = arg.numIterations or 50
self.rxQueues = arg.rxQueues
self.txQueues = arg.txQueues
self.skipConf = arg.skipConf
self.dut = arg.dut
self.initialized = true
end
function benchmark:config()
self.undoStack = {}
utils.addInterfaceIP(self.dut.ifIn, "198.18.1.1", 24)
table.insert(self.undoStack, {foo = utils.delInterfaceIP, args = {self.dut.ifIn, "198.18.1.1", 24}})
utils.addInterfaceIP(self.dut.ifOut, "198.19.1.1", 24)
table.insert(self.undoStack, {foo = utils.delInterfaceIP, args = {self.dut.ifOut, "198.19.1.1", 24}})
end
function benchmark:undoConfig()
local len = #self.undoStack
for k, v in ipairs(self.undoStack) do
--work in stack order
local elem = self.undoStack[len - k + 1]
elem.foo(unpack(elem.args))
end
--clear stack
self.undoStack = {}
end
function benchmark:getCSVHeader()
local str = "frameSize,precision,linkspeed,duration"
for iteration=1, self.numIterations do
str = str .. ",burstsize iter" .. iteration
end
return str
end
function benchmark:resultToCSV(result)
str = result.frameSize .. "," .. self.granularity .. "," .. self.txQueues[1].dev:getLinkStatus().speed .. "," .. self.duration .. "s"
for iteration=1, self.numIterations do
str = str .. "," .. result[iteration]
end
return str
end
function benchmark:toTikz(filename, ...)
local values = {}
local numResults = select("#", ...)
for i=1, numResults do
local result = select(i, ...)
local avg = 0
local numVals = 0
for _, v in ipairs(result) do
avg = avg + v
numVals = numVals + 1
end
avg = avg / numVals
table.insert(values, {k = result.frameSize, v = avg})
end
table.sort(values, function(e1, e2) return e1.k < e2.k end)
local xtick = ""
local t64 = false
local last = -math.huge
for k, p in ipairs(values) do
if (p.k - last) >= 128 then
xtick = xtick .. p.k
if values[k + 1] then
xtick = xtick .. ","
end
last = p.k
end
end
local img = tikz.new(filename .. ".tikz", [[xlabel={packet size [byte]}, ylabel={burst size [packet]}, grid=both, ymin=0, xmin=0, xtick={]] .. xtick .. [[},scaled ticks=false, width=9cm, height=4cm, cycle list name=exotic]])
img:startPlot()
for _, p in ipairs(values) do
img:addPoint(p.k, p.v)
end
img:endPlot("average burst size")
img:startPlot()
for _, p in ipairs(values) do
local v = math.ceil((self.txQueues[1].dev:getLinkStatus().speed * 10^6 / ((p.k + 20) * 8)) * self.duration)
img:addPoint(p.k, v)
end
img:finalize("max burst size")
end
function benchmark:bench(frameSize)
if not self.initialized then
return print("benchmark not initialized");
elseif frameSize == nil then
return error("benchmark got invalid frameSize");
end
if not self.skipConf then
self:config()
end
local port = UDP_PORT
local bar = barrier.new(2)
local results = {frameSize = frameSize}
for iteration=1, self.numIterations do
printf("starting iteration %d for frame size %d", iteration, frameSize)
local loadSlave = dpdk.launchLua("backtobackLoadSlave", self.txQueues[1], frameSize, nil, bar, self.granularity, self.duration)
local counterSlave = dpdk.launchLua("backtobackCounterSlave", self.rxQueues[1], frameSize, bar, self.granularity, self.duration)
local longestS = loadSlave:wait()
local longestR = counterSlave:wait()
if longest ~= loadSlave:wait() then
printf("WARNING: loadSlave and counterSlave reported different burst sizes (sender=%d, receiver=%d)", longestS, longestR)
results[iteration] = -1
else
results[iteration] = longestS
printf("iteration %d: longest burst: %d", iteration, longestS)
end
end
if not self.skipConf then
self:undoConfig()
end
return results
end
local rsns = namespaces.get()
function sendBurst(numPkts, mem, queue, size, port, modFoo)
local sent = 0
local bufs = mem:bufArray(64)
local stop = numPkts - (numPkts % 64)
while dpdk.running() and sent < stop do
bufs:alloc(size)
for _, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
pkt.udp:setDstPort(port)
end
bufs:offloadUdpChecksums()
sent = sent + queue:send(bufs)
end
if numPkts ~= stop then
bufs = mem:bufArray(numPkts % 64)
bufs:alloc(size)
for _, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
pkt.udp:setDstPort(port)
end
bufs:offloadUdpChecksums()
sent = sent + queue:send(bufs)
end
return sent
end
function backtobackLoadSlave(queue, frameSize, modifier, bar, granularity, duration)
local ethDst = arp.blockingLookup("198.18.1.1", 10)
--TODO: error on timeout
-- gen payload template suggested by RFC2544
local udpPayloadLen = frameSize - 46
local udpPayload = ffi.new("uint8_t[?]", udpPayloadLen)
for i = 0, udpPayloadLen - 1 do
udpPayload[i] = bit.band(i, 0xf)
end
local mem = memory.createMemPool(function(buf)
local pkt = buf:getUdpPacket()
pkt:fill{
pktLength = frameSize - 4, -- self sets all length headers fields in all used protocols, -4 for FCS
ethSrc = queue, -- get the src mac from the device
ethDst = ethDst,
-- does not affect performance, as self fill is done before any packet is sent
ip4Src = "198.18.1.2",
ip4Dst = "198.19.1.2",
udpSrc = UDP_PORT,
-- udpSrc will be set later as it varies
}
-- fill udp payload with prepared udp payload
ffi.copy(pkt.payload, udpPayload, udpPayloadLen)
end)
--wait for counter slave
bar:wait()
--TODO: dirty workaround for resetting a barrier
dpdk.sleepMicros(100)
bar:reinit(2)
local linkSpeed = queue.dev:getLinkStatus().speed
local maxPkts = math.ceil((linkSpeed * 10^6 / ((frameSize + 20) * 8)) * duration) -- theoretical max packets send in about `duration` seconds with linkspeed
local count = maxPkts
local longest = 0
local binSearch = utils.binarySearch(0, maxPkts)
local first = true
while dpdk.running() do
local t = timer.new(0.5)
queue:setRate(10)
while t:running() do
sendBurst(64, mem, queue, frameSize - 4, UDP_PORT+1)
end
queue:setRate(linkSpeed)
local sent = sendBurst(count, mem, queue, frameSize - 4, UDP_PORT)
rsns.sent = sent
bar:wait()
--TODO: fix barrier reset
-- reinit interferes with wait
dpdk.sleepMicros(100)
bar:reinit(2)
-- do a binary search
-- throw away firt try
if first then
first = false
else
local top = sent == rsns.received
--get next rate
local nextCount, finished = binSearch:next(count, top, granularity)
-- update longest
longest = (top and count) or longest
if finished then
break
end
printf("loadSlave: sent %d and received %d => changing from %d to %d", sent, rsns.received, count, nextCount)
count = nextCount
end
dpdk.sleepMillis(2000)
end
return longest
end
function backtobackCounterSlave(queue, frameSize, bar, granularity, duration)
local bufs = memory.bufArray()
local maxPkts = math.ceil((queue.dev:getLinkStatus().speed * 10^6 / ((frameSize + 20) * 8)) * duration) -- theoretical max packets send in about `duration` seconds with linkspeed
local count = maxPkts
local longest = 0
local binSearch = utils.binarySearch(0, maxPkts)
local first = true
local t = timer:new(0.5)
while t:running() do
queue:tryRecv(bufs, 100)
bufs:freeAll()
end
-- wait for sender to be ready
bar:wait()
while dpdk.running() do
local timer = timer:new(duration + 2)
local counter = 0
while timer:running() do
rx = queue:tryRecv(bufs, 1000)
for i = 1, rx do
local buf = bufs[i]
local pkt = buf:getUdpPacket()
if pkt.udp:getDstPort() == UDP_PORT then
counter = counter + 1
end
end
bufs:freeAll()
if counter >= count then
break
end
end
rsns.received = counter
-- wait for sender -> both renewed value in rsns
bar:wait()
-- do a binary search
-- throw away firt try
if first then
first = false
else
local top = counter == rsns.sent
--get next rate
local nextCount, finished = binSearch:next(count, top, granularity)
-- update longest
longest = (top and count) or longest
if finished then
break
end
printf("counterSlave: sent %d and received %d => changing from %d to %d", rsns.sent, counter, count, nextCount)
count = nextCount
end
dpdk.sleepMillis(2000)
end
return longest
end
--for standalone benchmark
if standalone then
function master()
local args = utils.parseArguments(arg)
local txPort, rxPort = args.txport, args.rxport
if not txPort or not rxPort then
return print("usage: --txport <txport> --rxport <rxport> --duration <duration> --iterations <num iterations>")
end
local rxDev, txDev
if txPort == rxPort then
-- sending and receiving from the same port
txDev = device.config({port = txPort, rxQueues = 2, txQueues = 4})
rxDev = txDev
else
-- two different ports, different configuration
txDev = device.config({port = txPort, rxQueues = 2, txQueues = 4})
rxDev = device.config({port = rxPort, rxQueues = 2, txQueues = 3})
end
device.waitForLinks()
if txPort == rxPort then
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2", "198.19.1.2"}
}
})
else
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2"}
},
{
txQueue = rxDev:getTxQueue(0),
rxQueue = rxDev:getRxQueue(1),
ips = {"198.19.1.2", "198.18.1.1"}
}
})
end
local bench = benchmark()
bench:init({
txQueues = {txDev:getTxQueue(1)},
rxQueues = {rxDev:getRxQueue(0)},
granularity = 100,
duration = args.duration,
numIterations = args.iterations,
skipConf = true,
})
print(bench:getCSVHeader())
local results = {}
local FRAME_SIZES = {64, 128, 256, 512, 1024, 1280, 1518}
for _, frameSize in ipairs(FRAME_SIZES) do
local result = bench:bench(frameSize)
-- save and report results
table.insert(results, result)
print(bench:resultToCSV(result))
end
bench:toTikz("btb", unpack(results))
end
end
local mod = {}
mod.__index = mod
mod.benchmark = benchmark
return mod
| mit |
RebootRevival/FFXI_Test | scripts/globals/effects/aftermath_lv1.lua | 30 | 1130 | -----------------------------------
--
-- EFFECT_AFTERMATH_LV1
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower();
if (effect:getSubPower() == 1) then
target:addMod(MOD_ACC,power);
elseif (effect:getSubPower() == 2) then
target:addMod(MOD_MACC,power)
elseif (effect:getSubPower() == 3) then
target:addMod(MOD_RACC,power)
end
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local power = effect:getPower();
if (effect:getSubPower() == 1) then
target:delMod(MOD_ACC,power);
elseif (effect:getSubPower() == 2) then
target:delMod(MOD_MACC,power)
elseif (effect:getSubPower() == 3) then
target:delMod(MOD_RACC,power)
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Port_San_dOria/npcs/Rugiette.lua | 3 | 2400 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Rugiette
-- Involved in Quests: Riding on the Clouds, Lure of the Wildcat (San d'Oria)
-- !pos 71 -9 -73 232
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer
player:messageSpecial(FLYER_REFUSED);
end
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 8) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_1",0);
player:tradeComplete();
player:addKeyItem(SCOWLING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatSandy = player:getVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,14) == false) then
player:startEvent(746);
else
player:startEvent(601);
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 == 746) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",14,true);
elseif (csid == 601) then
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_AVAILABLE and player:getVar("FFR") == 0) then
player:setVar("FFR",1);
end
end
end; | gpl-3.0 |
iovisor/bcc | src/lua/bpf/cdef.lua | 4 | 9392 | --[[
Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require('ffi')
local bit = require('bit')
local has_syscall, S = pcall(require, 'syscall')
local M = {}
ffi.cdef [[
struct bpf {
/* Instruction classes */
static const int LD = 0x00;
static const int LDX = 0x01;
static const int ST = 0x02;
static const int STX = 0x03;
static const int ALU = 0x04;
static const int JMP = 0x05;
static const int ALU64 = 0x07;
/* ld/ldx fields */
static const int W = 0x00;
static const int H = 0x08;
static const int B = 0x10;
static const int ABS = 0x20;
static const int IND = 0x40;
static const int MEM = 0x60;
static const int LEN = 0x80;
static const int MSH = 0xa0;
/* alu/jmp fields */
static const int ADD = 0x00;
static const int SUB = 0x10;
static const int MUL = 0x20;
static const int DIV = 0x30;
static const int OR = 0x40;
static const int AND = 0x50;
static const int LSH = 0x60;
static const int RSH = 0x70;
static const int NEG = 0x80;
static const int MOD = 0x90;
static const int XOR = 0xa0;
static const int JA = 0x00;
static const int JEQ = 0x10;
static const int JGT = 0x20;
static const int JGE = 0x30;
static const int JSET = 0x40;
static const int K = 0x00;
static const int X = 0x08;
static const int JNE = 0x50; /* jump != */
static const int JSGT = 0x60; /* SGT is signed '>', GT in x86 */
static const int JSGE = 0x70; /* SGE is signed '>=', GE in x86 */
static const int CALL = 0x80; /* function call */
static const int EXIT = 0x90; /* function return */
/* ld/ldx fields */
static const int DW = 0x18; /* double word */
static const int XADD = 0xc0; /* exclusive add */
/* alu/jmp fields */
static const int MOV = 0xb0; /* mov reg to reg */
static const int ARSH = 0xc0; /* sign extending arithmetic shift right */
/* change endianness of a register */
static const int END = 0xd0; /* flags for endianness conversion: */
static const int TO_LE = 0x00; /* convert to little-endian */
static const int TO_BE = 0x08; /* convert to big-endian */
/* misc */
static const int PSEUDO_MAP_FD = 0x01;
/* helper functions */
static const int F_CURRENT_CPU = 0xffffffff;
static const int F_USER_STACK = 1 << 8;
static const int F_FAST_STACK_CMP = 1 << 9;
static const int F_REUSE_STACKID = 1 << 10;
/* special offsets for ancillary data */
static const int NET_OFF = -0x100000;
static const int LL_OFF = -0x200000;
};
/* eBPF commands */
struct bpf_cmd {
static const int MAP_CREATE = 0;
static const int MAP_LOOKUP_ELEM = 1;
static const int MAP_UPDATE_ELEM = 2;
static const int MAP_DELETE_ELEM = 3;
static const int MAP_GET_NEXT_KEY = 4;
static const int PROG_LOAD = 5;
static const int OBJ_PIN = 6;
static const int OBJ_GET = 7;
};
/* eBPF helpers */
struct bpf_func_id {
static const int unspec = 0;
static const int map_lookup_elem = 1;
static const int map_update_elem = 2;
static const int map_delete_elem = 3;
static const int probe_read = 4;
static const int ktime_get_ns = 5;
static const int trace_printk = 6;
static const int get_prandom_u32 = 7;
static const int get_smp_processor_id = 8;
static const int skb_store_bytes = 9;
static const int l3_csum_replace = 10;
static const int l4_csum_replace = 11;
static const int tail_call = 12;
static const int clone_redirect = 13;
static const int get_current_pid_tgid = 14;
static const int get_current_uid_gid = 15;
static const int get_current_comm = 16;
static const int get_cgroup_classid = 17;
static const int skb_vlan_push = 18;
static const int skb_vlan_pop = 19;
static const int skb_get_tunnel_key = 20;
static const int skb_set_tunnel_key = 21;
static const int perf_event_read = 22;
static const int redirect = 23;
static const int get_route_realm = 24;
static const int perf_event_output = 25;
static const int skb_load_bytes = 26;
static const int get_stackid = 27;
};
/* BPF_MAP_STACK_TRACE structures and constants */
static const int BPF_MAX_STACK_DEPTH = 127;
struct bpf_stacktrace {
uint64_t ip[BPF_MAX_STACK_DEPTH];
};
]]
-- Compatibility: ljsyscall doesn't have support for BPF syscall
if not has_syscall or not S.bpf then
error("ljsyscall doesn't support bpf(), must be updated")
else
local strflag = require('syscall.helpers').strflag
-- Compatibility: ljsyscall<=0.12
if not S.c.BPF_MAP.LRU_HASH then
S.c.BPF_MAP = strflag {
UNSPEC = 0,
HASH = 1,
ARRAY = 2,
PROG_ARRAY = 3,
PERF_EVENT_ARRAY = 4,
PERCPU_HASH = 5,
PERCPU_ARRAY = 6,
STACK_TRACE = 7,
CGROUP_ARRAY = 8,
LRU_HASH = 9,
LRU_PERCPU_HASH = 10,
LPM_TRIE = 11,
ARRAY_OF_MAPS = 12,
HASH_OF_MAPS = 13,
DEVMAP = 14,
SOCKMAP = 15,
CPUMAP = 16,
}
end
if not S.c.BPF_PROG.TRACEPOINT then
S.c.BPF_PROG = strflag {
UNSPEC = 0,
SOCKET_FILTER = 1,
KPROBE = 2,
SCHED_CLS = 3,
SCHED_ACT = 4,
TRACEPOINT = 5,
XDP = 6,
PERF_EVENT = 7,
CGROUP_SKB = 8,
CGROUP_SOCK = 9,
LWT_IN = 10,
LWT_OUT = 11,
LWT_XMIT = 12,
SOCK_OPS = 13,
SK_SKB = 14,
CGROUP_DEVICE = 15,
SK_MSG = 16,
RAW_TRACEPOINT = 17,
CGROUP_SOCK_ADDR = 18,
}
end
end
-- Compatibility: metatype for stacktrace
local function stacktrace_iter(t, i)
i = i + 1
if i < #t and t.ip[i] > 0 then
return i, t.ip[i]
end
end
ffi.metatype('struct bpf_stacktrace', {
__len = function (t) return ffi.sizeof(t.ip) / ffi.sizeof(t.ip[0]) end,
__ipairs = function (t) return stacktrace_iter, t, -1 end,
})
-- Reflect cdata type
function M.typename(v)
if not v or type(v) ~= 'cdata' then return nil end
return string.match(tostring(ffi.typeof(v)), '<([^>]+)')
end
-- Reflect if cdata type can be pointer (accepts array or pointer)
function M.isptr(v, noarray)
local ctname = M.typename(v)
if ctname then
ctname = string.sub(ctname, -1)
ctname = ctname == '*' or (not noarray and ctname == ']')
end
return ctname
end
-- Return true if variable is a non-nil constant that can be used as immediate value
-- e.g. result of KSHORT and KNUM
function M.isimmconst(v)
return (type(v.const) == 'number' and not ffi.istype(v.type, ffi.typeof('void')))
or type(v.const) == 'cdata' and ffi.istype(v.type, ffi.typeof('uint64_t')) -- Lua numbers are at most 52 bits
or type(v.const) == 'cdata' and ffi.istype(v.type, ffi.typeof('int64_t'))
end
function M.osversion()
-- We have no better way to extract current kernel hex-string other
-- than parsing headers, compiling a helper function or reading /proc
local ver_str, count = S.sysctl('kernel.version'):match('%d+.%d+.%d+'), 2
if not ver_str then -- kernel.version is freeform, fallback to kernel.osrelease
ver_str = S.sysctl('kernel.osrelease'):match('%d+.%d+.%d+')
end
local version = 0
for i in ver_str:gmatch('%d+') do -- Convert 'X.Y.Z' to 0xXXYYZZ
version = bit.bor(version, bit.lshift(tonumber(i), 8*count))
count = count - 1
end
return version
end
function M.event_reader(reader, event_type)
-- Caller can specify event message binary format
if event_type then
assert(type(event_type) == 'string' and ffi.typeof(event_type), 'not a valid type for event reader')
event_type = ffi.typeof(event_type .. '*') -- Convert type to pointer-to-type
end
-- Wrap reader in interface that can interpret read event messages
return setmetatable({reader=reader,type=event_type}, {__index = {
block = function(_ --[[self]])
return S.select { readfds = {reader.fd} }
end,
next = function(_ --[[self]], k)
local len, ev = reader:next(k)
-- Filter out only sample frames
while ev and ev.type ~= S.c.PERF_RECORD.SAMPLE do
len, ev = reader:next(len)
end
if ev and event_type then
-- The perf event reader returns framed data with header and variable length
-- This is going skip the frame header and cast data to given type
ev = ffi.cast(event_type, ffi.cast('char *', ev) + ffi.sizeof('struct perf_event_header') + ffi.sizeof('uint32_t'))
end
return len, ev
end,
read = function(self)
return self.next, self, nil
end,
}})
end
function M.tracepoint_type(tp)
-- Read tracepoint format string
local fp = assert(io.open('/sys/kernel/debug/tracing/events/'..tp..'/format', 'r'))
local fmt = fp:read '*a'
fp:close()
-- Parse struct fields
local fields = {}
for f in fmt:gmatch 'field:([^;]+;)' do
table.insert(fields, f)
end
return string.format('struct { %s }', table.concat(fields))
end
return M
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/globals/abilities/pets/attachments/heat_seeker.lua | 4 | 2220 | -----------------------------------
-- Attachment: Heat Seeker
-----------------------------------
require("scripts/globals/status")
-----------------------------------
-- onUseAbility
-----------------------------------
function onEquip(pet)
pet:addListener("ENGAGE", "AUTO_HEAT_SEEKER_ENGAGE", function(pet, target)
pet:setLocalVar("heatseekertick", VanadielTime())
end)
pet:addListener("AUTOMATON_AI_TICK", "AUTO_HEAT_SEEKER_TICK", function(pet, target)
if pet:getLocalVar("heatseekertick") > 0 then
local master = pet:getMaster()
local maneuvers = master:countEffect(EFFECT_THUNDER_MANEUVER)
local lasttick = pet:getLocalVar("heatseekertick")
local tick = VanadielTime()
local dt = tick - lasttick
local prevamount = pet:getLocalVar("heatseeker")
local amount = 0
if maneuvers > 0 then
amount = maneuvers * dt
if (amount + prevamount) > 30 then
amount = 30 - prevamount
end
if amount ~= 0 then
pet:addMod(MOD_ACC, amount)
end
else
amount = -1 * dt
if (amount + prevamount) < 0 then
amount = -prevamount
end
if amount ~= 0 then
pet:delMod(MOD_ACC, -amount)
end
end
if amount ~= 0 then
pet:setLocalVar("heatseeker", prevamount + amount)
end
pet:setLocalVar("heatseekertick", tick)
end
end)
pet:addListener("DISENGAGE", "AUTO_HEAT_SEEKER_DISENGAGE", function(pet)
if pet:getLocalVar("heatseeker") > 0 then
pet:delMod(MOD_ACC, pet:getLocalVar("heatseeker"))
pet:setLocalVar("heatseeker", 0)
end
pet:setLocalVar("heatseekertick", 0)
end)
end
function onUnequip(pet)
pet:removeListener("AUTO_HEAT_SEEKER_ENGAGE")
pet:removeListener("AUTO_HEAT_SEEKER_TICK")
pet:removeListener("AUTO_HEAT_SEEKER_DISENGAGE")
end
function onManeuverGain(pet,maneuvers)
end
function onManeuverLose(pet,maneuvers)
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/items/wild_cookie.lua | 12 | 1346 | -----------------------------------------
-- ID: 4577
-- Item: wild_cookie
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Aquan killer +12
-- Silence resistance +12
-- MP recovered while healing +5
-----------------------------------------
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,4577);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AQUAN_KILLER, 12);
target:addMod(MOD_SILENCERES, 12);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AQUAN_KILLER, 12);
target:delMod(MOD_SILENCERES, 12);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Balgas_Dais/mobs/Maat.lua | 14 | 1549 | -----------------------------------
-- Area: Balga Dais
-- MOB: Maat
-- Genkai 5 Fight
-----------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Balgas_Dais/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
-- target:showText(mob,YOU_DECIDED_TO_SHOW_UP);
printf("Maat Balga Dais works");
-- When he take damage: target:showText(mob,THAT_LL_HURT_IN_THE_MORNING);
-- He use dragon kick or tackle: target:showText(mob,TAKE_THAT_YOU_WHIPPERSNAPPER);
-- He use spining attack: target:showText(mob,TEACH_YOU_TO_RESPECT_ELDERS);
-- If you dying: target:showText(mob,LOOKS_LIKE_YOU_WERENT_READY);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local bf = mob:getBattlefield();
if (mob:getHPP() <20) then
bf:win();
return;
-- WHM's Maat additionally gives up if kept fighting for 5 min
elseif (target:getMainJob() == JOBS.WHM and mob:getBattleTime() > 300) then
bf:win();
return;
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob,YOUVE_COME_A_LONG_WAY);
end;
| gpl-3.0 |
blackzw/openwrt_sdk_dev1 | staging_dir/target-mips_r2_uClibc-0.9.33.2/root-ar71xx/usr/lib/lua/luci/webapi/UserSettings.lua | 1 | 2769 | module("luci.webapi.UserSettings", package.seeall)
local common = require('luci.webapi.Util')
--[[
Get User Settings
Parameters
Return value:
[{
"DeviceName":"iphone5s",
"DeviceIP":"192.168.17",
"DeviceMac":"f8:1e:df:e4:ed:8b",
"DeviceType":"1",
"InternetRight":"0",
"StorageRight":"0"
},¡]
]]
function GetUserSettings()
local rsp = {}
local nwItem = {}
local userlist = common.GetValueList("acl", "device") --etc/config/acl
if userlist == nil then
errs = {code=190101, message="Get User Settings list info failed."}
return nil, errs
end
rsp["List"] = {}
for i=1,table.getn(userlist.valuelist) do
nwItem = {}
nwItem["DeviceName"] = userlist.valuelist[i]["name"]
nwItem["DeviceIP"] = ""
nwItem["DeviceMac"] = ""
if userlist.valuelist[i]["type"] == "default" then
nwItem["DeviceType"] = 0
else
nwItem["DeviceType"] = 1
end
if userlist.valuelist[i]["internet"] == 0 or userlist.valuelist[i]["internet"] == "0" then
nwItem["InternetRight"] = 0
else
nwItem["InternetRight"] = 1
end
if userlist.valuelist[i]["storage"] == 0 or userlist.valuelist[i]["storage"] == "0" then
nwItem["StorageRight"] = 0
else
nwItem["StorageRight"] = 1
end
rsp["List"][i] = nwItem
end
return rsp
end
--[[
Set User Settings
Parameters
[{
"DeviceName":"iphone5s",
"DeviceIP":"192.168.17",
"DeviceMac":"f8:1e:df:e4:ed:8b",
"DeviceType":"1",
"InternetRight":"0",
"StorageRight":"0"
},¡]
Return value:
null
]]
function SetUserSettings(req)
local userlist = req["List"]
if userlist == nil then
errs = {code=7, message="Bad parameter"}
return nil, errs
end
local ret = common.DeleteSection("acl", "device") --etc/config/acl
if ret == false then
errs = {code=190201, message="Set User Settings failed."}
return nil, errs
end
for i=1,table.getn(userlist) do
nwItem = {}
nwItem["name"] = userlist[i]["DeviceName"]
nwItem["internet"] = userlist[i]["InternetRight"]
nwItem["storage"] = userlist[i]["StorageRight"]
if userlist[i]["DeviceType"] == 0 or userlist[i]["DeviceType"] == "0" then
nwItem["type"] = "default"
else
nwItem["type"] = ""
end
ret = common.AddSection("acl", "device", nil, nwItem)
if ret == false then
errs = {code=190201, message="Set User Settings failed."}
return nil, errs
end
end
ret = common.SaveFile("acl")
if ret == false then
errs = {code=190201, message="Set User Settings failed."}
return nil, errs
end
ret = common.Exec("/etc/init.d/firewall restart") -- restart firewall
if ret == false then
errs = {code=190201, message="Set User Settings failed."}
return nil, errs
end
return luci.json.null
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/items/high_breath_mantle.lua | 43 | 1427 | -----------------------------------------
-- ID: 15487
-- Item: High Breath Mantle
-- Item Effect: HP+38 / Enmity+5
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local effect = target:getStatusEffect(EFFECT_ENCHANTMENT);
if (effect ~= nil) then
if (effect:getSubType() == 15487) then
target:delStatusEffect(EFFECT_ENCHANTMENT);
end;
end;
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
if (target:hasStatusEffect(EFFECT_ENCHANTMENT) == true) then
target:delStatusEffect(EFFECT_ENCHANTMENT);
target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,1800,15487);
else
target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,1800,15487);
end;
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 38);
target:addMod(MOD_ENMITY, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 38);
target:delMod(MOD_ENMITY, 5);
end; | gpl-3.0 |
lzyzsd/ABTestingGateway | lib/abtesting/error/errcode.lua | 22 | 1583 | local modulename = 'abtestingErrorInfo'
local _M = {}
_M._VERSION = '0.0.1'
_M.info = {
-- index code desc
-- SUCCESS
["SUCCESS"] = { 200, 'success '},
-- System Level ERROR
['REDIS_ERROR'] = { 40101, 'redis error for '},
['POLICY_DB_ERROR'] = { 40102, 'policy in db error '},
['RUNTIME_DB_ERROR'] = { 40103, 'runtime info in db error '},
['LUA_RUNTIME_ERROR'] = { 40201, 'lua runtime error '},
['BLANK_INFO_ERROR'] = { 40202, 'errinfo blank in handler '},
-- Service Level ERROR
-- input or parameter error
['PARAMETER_NONE'] = { 50101, 'expected parameter for '},
['PARAMETER_ERROR'] = { 50102, 'parameter error for '},
['PARAMETER_NEEDED'] = { 50103, 'need parameter for '},
['PARAMETER_TYPE_ERROR'] = { 50104, 'parameter type error for '},
-- input policy error
['POLICY_INVALID_ERROR'] = { 50201, 'policies invalid for ' },
['POLICY_BUSY_ERROR'] = { 50202, 'policy is busy and policyID is ' },
-- redis connect error
['REDIS_CONNECT_ERROR'] = { 50301, 'redis connect error for '},
['REDIS_KEEPALIVE_ERROR'] = { 50302, 'redis keepalive error for '},
-- runtime error
['POLICY_BLANK_ERROR'] = { 50401, 'policy contains no data '},
['RUNTIME_BLANK_ERROR'] = { 50402, 'expect runtime info for '},
['MODULE_BLANK_ERROR'] = { 50403, 'no required module for '},
['USERINFO_BLANK_ERROR'] = { 50404, 'no userinfo fetched from '},
-- unknown reason
['UNKNOWN_ERROR'] = { 50501, 'unknown reason '},
}
return _M
| mit |
RebootRevival/FFXI_Test | scripts/zones/Temenos/mobs/Telchines_Bard.lua | 28 | 1126 | -----------------------------------
-- Area: Temenos N T
-- NPC: Telchines_Bard
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (IsMobDead(16928788)==true and IsMobDead(16928789)==true and IsMobDead(16928792)==true and IsMobDead(16928793)==true ) then
GetNPCByID(16928768+26):setPos(19,80,430);
GetNPCByID(16928768+26):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+160):setPos(16,80,430);
GetNPCByID(16928768+160):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+211):setPos(22,80,430);
GetNPCByID(16928768+211):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
blackzw/openwrt_sdk_dev1 | staging_dir/target-mips_r2_uClibc-0.9.33.2/root-ar71xx/usr/lib/lua/luci/model/cbi/admin_network/iface_add.lua | 1 | 3153 | --[[
LuCI - Lua Configuration Interface
Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: iface_add.lua 9655 2013-01-27 18:43:41Z jow $
]]--
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/basicsettings/lan")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "uciname"
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/basicsettings/lan/lansettings", name))
end
end
return m
| gpl-2.0 |
padrinoo1/telegeek | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
Goodzilam/Goodzila-bot_v1.5 | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/abilities/curing_waltz_iv.lua | 4 | 2582 | -----------------------------------
-- Ability: Curing Waltz IV
-- Heals HP to target player.
-- Obtained: Dancer Level 70
-- TP Required: 65%
-- Recast Time: 00:17
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/msg");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return msgBasic.CANNOT_ON_THAT_TARG,0;
elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then
return msgBasic.UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 650) then
return msgBasic.NOT_ENOUGH_TP,0;
else
--[[ Apply "Waltz Ability Delay" reduction
1 modifier = 1 second]]
local recastMod = player:getMod(MOD_WALTZ_DELAY);
if (recastMod ~= 0) then
local newRecast = ability:getRecast() +recastMod;
ability:setRecast(utils.clamp(newRecast,0,newRecast));
end
-- Apply "Fan Dance" Waltz recast reduction
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
local fanDanceMerits = target:getMerit(MERIT_FAN_DANCE);
-- Every tier beyond the 1st is -5% recast time
if (fanDanceMerits > 5) then
ability:setRecast(ability:getRecast() * ((fanDanceMerits -5)/100));
end
end
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(650);
end;
--Grabbing variables.
local vit = target:getStat(MOD_VIT);
local chr = player:getStat(MOD_CHR);
local mjob = player:getMainJob(); --19 for DNC main.
local cure = 0;
--Performing mj check.
if (mjob == 19) then
cure = (vit+chr)+450;
end
-- apply waltz modifiers
cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100)));
--Reducing TP.
--Applying server mods....
cure = cure * CURE_POWER;
--Cap the final amount to max HP.
if ((target:getMaxHP() - target:getHP()) < cure) then
cure = (target:getMaxHP() - target:getHP());
end
--Do it
target:restoreHP(cure);
target:wakeUp();
player:updateEnmityFromCure(target,cure);
return cure;
end;
| gpl-3.0 |
CCAAHH/telegram-bot-supergroups | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
AmirPGA/pgahide | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Bastok_Mines/npcs/Gumbah.lua | 17 | 2154 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Gumbah
-- Finishes Quest: Blade of Darkness
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local bladeDarkness = player:getQuestStatus(BASTOK, BLADE_OF_DARKNESS);
if (player:getMainLvl() >= ADVANCED_JOB_LEVEL and bladeDarkness == QUEST_AVAILABLE) then
--DARK KNIGHT QUEST
player:startEvent(0x0063);
elseif (bladeDarkness == QUEST_COMPLETED and player:getQuestStatus(BASTOK,BLADE_OF_DEATH) == QUEST_AVAILABLE) then
player:startEvent(0x0082);
elseif ((player:hasCompletedMission(BASTOK, ON_MY_WAY) == true)
or ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 3)))
and (player:getVar("[B7-2]Werei") == 0) then
player:startEvent(0x00b1);
else
--DEFAULT
player:startEvent(0x0034);
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 == 0x0063) then
player:addQuest(BASTOK, BLADE_OF_DARKNESS);
elseif (csid == 0x0082) then
player:addQuest(BASTOK, BLADE_OF_DEATH);
player:addKeyItem(LETTER_FROM_ZEID);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_ZEID);
elseif (csid == 0x00b1) then
player:setVar("[B7-2]Werei", 1);
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/items/plate_of_dulcet_panettones.lua | 12 | 1385 | -----------------------------------------
-- ID: 5979
-- Item: Plate of Dulcet Panettones
-- Food Effect: 240 Min, All Races
-----------------------------------------
-- MP % 6 Cap 105
-- Intelligence +8
-- MP Healing +4
-----------------------------------------
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,14400,5979);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 6);
target:addMod(MOD_FOOD_MP_CAP, 105);
target:addMod(MOD_INT, 8);
target:addMod(MOD_MPHEAL, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 6);
target:delMod(MOD_FOOD_MP_CAP, 105);
target:delMod(MOD_INT, 8);
target:delMod(MOD_MPHEAL, 4);
end;
| gpl-3.0 |
iRonJ/Crepe | train/scroll.lua | 5 | 3639 | --[[ The schollable UI
By Xiang Zhang @ New York University
--]]
local Scroll = torch.class("Scroll")
-- Initialize a scroll interface
-- width: (optional) the pixel width of the scollable area. Default is 800.
-- title: (optional) title for the window
function Scroll:__init(width,title)
require("qtuiloader")
require("qtwidget")
require("qttorch")
self.file = "scroll.ui"
self.win = qtuiloader.load(self.file)
self.frame = self.win.frame
self.painter = qt.QtLuaPainter(self.frame)
self.width = width
self.height = 0
self.fontSize = 15
self.x = 0
self.y = 0
self.border = 1
self:resize(self.width, self.height)
self:setFontSize(self.fontSize)
if title then
self:setTitle(title)
end
self:show()
end
-- Resize the window to designated width and height
function Scroll:resize(width,height)
self.width = width or self.width
self.height = height or self.height
self.frame.size = qt.QSize{width = self.width,height = self.height}
end
-- Set the text width
function Scroll:setFontSize(size)
self.painter:setfontsize(size or 15)
self.fontSize = size
end
-- Set border width
function Scroll:setBorder(width)
self.border = width
end
-- Draw text
function Scroll:drawText(text)
-- Drawing text must happen on a new line
if self.x ~= 0 then
self.x = 0
self.y = self.height
end
-- Determine height and resize if necessary
if self.height < self.y+self.fontSize+1 then
self:resize(self.width,self.y+self.fontSize+1+self.border)
end
-- Draw the yellow main text
self.painter:gbegin()
self.painter:moveto(self.x,self.y+self.fontSize-1)
self.painter:setcolor(1,1,0,1)
self.painter:show(text)
self.painter:stroke()
self.painter:gend()
-- Draw the black shadow text
self.painter:gbegin()
self.painter:moveto(self.x,self.y+self.fontSize+1-1)
self.painter:setcolor(0,0,0,1)
self.painter:show(text)
self.painter:stroke()
self.painter:gend()
-- Move the cursor to next line
self.x = 0
if self.height < self.y+self.fontSize+1+self.border then
self:resize(self.width,self.y+self.fontSize+1+self.border)
end
self.y = self.height
end
-- Draw image
function Scroll:drawImage(im,scale)
-- Get the image height and width
local scale = scale or 1
local height,width
if im:dim() == 2 then
height = im:size(1)*scale
width = im:size(2)*scale
elseif im:dim() == 3 then
height = im:size(2)*scale
width = im:size(3)*scale
else
error("Image must be 2-dim or 3-dim data")
end
-- Determine whether a new line is needed
if self.x ~=0 and self.x + width > self.width then
self.x = 0
self.y = self.height
end
-- Determine whether need to resize the document area
if self.y + height > self.height then
self:resize(self.width,self.y+height+self.border)
end
-- Draw the image
self.painter:gbegin()
self.painter:image(self.x,self.y,width,height,qt.QImage.fromTensor(im))
self.painter:stroke()
self.painter:gend()
-- Move the cursor
self.x = self.x + width + self.border
end
-- Draw a new line
function Scroll:drawEndOfLine()
self.x = 0
self.y = self.height
end
-- Show the window
function Scroll:show()
self.win:show()
end
-- Hide the window
function Scroll:hide()
self.win:hide()
end
-- Save to file
function Scroll:save(file)
self.painter:write(file)
end
-- Set window title
function Scroll:setTitle(title)
self.win:setWindowTitle(title)
end
-- Reset the drawing area
function Scroll:clear()
self:resize(self.width,0)
self.x = 0
self.y = 0
end
| bsd-3-clause |
imashkan/firesbss | plugins/id.lua | 50 | 4275 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
for k,v in pairs(result.members) do
text = text .. v.print_name .. " (user#id" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "ایدی" then
local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')'
if is_chat_msg(msg) then
text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
elseif matches[1] == "member" and matches[2] == "@" then
local nick = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local receiver = extra.receiver
local nick = extra.nick
local found
for k,user in pairs(result.members) do
if user.username == nick then
found = user
end
end
if not found then
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = "ID: "..found.id
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, nick=nick})
elseif matches[1] == "members" and matches[2] == "name" then
local text = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local members = result.members
local receiver = extra.receiver
local text = extra.text
local founds = {}
for k,member in pairs(members) do
local fields = {'first_name', 'print_name', 'username'}
for k,field in pairs(fields) do
if member[field] and type(member[field]) == "string" then
if member[field]:match(text) then
local id = tostring(member.id)
founds[id] = member
end
end
end
end
if next(founds) == nil then -- Empty table
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = ""
for k,user in pairs(founds) do
local first_name = user.first_name or ""
local print_name = user.print_name or ""
local user_name = user.user_name or ""
local id = user.id or "" -- This would be funny
text = text.."First name: "..first_name.."\n"
.."Print name: "..print_name.."\n"
.."User name: "..user_name.."\n"
.."ID: "..id
end
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, text=text})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"ایدی: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id member @<user_name>: Return the member @<user_name> ID from the current chat",
"!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat"
},
patterns = {
"^ایدی$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (member) (@)(.+)",
"^!id (members) (name) (.+)"
},
run = run
}
| gpl-2.0 |
openwrt-es/openwrt-luci | applications/luci-app-dnscrypt-proxy/luasrc/controller/dnscrypt-proxy.lua | 5 | 2121 | -- Copyright 2017-2019 Dirk Brenken (dev@brenken.org)
-- This is free software, licensed under the Apache License, Version 2.0
module("luci.controller.dnscrypt-proxy", package.seeall)
local util = require("luci.util")
local i18n = require("luci.i18n")
local templ = require("luci.template")
function index()
if not nixio.fs.access("/etc/config/dnscrypt-proxy") then
nixio.fs.writefile("/etc/config/dnscrypt-proxy", "")
end
entry({"admin", "services", "dnscrypt-proxy"}, firstchild(), _("DNSCrypt-Proxy"), 60).dependent = false
entry({"admin", "services", "dnscrypt-proxy", "tab_from_cbi"}, cbi("dnscrypt-proxy/overview_tab", {hideresetbtn=true, hidesavebtn=true}), _("Overview"), 10).leaf = true
entry({"admin", "services", "dnscrypt-proxy", "logfile"}, call("logread"), _("View Logfile"), 20).leaf = true
entry({"admin", "services", "dnscrypt-proxy", "advanced"}, firstchild(), _("Advanced"), 100)
entry({"admin", "services", "dnscrypt-proxy", "advanced", "configuration"}, form("dnscrypt-proxy/configuration_tab"), _("Edit DNSCrypt-Proxy Configuration"), 110).leaf = true
entry({"admin", "services", "dnscrypt-proxy", "advanced", "cfg_dnsmasq"}, form("dnscrypt-proxy/cfg_dnsmasq_tab"), _("Edit Dnsmasq Configuration"), 120).leaf = true
entry({"admin", "services", "dnscrypt-proxy", "advanced", "cfg_resolvcrypt"}, form("dnscrypt-proxy/cfg_resolvcrypt_tab"), _("Edit Resolvcrypt Configuration"), 130).leaf = true
entry({"admin", "services", "dnscrypt-proxy", "advanced", "view_reslist"}, call("view_reslist"), _("View Resolver List"), 140).leaf = true
end
function view_reslist()
local reslist = util.trim(util.exec("cat /usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv"))
templ.render("dnscrypt-proxy/view_reslist", {title = i18n.translate("DNSCrypt-Proxy Resolver List"), content = reslist})
end
function logread()
local logfile = util.trim(util.exec("logread -e 'dnscrypt-proxy' 2>/dev/null")) or ""
if logfile == "" then
logfile = "No DNSCrypt-Proxy related logs yet!"
end
templ.render("dnscrypt-proxy/logread", {title = i18n.translate("DNSCrypt-Proxy Logfile"), content = logfile})
end
| apache-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Inner_Horutoto_Ruins/Zone.lua | 12 | 4654 | -----------------------------------
--
-- Zone: Inner_Horutoto_Ruins (192)
--
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/zone");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -261, -1, -31, -257, 1, -27); -- Red
zone:registerRegion(2, -265, -1, -26, -261, 1, -22); -- White
zone:registerRegion(3, -258, -1, -26, -254, 1, -22); -- Black
zone:registerRegion(4, -261, -3, 182, -257, -1, 186); -- Teleport at H-6
UpdateTreasureSpawnPoint(17563914);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-259.996,6.399,242.859,67);
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)
local circle= 17563861;
local red = GetNPCByID(circle);
local white = GetNPCByID(circle+1);
local black = GetNPCByID(circle+2);
-- Prevent negatives..
if (region:GetCount() < 0) then
region:AddCount( math.abs( region:GetCount() ) );
end
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Red Circle
if (player:getMainJob() == JOBS.RDM and region:AddCount(1) == 1) then
red:setAnimation(8);
if (white:getAnimation() == 8 and black:getAnimation() == 8) then
GetNPCByID(circle+3):openDoor(30);
GetNPCByID(circle+4):openDoor(30);
end
end
end,
[2] = function (x) -- White Circle
if (player:getMainJob() == JOBS.WHM and region:AddCount(1) == 1) then
white:setAnimation(8);
if (red:getAnimation() == 8 and black:getAnimation() == 8) then
GetNPCByID(circle+3):openDoor(30);
GetNPCByID(circle+4):openDoor(30);
end
end
end,
[3] = function (x) -- Black Circle
if (player:getMainJob() == JOBS.BLM and region:AddCount(1) == 1) then
black:setAnimation(8);
if (red:getAnimation() == 8 and white:getAnimation() == 8) then
GetNPCByID(circle+3):openDoor(30);
GetNPCByID(circle+4):openDoor(30);
end
end
end,
[4] = function (x) -- Teleport at H-6
player:setPos(-260,0,-21,65);
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
local circle= 17563860;
local red = GetNPCByID(circle);
local white = GetNPCByID(circle+1);
local black = GetNPCByID(circle+2);
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Red Circle
if (player:getMainJob() == JOBS.RDM and region:DelCount(1) == 0) then
red:setAnimation(9);
end
end,
[2] = function (x) -- White Circle
if (player:getMainJob() == JOBS.WHM and region:DelCount(1) == 0) then
white:setAnimation(9);
end
end,
[3] = function (x) -- Black Circle
if (player:getMainJob() == JOBS.BLM and region:DelCount(1) == 0) then
black:setAnimation(9);
end
end,
}
-- Prevent negatives..
if (region:GetCount() < 0) then
region:AddCount( math.abs( region:GetCount() ) );
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 |
RebootRevival/FFXI_Test | scripts/zones/Mhaura/npcs/Tya_Padolih.lua | 3 | 1472 | -----------------------------------
-- Area: Mhaura
-- NPC: Tya Padolih
-- Standard Merchant NPC
-- !pos -48 -4 30 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TYAPADOLIH_SHOP_DIALOG);
stock = {0x126c,4147, --Scroll of Regen
0x126e,7516, --Scroll of Regen II
0x1311,10752, --Scroll of Sleepga
0x1252,29030, --Scroll of Baramnesia
0x1253,29030, --Scroll of Baramnesra
0x1288,5523, --Scroll of Invisible
0x1289,2400, --Scroll of Sneak
0x128a,1243, --Scroll of Deodorize
0x1330,18032} --Scroll of Distract
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 |
RebootRevival/FFXI_Test | scripts/zones/Bastok_Mines/npcs/Gelzerio.lua | 17 | 1737 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Galzerio
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,GELZERIO_SHOP_DIALOG);
stock = {
0x338E, 19602,1, --Swordbelt
0x43ED, 486,1, --Bamboo Fishing Rod
0x43F4, 3,2, --Little Worm
0x43EE, 212,2, --Yew Fishing Rod
0x338C, 10054,3, --Silver Belt
0x43F3, 10,3, --Lugworm
0x43EF, 64,3, --Willow Fishing Rod
0x3138, 216,3, --Robe
0x31B8, 118,3, --Cuffs
0x3238, 172,3, --Slops
0x32B8, 111,3, --Ash Clogs
0x30B0, 1742,3, --Headgear
0x3130, 2470,3, --Doublet
0x31B0, 1363,3, --Gloves
0x3230, 1899,3, --Brais
0x32B0, 1269,3 --Gaiters
}
showNationShop(player, NATION_BASTOK, 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 |
RebootRevival/FFXI_Test | scripts/zones/Castle_Oztroja/mobs/Yagudo_Interrogator.lua | 3 | 1028 | -----------------------------------
-- Area: Castle Oztroja (151)
-- MOB: Yagudo_Interrogator
-----------------------------------
require("scripts/zones/Castle_Oztroja/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
if (Mee_Deggi_the_Punisher_PH[mobID] ~= nil) then
local ToD = GetServerVariable("[POP]Mee_Deggi_the_Punisher");
if (ToD <= os.time() and GetMobAction(Mee_Deggi_the_Punisher) == 0) then
if (math.random(1,20) == 5) then
UpdateNMSpawnPoint(Mee_Deggi_the_Punisher);
GetMobByID(Mee_Deggi_the_Punisher):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Mee_Deggi_the_Punisher", mobID);
DisallowRespawn(mobID, true);
end
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/weaponskills/glory_slash.lua | 19 | 1581 | -----------------------------------
-- Glory Slash
-- Sword weapon skill
-- Skill Level: NA
-- Only avaliable during Campaign Battle while weilding Lex Talionis.
-- Delivers and area attack that deals triple damage. Damage varies with TP. Additional effect Stun.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: Light
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 3.00 3.50 4.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3.5; params.ftp300 = 4;
params.str_wsc = 0.3; params.dex_wsc = 0.0; 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 (damage > 0) then
local duration = (tp/500);
if (target:hasStatusEffect(EFFECT_STUN) == false) then
target:addStatusEffect(EFFECT_STUN, 1, 0, duration);
end
end
local damage, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, damage;
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/GM_Home/npcs/Trader.lua | 32 | 1090 | -----------------------------------
-- Area: GM Home
-- NPC: Trader
-- Type: Debug NPC for testing trades.
-----------------------------------
package.loaded["scripts/zones/GM_Home/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/GM_Home/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(4096,1) and trade:getItemCount() == 1) then
player:startEvent(126);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(127);
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 |
RebootRevival/FFXI_Test | scripts/zones/South_Gustaberg/TextIDs.lua | 3 | 1264 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6402; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6408; -- Obtained: <item>.
GIL_OBTAINED = 6409; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6411; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7228; -- You can't fish here.
-- Standard Text
FIRE_GOOD = 7402; -- The fire seems to be good enough for cooking.
FIRE_PUT = 7403; -- You put$ in the fire.
FIRE_TAKE = 7404; -- You take$ out of the fire.
FIRE_LONGER = 7405; -- It may take a little while more to cook
MEAT_ALREADY_PUT = 7406; -- is already in the fire
-- Other dialog
NOTHING_HAPPENS = 141; -- Nothing happens...
NOTHING_OUT_OF_ORDINARY = 6422; -- There is nothing out of the ordinary here.
MONSTER_TRACKS = 7398; -- You see monster tracks on the ground.
MONSTER_TRACKS_FRESH = 7399; -- You see fresh monster tracks on the ground.
-- conquest Base
CONQUEST_BASE = 7069; -- Tallying conquest results...
--chocobo digging
DIG_THROW_AWAY = 7241; -- You dig up$, but your inventory is full. You regretfully throw the # away.
FIND_NOTHING = 7243; -- You dig and you dig, but find nothing.
| gpl-3.0 |
chen0031/sysdig | userspace/sysdig/chisels/topprocs_errors.lua | 12 | 1631 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Chisel description
description = "Shows the top processes in terms of system call errors. This chisel is compatable with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown."
short_description = "top processes by number of errors"
category = "Errors"
-- Chisel argument list
args = {}
-- Argument notification callback
function on_set_arg(name, val)
return false
end
-- Initialization callback
function on_init()
-- The -pc or -pcontainer options was supplied on the cmd line
print_container = sysdig.is_print_container_data()
if print_container then
chisel.exec("table_generator",
"proc.name,proc.pid,thread.vtid,container.name",
"Process,Host_pid,Container_pid,container.name",
"evt.count",
"#Errors",
"evt.failed=true",
"100",
"none")
else
chisel.exec("table_generator",
"proc.name,proc.pid",
"Process,PID",
"evt.count",
"#Errors",
"evt.failed=true",
"100",
"none")
end
return true
end
| gpl-2.0 |
Majid110/MasafAutomation | utf8.lua | 1 | 26263 | -- $Id: utf8.lua 179 2009-04-03 18:10:03Z pasta $
--
-- Provides UTF-8 aware string functions implemented in pure lua:
-- * utf8len(s)
-- * utf8sub(s, i, j)
-- * utf8reverse(s)
-- * utf8char(unicode)
-- * utf8unicode(s, i, j)
-- * utf8gensub(s, sub_len)
-- * utf8find(str, regex, init, plain)
-- * utf8match(str, regex, init)
-- * utf8gmatch(str, regex, all)
-- * utf8gsub(str, regex, repl, limit)
--
-- If utf8data.lua (containing the lower<->upper case mappings) is loaded, these
-- additional functions are available:
-- * utf8upper(s)
-- * utf8lower(s)
--
-- All functions behave as their non UTF-8 aware counterparts with the exception
-- that UTF-8 characters are used instead of bytes for all units.
--[[
Copyright (c) 2006-2007, Kyle Smith
All rights reserved.
Contributors:
Alimov Stepan
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
-- ABNF from RFC 3629
--
-- UTF8-octets = *( UTF8-char )
-- UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
-- UTF8-1 = %x00-7F
-- UTF8-2 = %xC2-DF UTF8-tail
-- UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
-- %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
-- UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
-- %xF4 %x80-8F 2( UTF8-tail )
-- UTF8-tail = %x80-BF
--
local byte = string.byte
local char = string.char
local dump = string.dump
local find = string.find
local format = string.format
local len = string.len
local lower = string.lower
local rep = string.rep
local sub = string.sub
local upper = string.upper
-- returns the number of bytes used by the UTF-8 character at byte i in s
-- also doubles as a UTF-8 character validator
local function utf8charbytes (s, i)
-- argument defaults
i = i or 1
-- argument checking
if type(s) ~= "string" then
error("bad argument #1 to 'utf8charbytes' (string expected, got ".. type(s).. ")")
end
if type(i) ~= "number" then
error("bad argument #2 to 'utf8charbytes' (number expected, got ".. type(i).. ")")
end
local c = byte(s, i)
-- determine bytes needed for character, based on RFC 3629
-- validate byte 1
if c > 0 and c <= 127 then
-- UTF8-1
return 1
elseif c >= 194 and c <= 223 then
-- UTF8-2
local c2 = byte(s, i + 1)
if not c2 then
error("UTF-8 string terminated early")
end
-- validate byte 2
if c2 < 128 or c2 > 191 then
error("Invalid UTF-8 character")
end
return 2
elseif c >= 224 and c <= 239 then
-- UTF8-3
local c2 = byte(s, i + 1)
local c3 = byte(s, i + 2)
if not c2 or not c3 then
error("UTF-8 string terminated early")
end
-- validate byte 2
if c == 224 and (c2 < 160 or c2 > 191) then
error("Invalid UTF-8 character")
elseif c == 237 and (c2 < 128 or c2 > 159) then
error("Invalid UTF-8 character")
elseif c2 < 128 or c2 > 191 then
error("Invalid UTF-8 character")
end
-- validate byte 3
if c3 < 128 or c3 > 191 then
error("Invalid UTF-8 character")
end
return 3
elseif c >= 240 and c <= 244 then
-- UTF8-4
local c2 = byte(s, i + 1)
local c3 = byte(s, i + 2)
local c4 = byte(s, i + 3)
if not c2 or not c3 or not c4 then
error("UTF-8 string terminated early")
end
-- validate byte 2
if c == 240 and (c2 < 144 or c2 > 191) then
error("Invalid UTF-8 character")
elseif c == 244 and (c2 < 128 or c2 > 143) then
error("Invalid UTF-8 character")
elseif c2 < 128 or c2 > 191 then
error("Invalid UTF-8 character")
end
-- validate byte 3
if c3 < 128 or c3 > 191 then
error("Invalid UTF-8 character")
end
-- validate byte 4
if c4 < 128 or c4 > 191 then
error("Invalid UTF-8 character")
end
return 4
else
error("Invalid UTF-8 character")
end
end
-- returns the number of characters in a UTF-8 string
local function utf8len (s)
-- argument checking
if type(s) ~= "string" then
for k,v in pairs(s) do print('"',tostring(k),'"',tostring(v),'"') end
error("bad argument #1 to 'utf8len' (string expected, got ".. type(s).. ")")
end
local pos = 1
local bytes = len(s)
local length = 0
while pos <= bytes do
length = length + 1
pos = pos + utf8charbytes(s, pos)
end
return length
end
-- functions identically to string.sub except that i and j are UTF-8 characters
-- instead of bytes
local function utf8sub (s, i, j)
-- argument defaults
j = j or -1
local pos = 1
local bytes = len(s)
local length = 0
-- only set l if i or j is negative
local l = (i >= 0 and j >= 0) or utf8len(s)
local startChar = (i >= 0) and i or l + i + 1
local endChar = (j >= 0) and j or l + j + 1
-- can't have start before end!
if startChar > endChar then
return ""
end
-- byte offsets to pass to string.sub
local startByte,endByte = 1,bytes
while pos <= bytes do
length = length + 1
if length == startChar then
startByte = pos
end
pos = pos + utf8charbytes(s, pos)
if length == endChar then
endByte = pos - 1
break
end
end
if startChar > length then startByte = bytes+1 end
if endChar < 1 then endByte = 0 end
return sub(s, startByte, endByte)
end
--[[
-- replace UTF-8 characters based on a mapping table
local function utf8replace (s, mapping)
-- argument checking
if type(s) ~= "string" then
error("bad argument #1 to 'utf8replace' (string expected, got ".. type(s).. ")")
end
if type(mapping) ~= "table" then
error("bad argument #2 to 'utf8replace' (table expected, got ".. type(mapping).. ")")
end
local pos = 1
local bytes = len(s)
local charbytes
local newstr = ""
while pos <= bytes do
charbytes = utf8charbytes(s, pos)
local c = sub(s, pos, pos + charbytes - 1)
newstr = newstr .. (mapping[c] or c)
pos = pos + charbytes
end
return newstr
end
-- identical to string.upper except it knows about unicode simple case conversions
local function utf8upper (s)
return utf8replace(s, utf8_lc_uc)
end
-- identical to string.lower except it knows about unicode simple case conversions
local function utf8lower (s)
return utf8replace(s, utf8_uc_lc)
end
]]
-- identical to string.reverse except that it supports UTF-8
local function utf8reverse (s)
-- argument checking
if type(s) ~= "string" then
error("bad argument #1 to 'utf8reverse' (string expected, got ".. type(s).. ")")
end
local bytes = len(s)
local pos = bytes
local charbytes
local newstr = ""
while pos > 0 do
local c = byte(s, pos)
while c >= 128 and c <= 191 do
pos = pos - 1
c = byte(s, pos)
end
charbytes = utf8charbytes(s, pos)
newstr = newstr .. sub(s, pos, pos + charbytes - 1)
pos = pos - 1
end
return newstr
end
-- http://en.wikipedia.org/wiki/Utf8
-- http://developer.coronalabs.com/code/utf-8-conversion-utility
local function utf8char(unicode)
if unicode <= 0x7F then return char(unicode) end
if (unicode <= 0x7FF) then
local Byte0 = 0xC0 + math.floor(unicode / 0x40);
local Byte1 = 0x80 + (unicode % 0x40);
return char(Byte0, Byte1);
end;
if (unicode <= 0xFFFF) then
local Byte0 = 0xE0 + math.floor(unicode / 0x1000);
local Byte1 = 0x80 + (math.floor(unicode / 0x40) % 0x40);
local Byte2 = 0x80 + (unicode % 0x40);
return char(Byte0, Byte1, Byte2);
end;
if (unicode <= 0x10FFFF) then
local code = unicode
local Byte3= 0x80 + (code % 0x40);
code = math.floor(code / 0x40)
local Byte2= 0x80 + (code % 0x40);
code = math.floor(code / 0x40)
local Byte1= 0x80 + (code % 0x40);
code = math.floor(code / 0x40)
local Byte0= 0xF0 + code;
return char(Byte0, Byte1, Byte2, Byte3);
end;
error 'Unicode cannot be greater than U+10FFFF!'
end
local shift_6 = 2^6
local shift_12 = 2^12
local shift_18 = 2^18
local utf8unicode
utf8unicode = function(str, i, j, byte_pos)
i = i or 1
j = j or i
if i > j then return end
local ch,bytes
if byte_pos then
bytes = utf8charbytes(str,byte_pos)
ch = sub(str,byte_pos,byte_pos-1+bytes)
else
ch,byte_pos = utf8sub(str,i,i), 0
bytes = #ch
end
local unicode
if bytes == 1 then unicode = byte(ch) end
if bytes == 2 then
local byte0,byte1 = byte(ch,1,2)
local code0,code1 = byte0-0xC0,byte1-0x80
unicode = code0*shift_6 + code1
end
if bytes == 3 then
local byte0,byte1,byte2 = byte(ch,1,3)
local code0,code1,code2 = byte0-0xE0,byte1-0x80,byte2-0x80
unicode = code0*shift_12 + code1*shift_6 + code2
end
if bytes == 4 then
local byte0,byte1,byte2,byte3 = byte(ch,1,4)
local code0,code1,code2,code3 = byte0-0xF0,byte1-0x80,byte2-0x80,byte3-0x80
unicode = code0*shift_18 + code1*shift_12 + code2*shift_6 + code3
end
return unicode,utf8unicode(str, i+1, j, byte_pos+bytes)
end
-- Returns an iterator which returns the next substring and its byte interval
local function utf8gensub(str, sub_len)
sub_len = sub_len or 1
local byte_pos = 1
local length = #str
return function(skip)
if skip then byte_pos = byte_pos + skip end
local char_count = 0
local start = byte_pos
repeat
if byte_pos > length then return end
char_count = char_count + 1
local bytes = utf8charbytes(str,byte_pos)
byte_pos = byte_pos+bytes
until char_count == sub_len
local last = byte_pos-1
local slice = sub(str,start,last)
return slice, start, last
end
end
local function binsearch(sortedTable, item, comp)
local head, tail = 1, #sortedTable
local mid = math.floor((head + tail)/2)
if not comp then
while (tail - head) > 1 do
if sortedTable[tonumber(mid)] > item then
tail = mid
else
head = mid
end
mid = math.floor((head + tail)/2)
end
end
if sortedTable[tonumber(head)] == item then
return true, tonumber(head)
elseif sortedTable[tonumber(tail)] == item then
return true, tonumber(tail)
else
return false
end
end
local function classMatchGenerator(class, plain)
local codes = {}
local ranges = {}
local ignore = false
local range = false
local firstletter = true
local unmatch = false
local it = utf8gensub(class)
local skip
for c, _, be in it do
skip = be
if not ignore and not plain then
if c == "%" then
ignore = true
elseif c == "-" then
table.insert(codes, utf8unicode(c))
range = true
elseif c == "^" then
if not firstletter then
error('!!!')
else
unmatch = true
end
elseif c == ']' then
break
else
if not range then
table.insert(codes, utf8unicode(c))
else
table.remove(codes) -- removing '-'
table.insert(ranges, {table.remove(codes), utf8unicode(c)})
range = false
end
end
elseif ignore and not plain then
if c == 'a' then -- %a: represents all letters. (ONLY ASCII)
table.insert(ranges, {65, 90}) -- A - Z
table.insert(ranges, {97, 122}) -- a - z
elseif c == 'c' then -- %c: represents all control characters.
table.insert(ranges, {0, 31})
table.insert(codes, 127)
elseif c == 'd' then -- %d: represents all digits.
table.insert(ranges, {48, 57}) -- 0 - 9
elseif c == 'g' then -- %g: represents all printable characters except space.
table.insert(ranges, {1, 8})
table.insert(ranges, {14, 31})
table.insert(ranges, {33, 132})
table.insert(ranges, {134, 159})
table.insert(ranges, {161, 5759})
table.insert(ranges, {5761, 8191})
table.insert(ranges, {8203, 8231})
table.insert(ranges, {8234, 8238})
table.insert(ranges, {8240, 8286})
table.insert(ranges, {8288, 12287})
elseif c == 'l' then -- %l: represents all lowercase letters. (ONLY ASCII)
table.insert(ranges, {97, 122}) -- a - z
elseif c == 'p' then -- %p: represents all punctuation characters. (ONLY ASCII)
table.insert(ranges, {33, 47})
table.insert(ranges, {58, 64})
table.insert(ranges, {91, 96})
table.insert(ranges, {123, 126})
elseif c == 's' then -- %s: represents all space characters.
table.insert(ranges, {9, 13})
table.insert(codes, 32)
table.insert(codes, 133)
table.insert(codes, 160)
table.insert(codes, 5760)
table.insert(ranges, {8192, 8202})
table.insert(codes, 8232)
table.insert(codes, 8233)
table.insert(codes, 8239)
table.insert(codes, 8287)
table.insert(codes, 12288)
elseif c == 'u' then -- %u: represents all uppercase letters. (ONLY ASCII)
table.insert(ranges, {65, 90}) -- A - Z
elseif c == 'w' then -- %w: represents all alphanumeric characters. (ONLY ASCII)
table.insert(ranges, {48, 57}) -- 0 - 9
table.insert(ranges, {65, 90}) -- A - Z
table.insert(ranges, {97, 122}) -- a - z
elseif c == 'x' then -- %x: represents all hexadecimal digits.
table.insert(ranges, {48, 57}) -- 0 - 9
table.insert(ranges, {65, 70}) -- A - F
table.insert(ranges, {97, 102}) -- a - f
else
if not range then
table.insert(codes, utf8unicode(c))
else
table.remove(codes) -- removing '-'
table.insert(ranges, {table.remove(codes), utf8unicode(c)})
range = false
end
end
ignore = false
else
if not range then
table.insert(codes, utf8unicode(c))
else
table.remove(codes) -- removing '-'
table.insert(ranges, {table.remove(codes), utf8unicode(c)})
range = false
end
ignore = false
end
firstletter = false
end
table.sort(codes)
local function inRanges(charCode)
for _,r in ipairs(ranges) do
if r[1] <= charCode and charCode <= r[2] then
return true
end
end
return false
end
if not unmatch then
return function(charCode)
return binsearch(codes, charCode) or inRanges(charCode)
end, skip
else
return function(charCode)
return charCode ~= -1 and not (binsearch(codes, charCode) or inRanges(charCode))
end, skip
end
end
--[[
-- utf8sub with extra argument, and extra result value
local function utf8subWithBytes (s, i, j, sb)
-- argument defaults
j = j or -1
local pos = sb or 1
local bytes = len(s)
local length = 0
-- only set l if i or j is negative
local l = (i >= 0 and j >= 0) or utf8len(s)
local startChar = (i >= 0) and i or l + i + 1
local endChar = (j >= 0) and j or l + j + 1
-- can't have start before end!
if startChar > endChar then
return ""
end
-- byte offsets to pass to string.sub
local startByte,endByte = 1,bytes
while pos <= bytes do
length = length + 1
if length == startChar then
startByte = pos
end
pos = pos + utf8charbytes(s, pos)
if length == endChar then
endByte = pos - 1
break
end
end
if startChar > length then startByte = bytes+1 end
if endChar < 1 then endByte = 0 end
return sub(s, startByte, endByte), endByte + 1
end
]]
local cache = setmetatable({},{
__mode = 'kv'
})
local cachePlain = setmetatable({},{
__mode = 'kv'
})
local function matcherGenerator(regex, plain)
local matcher = {
functions = {},
captures = {}
}
if not plain then
cache[regex] = matcher
else
cachePlain[regex] = matcher
end
local function simple(func)
return function(cC)
if func(cC) then
matcher:nextFunc()
matcher:nextStr()
else
matcher:reset()
end
end
end
local function star(func)
return function(cC)
if func(cC) then
matcher:fullResetOnNextFunc()
matcher:nextStr()
else
matcher:nextFunc()
end
end
end
local function minus(func)
return function(cC)
if func(cC) then
matcher:fullResetOnNextStr()
end
matcher:nextFunc()
end
end
local function question(func)
return function(cC)
if func(cC) then
matcher:fullResetOnNextFunc()
matcher:nextStr()
end
matcher:nextFunc()
end
end
local function capture(id)
return function(_)
local l = matcher.captures[id][2] - matcher.captures[id][1]
local captured = utf8sub(matcher.string, matcher.captures[id][1], matcher.captures[id][2])
local check = utf8sub(matcher.string, matcher.str, matcher.str + l)
if captured == check then
for _ = 0, l do
matcher:nextStr()
end
matcher:nextFunc()
else
matcher:reset()
end
end
end
local function captureStart(id)
return function(_)
matcher.captures[id][1] = matcher.str
matcher:nextFunc()
end
end
local function captureStop(id)
return function(_)
matcher.captures[id][2] = matcher.str - 1
matcher:nextFunc()
end
end
local function balancer(str)
local sum = 0
local bc, ec = utf8sub(str, 1, 1), utf8sub(str, 2, 2)
local skip = len(bc) + len(ec)
bc, ec = utf8unicode(bc), utf8unicode(ec)
return function(cC)
if cC == ec and sum > 0 then
sum = sum - 1
if sum == 0 then
matcher:nextFunc()
end
matcher:nextStr()
elseif cC == bc then
sum = sum + 1
matcher:nextStr()
else
if sum == 0 or cC == -1 then
sum = 0
matcher:reset()
else
matcher:nextStr()
end
end
end, skip
end
matcher.functions[1] = function(_)
matcher:fullResetOnNextStr()
matcher.seqStart = matcher.str
matcher:nextFunc()
if (matcher.str > matcher.startStr and matcher.fromStart) or matcher.str >= matcher.stringLen then
matcher.stop = true
matcher.seqStart = nil
end
end
local lastFunc
local ignore = false
local skip = nil
local it = (function()
local gen = utf8gensub(regex)
return function()
return gen(skip)
end
end)()
local cs = {}
for c, bs, be in it do
skip = nil
if plain then
table.insert(matcher.functions, simple(classMatchGenerator(c, plain)))
else
if ignore then
if find('123456789', c, 1, true) then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
lastFunc = nil
end
table.insert(matcher.functions, capture(tonumber(c)))
elseif c == 'b' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
lastFunc = nil
end
local b
b, skip = balancer(sub(regex, be + 1, be + 9))
table.insert(matcher.functions, b)
else
lastFunc = classMatchGenerator('%' .. c)
end
ignore = false
else
if c == '*' then
if lastFunc then
table.insert(matcher.functions, star(lastFunc))
lastFunc = nil
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '+' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
table.insert(matcher.functions, star(lastFunc))
lastFunc = nil
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '-' then
if lastFunc then
table.insert(matcher.functions, minus(lastFunc))
lastFunc = nil
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '?' then
if lastFunc then
table.insert(matcher.functions, question(lastFunc))
lastFunc = nil
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '^' then
if bs == 1 then
matcher.fromStart = true
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '$' then
if be == len(regex) then
matcher.toEnd = true
else
error('invalid regex after ' .. sub(regex, 1, bs))
end
elseif c == '[' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
end
lastFunc, skip = classMatchGenerator(sub(regex, be + 1))
elseif c == '(' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
lastFunc = nil
end
table.insert(matcher.captures, {})
table.insert(cs, #matcher.captures)
table.insert(matcher.functions, captureStart(cs[#cs]))
if sub(regex, be + 1, be + 1) == ')' then matcher.captures[#matcher.captures].empty = true end
elseif c == ')' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
lastFunc = nil
end
local cap = table.remove(cs)
if not cap then
error('invalid capture: "(" missing')
end
table.insert(matcher.functions, captureStop(cap))
elseif c == '.' then
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
end
lastFunc = function(cC) return cC ~= -1 end
elseif c == '%' then
ignore = true
else
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
end
lastFunc = classMatchGenerator(c)
end
end
end
end
if #cs > 0 then
error('invalid capture: ")" missing')
end
if lastFunc then
table.insert(matcher.functions, simple(lastFunc))
end
table.insert(matcher.functions, function()
if matcher.toEnd and matcher.str ~= matcher.stringLen then
matcher:reset()
else
matcher.stop = true
end
end)
matcher.nextFunc = function(self)
self.func = self.func + 1
end
matcher.nextStr = function(self)
self.str = self.str + 1
end
matcher.strReset = function(self)
local oldReset = self.reset
local str = self.str
self.reset = function(s)
s.str = str
s.reset = oldReset
end
end
matcher.fullResetOnNextFunc = function(self)
local oldReset = self.reset
local func = self.func +1
local str = self.str
self.reset = function(s)
s.func = func
s.str = str
s.reset = oldReset
end
end
matcher.fullResetOnNextStr = function(self)
local oldReset = self.reset
local str = self.str + 1
local func = self.func
self.reset = function(s)
s.func = func
s.str = str
s.reset = oldReset
end
end
matcher.process = function(self, str, start)
self.func = 1
start = start or 1
self.startStr = (start >= 0) and start or utf8len(str) + start + 1
self.seqStart = self.startStr
self.str = self.startStr
self.stringLen = utf8len(str) + 1
self.string = str
self.stop = false
self.reset = function(s)
s.func = 1
end
-- local lastPos = self.str
-- local lastByte
local ch
while not self.stop do
if self.str < self.stringLen then
--[[ if lastPos < self.str then
print('last byte', lastByte)
ch, lastByte = utf8subWithBytes(str, 1, self.str - lastPos - 1, lastByte)
ch, lastByte = utf8subWithBytes(str, 1, 1, lastByte)
lastByte = lastByte - 1
else
ch, lastByte = utf8subWithBytes(str, self.str, self.str)
end
lastPos = self.str ]]
ch = utf8sub(str, self.str,self.str)
--print('char', ch, utf8unicode(ch))
self.functions[self.func](utf8unicode(ch))
else
self.functions[self.func](-1)
end
end
if self.seqStart then
local captures = {}
for _,pair in pairs(self.captures) do
if pair.empty then
table.insert(captures, pair[1])
else
table.insert(captures, utf8sub(str, pair[1], pair[2]))
end
end
return self.seqStart, self.str - 1, unpack(captures)
end
end
return matcher
end
-- string.find
local function utf8find(str, regex, init, plain)
local matcher = cache[regex] or matcherGenerator(regex, plain)
return matcher:process(str, init)
end
-- string.match
local function utf8match(str, regex, init)
init = init or 1
local found = {utf8find(str, regex, init)}
if found[1] then
if found[3] then
return unpack(found, 3)
end
return utf8sub(str, found[1], found[2])
end
end
-- string.gmatch
local function utf8gmatch(str, regex, all)
regex = (utf8sub(regex,1,1) ~= '^') and regex or '%' .. regex
local lastChar = 1
return function()
local found = {utf8find(str, regex, lastChar)}
if found[1] then
lastChar = found[2] + 1
if found[all and 1 or 3] then
return unpack(found, all and 1 or 3)
end
return utf8sub(str, found[1], found[2])
end
end
end
local function replace(repl, args)
local ret = ''
if type(repl) == 'string' then
local ignore = false
local num
for c in utf8gensub(repl) do
if not ignore then
if c == '%' then
ignore = true
else
ret = ret .. c
end
else
num = tonumber(c)
if num then
ret = ret .. args[num]
else
ret = ret .. c
end
ignore = false
end
end
elseif type(repl) == 'table' then
ret = repl[args[1] or args[0]] or ''
elseif type(repl) == 'function' then
if #args > 0 then
ret = repl(unpack(args, 1)) or ''
else
ret = repl(args[0]) or ''
end
end
return ret
end
-- string.gsub
local function utf8gsub(str, regex, repl, limit)
limit = limit or -1
local ret = ''
local prevEnd = 1
local it = utf8gmatch(str, regex, true)
local found = {it()}
local n = 0
while #found > 0 and limit ~= n do
local args = {[0] = utf8sub(str, found[1], found[2]), unpack(found, 3)}
ret = ret .. utf8sub(str, prevEnd, found[1] - 1)
.. replace(repl, args)
prevEnd = found[2] + 1
n = n + 1
found = {it()}
end
return ret .. utf8sub(str, prevEnd), n
end
local utf8 = {}
utf8.len = utf8len
utf8.sub = utf8sub
utf8.reverse = utf8reverse
utf8.char = utf8char
utf8.unicode = utf8unicode
utf8.gensub = utf8gensub
utf8.byte = utf8unicode
utf8.find = utf8find
utf8.match = utf8match
utf8.gmatch = utf8gmatch
utf8.gsub = utf8gsub
utf8.dump = dump
utf8.format = format
utf8.lower = lower
utf8.upper = upper
utf8.rep = rep
utf8.charbytes = utf8charbytes
return utf8
| mit |
RebootRevival/FFXI_Test | scripts/zones/Abyssea-Tahrongi/npcs/qm15.lua | 3 | 1566 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns Lacovie
-- !pos ? ? ? 45
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961951) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(OVERGROWN_MANDRAGORA_FLOWER) and player:hasKeyItem(CHIPPED_SANDWORM_TOOTH)) then
player:startEvent(1020, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Ask if player wants to use KIs
else
player:startEvent(1021, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961951):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(OVERGROWN_MANDRAGORA_FLOWER);
player:delKeyItem(CHIPPED_SANDWORM_TOOTH);
end
end;
| gpl-3.0 |
Cyco12/PotatoBot | deps/discordia/class.lua | 3 | 4654 | local max = math.max
local insert, sort = table.insert, table.sort
local lower, upper = string.lower, string.upper
local f, padright = string.format, string.padright
local printf = printf -- luacheck: ignore printf
local meta = {}
local classes = {}
function meta:__call(...)
local obj = setmetatable({}, self)
obj:__init(...)
return obj
end
function meta:__tostring()
return 'class: ' .. self.__name
end
local Base -- defined below
local class = setmetatable({__classes = classes}, {__call = function(_, name, ...)
if classes[name] then return error(f('Class %q already defined', name)) end
local class = setmetatable({}, meta)
local getters, setters = {}, {} -- for property metatables
local properties, methods, caches = {}, {}, {} -- for documentation
local info = {
getters = getters, setters = setters,
properties = properties, methods = methods, caches = caches,
}
local bases = {Base, ...}
for _, base in ipairs(bases) do
for k, v in pairs(base) do
class[k] = v
end
for k1, v1 in pairs(base.__info) do
for k2, v2 in pairs(v1) do
info[k1][k2] = v2
end
end
end
class.__info = info
class.__name = name
class.__class = class
class.__bases = bases
class.__description = nil
local pool = {}
local n = 1
function class:__index(k)
local getter = getters[k]
if getter then -- don't use ternary operator
return getter(self)
else
return rawget(self, pool[k]) or class[k]
end
end
function class:__newindex(k, v)
local setter = setters[k]
if setter then
return setter(self, v)
elseif class[k] or properties[k] then
return error(f('Cannot overwrite protected property: %s.%s', name, k))
else
if not pool[k] then
pool[k] = n
n = n + 1
end
return rawset(self, pool[k], v)
end
end
local function property(k, get, set, t, d)
assert(type(k) == 'string')
assert(type(t) == 'string')
assert(type(d) == 'string' and #d < 120)
local m = k:gsub('^%l', upper)
local getter = get
if type(get) == 'string' then
getter = function(self) return self[get] end
end
assert(type(getter) == 'function')
getters[k] = getter
class['get' .. m] = getter
if set then
local setter = set
if type(set) == 'string' then
setter = function(self, v) self[set] = v end
end
assert(type(setter) == 'function')
setters[k] = setter
class['set' .. m] = setter
end
properties[k] = {t, d}
end
local function method(k, fn, params, desc, interface)
assert(type(k) == 'string')
assert(type(fn) == 'function')
assert(type(desc) == 'string' and #desc < 120)
class[k] = fn
methods[k] = {params or '', desc, interface or 'Local'}
end
local function cache(k, count, get, getAll, find, findAll)
local k1 = k:gsub('^.', lower)
local k2 = name:gsub('(.*)(%u)', function(_, str) return lower(str) end)
property(f('%ss', k1), getAll, nil, 'function', f("Iterator for the %s's cached %ss.", k2, k))
property(f('%sCount', k1), count, nil, 'number', f("How many %ss are cached for the %s.", k, k2))
class[f('get%s', k)] = get
class[f('find%s', k)] = find
class[f('find%ss', k)] = findAll
caches[k] = true
end
classes[name] = class
return class, property, method, cache
end})
Base = class('Base') -- forward-declared above
function Base:__tostring()
return 'instance of class: ' .. self.__name
end
local function isSub(self, other)
for _, base in ipairs(self.__bases) do
if base == other then return true end
if isSub(base, other) then return true end
end
return false
end
function Base:isInstanceOf(name)
local other = classes[name]
if not other then return error(f('Class %q is undefined', name)) end
if self.__class == other.__class then return true, true end
return isSub(self, other), false
end
local function sorter(a, b)
return a[1] < b[1]
end
function Base:help()
printf('\n-- %s --\n%s\n', self.__name, self.__description)
if next(self.__info.properties) then
local properties = {}
local n, m = 0, 0
for k, v in pairs(self.__info.properties) do
insert(properties, {k, v[1], v[2]})
n = max(n, #k)
m = max(m, #v[1])
end
sort(properties, sorter)
for _, v in ipairs(properties) do
printf('%s %s %s', padright(v[1], n), padright(v[2], m), v[3])
end
print()
end
if next(self.__info.methods) then
local methods = {}
local n, m = 0, 0
for k, v in pairs(self.__info.methods) do
insert(methods, {k, v[1], v[2]})
n = max(n, #k + #v[1] + 2)
m = max(m, #v[2])
end
sort(methods, sorter)
for _, v in ipairs(methods) do
printf('%s %s', padright(f('%s(%s)', v[1], v[2]), n), padright(v[3], m))
end
print()
end
end
return class
| apache-2.0 |
rafradek/wire | lua/entities/gmod_wire_expression2/core/compat.lua | 9 | 3207 | -- Functions in this file are retained purely for backwards-compatibility. They should not be used in new code and might be removed at any time.
e2function string number:teamName()
local str = team.GetName(this)
if not str then return "" end
return str
end
e2function number number:teamScore()
return team.GetScore(this)
end
e2function number number:teamPlayers()
return team.NumPlayers(this)
end
e2function number number:teamDeaths()
return team.TotalDeaths(this)
end
e2function number number:teamFrags()
return team.TotalFrags(this)
end
e2function void setColor(r, g, b)
self.entity:SetColor(Color(math.Clamp(r, 0, 255), math.Clamp(g, 0, 255), math.Clamp(b, 0, 255), 255))
end
__e2setcost(30) -- temporary
e2function void applyForce(vector force)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceCenter(Vector(force[1],force[2],force[3]))
end
e2function void applyOffsetForce(vector force, vector position)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceOffset(Vector(force[1],force[2],force[3]), Vector(position[1],position[2],position[3]))
end
e2function void applyAngForce(angle angForce)
if angForce[1] == 0 and angForce[2] == 0 and angForce[3] == 0 then return end
local ent = self.entity
local phys = ent:GetPhysicsObject()
-- assign vectors
local up = ent:GetUp()
local left = ent:GetRight() * -1
local forward = ent:GetForward()
-- apply pitch force
if angForce[1] ~= 0 then
local pitch = up * (angForce[1] * 0.5)
phys:ApplyForceOffset( forward, pitch )
phys:ApplyForceOffset( forward * -1, pitch * -1 )
end
-- apply yaw force
if angForce[2] ~= 0 then
local yaw = forward * (angForce[2] * 0.5)
phys:ApplyForceOffset( left, yaw )
phys:ApplyForceOffset( left * -1, yaw * -1 )
end
-- apply roll force
if angForce[3] ~= 0 then
local roll = left * (angForce[3] * 0.5)
phys:ApplyForceOffset( up, roll )
phys:ApplyForceOffset( up * -1, roll * -1 )
end
end
e2function void applyTorque(vector torque)
if torque[1] == 0 and torque[2] == 0 and torque[3] == 0 then return end
local phys = self.entity:GetPhysicsObject()
local tq = Vector(torque[1], torque[2], torque[3])
local torqueamount = tq:Length()
-- Convert torque from local to world axis
tq = phys:LocalToWorld( tq ) - phys:GetPos()
-- Find two vectors perpendicular to the torque axis
local off
if math.abs(tq.x) > torqueamount * 0.1 or math.abs(tq.z) > torqueamount * 0.1 then
off = Vector(-tq.z, 0, tq.x)
else
off = Vector(-tq.y, tq.x, 0)
end
off = off:GetNormal() * torqueamount * 0.5
local dir = ( tq:Cross(off) ):GetNormal()
phys:ApplyForceOffset( dir, off )
phys:ApplyForceOffset( dir * -1, off * -1 )
end
__e2setcost(10)
e2function number entity:height()
--[[ Old code (UGLYYYY)
if(!IsValid(this)) then return 0 end
if(this:IsPlayer() or this:IsNPC()) then
local pos = this:GetPos()
local up = this:GetUp()
return this:NearestPoint(Vector(pos.x+up.x*100,pos.y+up.y*100,pos.z+up.z*100)).z-this:NearestPoint(Vector(pos.x-up.x*100,pos.y-up.y*100,pos.z-up.z*100)).z
else return 0 end
]]
-- New code (Same as E:boxSize():z())
if(!IsValid(this)) then return 0 end
return (this:OBBMaxs() - this:OBBMins()).z
end
| apache-2.0 |
hfjgjfg/jjjn | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
tommo/mock | mock/gfx/asset/MultiTexture.lua | 1 | 3259 | module 'mock'
--------------------------------------------------------------------
CLASS: MultiTextureInstance ( TextureInstanceBase )
:MODEL{}
function MultiTextureInstance:__init()
self.moaiTexture = MOAIMultiTexture.new()
self.subTextures = {}
self.defaultSize = { 32, 32 }
self.dirty = true
end
function MultiTextureInstance:setDefaultSize( w, h )
self.defaultSize = { w, h }
end
function MultiTextureInstance:getMoaiTexture()
self:update()
return self.moaiTexture
end
function MultiTextureInstance:getSize()
return unpack( self.defaultSize )
end
function MultiTextureInstance:getMoaiTextureUV()
local tex = self:getMoaiTexture()
local uvrect = { self:getUVRect() }
return tex, uvrect
end
function MultiTextureInstance:getTextures()
return self.subTextures
end
function MultiTextureInstance:setTextures( subTextures )
self.subTextures = subTextures
self:markDirty()
end
function MultiTextureInstance:getTexture( idx )
return self.subTextures[ idx ]
end
function MultiTextureInstance:setTexture( idx, tex )
self.subTextures[ idx ] = tex
self:markDirty()
end
function MultiTextureInstance:markDirty()
self.dirty = true
end
local function _affirmMoaiTextureInstance( tex )
if tex:isPacked() then
_warn( 'attempt to use packed texture in MultiTexture' )
return false
end
return tex:getMoaiTexture()
end
local function _affirmMoaiTexture( src )
local tt = type( src )
if tt == 'string' then --asset
local tex = loadAsset( src )
if tex then
return _affirmMoaiTextureInstance( tex )
end
elseif tt == 'table' and isInstance( src, TextureInstance ) then
return _affirmMoaiTextureInstance( src )
elseif tt == 'userdata' then
local className = src:getClassName()
if className == 'MOAITexture' or className == 'MOAIFrameBufferTexture' then
return src
end
end
return false
end
local function affrimInt( n )
n = tonumber( n )
if type( n ) ~= 'number' then return false end
if math.floor( n ) ~= n then return false end
return n
end
local MAX_TEX_COUNT = 12
function MultiTextureInstance:update( forced )
if ( not self.dirty ) and ( not forced ) then return true end
local count = 0
local moaiTextures = {}
for n, texture in pairs( self.subTextures ) do
local idx = affrimInt( n )
if idx then
if idx > MAX_TEX_COUNT or idx <= 0 then
_warn( 'texture index not in range', idx, texture )
else
moaiTextures [ idx ] = _affirmMoaiTexture( texture )
count = math.max( idx, count )
end
else
_warn( 'texture index must be integer', n, texture )
end
end
local moaiTexture = self.moaiTexture
self.moaiTexture:reserve( count )
for i = 1, count do
local t = moaiTextures[ i ] or nil
self.moaiTexture:setTexture( i, t )
end
return true
end
--------------------------------------------------------------------
function createMultiTexture( textures )
local tex = MultiTextureInstance()
tex:setTextures( textures or {} )
return tex
end
--------------------------------------------------------------------
function MultiTextureConfigLoader( node )
local data = loadAssetDataTable( node:getObjectFile( 'data' ) )
if not data then return false end
return createMultiTexture( data and data[ 'textures' ] )
end
addSupportedTextureAssetType( 'multi_texture' ) | mit |
RebootRevival/FFXI_Test | scripts/zones/Attohwa_Chasm/mobs/Alastor_Antlion.lua | 3 | 1897 | -----------------------------------
-- Area: Attohwa Chasm
-- NPC: Alastor Antlion
-----------------------------------
mixins = {require("scripts/mixins/families/antlion_ambush_noaggro")}
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
mob:setMobMod(MOBMOD_GA_CHANCE,50);
mob:setMobMod(MOBMOD_MUG_GIL,10000);
mob:addMod(MOD_FASTCAST,10);
mob:addMod(MOD_BINDRES,40);
mob:addMod(MOD_SILENCERES,40);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob, target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onAdditionalEffect
-----------------------------------
function onAdditionalEffect(mob, player)
local chance = 25;
local resist = applyResistanceAddEffect(mob,player,ELE_EARTH,EFFECT_PETRIFICATION);
if (math.random(0,99) >= chance or resist <= 0.5) then
return 0,0,0;
else
local duration = 30;
if (mob:getMainLvl() > player:getMainLvl()) then
duration = duration + (mob:getMainLvl() - player:getMainLvl())
end
duration = utils.clamp(duration,1,45);
duration = duration * resist;
if (not player:hasStatusEffect(EFFECT_PETRIFICATION)) then
player:addStatusEffect(EFFECT_PETRIFICATION, 1, 0, duration);
end
return SUBEFFECT_PETRIFY, msgBasic.ADD_EFFECT_STATUS, EFFECT_PETRIFICATION;
end
end;
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/items/crepe_forestiere.lua | 12 | 1467 | -----------------------------------------
-- ID: 5774
-- Item: crepe_forestiere
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Mind 2
-- MP % 10 (cap 35)
-- Magic Accuracy +15
-- Magic Def. Bonus +6
-----------------------------------------
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,5774);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MND, 2);
target:addMod(MOD_FOOD_MPP, 10);
target:addMod(MOD_FOOD_MP_CAP, 35);
target:addMod(MOD_MACC, 15);
target:addMod(MOD_MDEF, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MND, 2);
target:delMod(MOD_FOOD_MPP, 10);
target:delMod(MOD_FOOD_MP_CAP, 35);
target:delMod(MOD_MACC, 15);
target:delMod(MOD_MDEF, 6);
end;
| gpl-3.0 |
jpmac26/PGE-Project | Content/configs/SMBX/script/npcs/vinehead.lua | 1 | 2481 | class 'vinehead'
function vinehead:round(num)
if num >= 0 then return math.floor(num+.5)
else return math.ceil(num-.5) end
end
function vinehead:spawnVine()
local spawnID=0
if(self.npc_obj.id==226)then
spawnID = 213
elseif(self.npc_obj.id==225)then
spawnID = 214
elseif(self.npc_obj.id==227)then
spawnID = 224
end
local vine=self.npc_obj:spawnNPC(spawnID, GENERATOR_APPEAR, SPAWN_UP, false)
vine.speedX = 0
vine.speedY = 0
-- Let's align Y value to 32px grid!
local rY = self:round(self.npc_obj.y)
local gridY = rY - (math.fmod(rY, 32))
if(rY<0)then
if(rY < (gridY-16) )then
gridY = gridY-32
end
else
if(rY > (gridY+16) )then
gridY = gridY+32
end
end
vine.center_x = self.npc_obj.center_x
vine.y = gridY
end
function vinehead:initProps()
-- Animation properties
--self.radius = 4*32-self.npc_obj.width/2-16
self.init_y = self.npc_obj.y
self.passed_height = 0
self.firstTime=true
self.speed = -2
end
function vinehead:__init(npc_obj)
self.npc_obj = npc_obj
self.init_y = 0
self.passed_height = 0
self.firstTime=false
-- self.contacts = npc_obj:installContactDetector()
self.contacts = self.npc_obj:installInAreaDetector(-(npc_obj.width/2), -(npc_obj.height/2), npc_obj.width/2, npc_obj.height/2, {1})
end
function vinehead:onActivated()
self:initProps()
end
function vinehead:onLoop(tickTime)
if(self.firstTime)then
self:spawnVine()
self.firstTime=false
end
self.npc_obj.speedY=self.speed
self.passed_height = math.abs(self.init_y-self.npc_obj.y)
if(self.passed_height >= 32)then
self.init_y = self.init_y - 32
-- selfDestroy on contact with solid blocks
if(self.contacts:detected())then
local blocks= self.contacts:getBlocks()
for K,Blk in pairs(blocks) do
if(Blk.isSolid and ((Blk.top+(Blk.height/2.0)) >= self.npc_obj.top )
and ((Blk.left-(Blk.width/2.0))<=self.npc_obj.left)
and (Blk.right+(Blk.width/2.0))>=self.npc_obj.right )then
self.npc_obj:unregister()
return
end
end
end
self:spawnVine()
end
end
return vinehead
| gpl-3.0 |
tommo/mock | mock/ai/FSMController.lua | 1 | 6588 | module 'mock'
--------------------------------------------------------------------
local stateCollectorMT
local setmetatable=setmetatable
local insert, remove = table.insert, table.remove
local rawget,rawset=rawget,rawset
local pairs=pairs
stateCollectorMT = {
__index = function( t, k )
local __state = t.__state
local __id = t.__id
return setmetatable({
__state = __state and __state..'.'..k or k,
__id = __id and __id..'_'..k or '_FSM_'..k,
__class = t.__class
} ,stateCollectorMT)
end,
--got state method
__newindex =function( t, action, func )
local name = t.__state
local id = t.__id
local class = t.__class
if
action ~= 'jumpin' and action ~= 'jumpout'
and action~='step' and action~='enter' and action~='exit'
then
return error(
string.format( 'unsupported state action: %s:%s', id, action )
)
end
--NOTE:validation will be done after setting scheme to controller
--save under fullname
local methodName = id..'__'..action
rawset ( class, methodName, func )
end
}
local function newStateMethodCollector( class )
return setmetatable({
__state = false,
__id = false,
__class = class
} ,stateCollectorMT )
end
--------------------------------------------------------------------
CLASS: FSMController ( Behaviour )
:MODEL{
Field 'state' :string() :readonly() :get('getState');
Field 'scheme' :asset('fsm_scheme') :getset('Scheme');
Field 'syncEntityState' :boolean();
}
:META{
category = 'behaviour'
}
-----fsm state method collector
FSMController.fsm = newStateMethodCollector( FSMController )
function FSMController.__createStateMethodCollector( targetClass )
return newStateMethodCollector( targetClass )
end
function FSMController:__initclass( subclass )
subclass.fsm = newStateMethodCollector( subclass )
end
function FSMController:__init()
self.stateElapsedTime = 0
self.stateElapsedFrames = 0
local msgBox = {}
self.msgBox = msgBox
self.syncEntityState = false
local msgFilter = false
self.msgBoxListener = function( msg, data, source )
if msgFilter and msgFilter( msg, data, source ) == false then return end
if msg == 'state.change' then
self:setVar( 'entity_state', data[1] )
end
return insert( msgBox, { msg, data, source } )
end
self._msgFilterSetter = function( f ) msgFilter = f end
self.forceJumping = false
self.vars = {}
self.varDirty = true
self.currentExprJump = false
end
function FSMController:setMsgFilter( func )
return self._msgFilterSetter( func )
end
function FSMController:onAttach( entity )
Behaviour.onAttach( self, entity )
entity:addMsgListener( self.msgBoxListener )
end
function FSMController:onStart( entity )
self.threadFSMUpdate = self:addDaemonCoroutine( 'onThreadFSMUpdate' )
return Behaviour.onStart( self, entity )
end
function FSMController:onDetach( ent )
FSMController.__super.onDetach( self, ent )
ent:removeMsgListener( self.msgBoxListener )
end
function FSMController:getFSMUpdateThread()
return self.threadFSMUpdate
end
function FSMController:getState()
return self.state
end
function FSMController:inState(...)
local state = self:getState()
for i = 1, select( '#', ... ) do
local s = select( i , ... )
if s == state then return s end
end
return false
end
local stringfind=string.find
local function _isStartWith(a,b,b1,...)
if not a then return false end
if stringfind(a,b)==1 then return true end --a:startWith(b)
if b1 then return _isStartWith(a,b1,...) end
return false
end
function FSMController:inStateGroup( s1, ... )
return _isStartWith( self:getState(), s1, ... )
end
function FSMController:acceptStateChange( s )
return true
end
function FSMController:setState( state )
self.state = state
self.stateElapsedTime = 0
self.stateElapsedFrames = 0
if self._entity and self.syncEntityState then
self._entity:setState( state )
end
self:updateExprJump()
end
function FSMController:getEntityState()
return self._entity and self._entity:getState()
end
function FSMController:forceState( state, msg, args )
self.forceJumping = { state, msg or '__forced', args or {} }
end
function FSMController:forceRefreshState()
return self:forceState( self:getState() )
end
function FSMController:clearMsgBox()
table.clear( self.msgBox )
end
function FSMController:pushTopMsg( msg, data, source )
return insert( self.msgBox, 1, { msg, data, source } )
end
function FSMController:appendMsg( msg, data, source )
return insert( self.msgBox, { msg, data, source } )
end
function FSMController:pollMsg()
local m = remove( self.msgBox, 1 )
if m then return m[1],m[2],m[3] end
return nil
end
function FSMController:peekMsg( id )
id = id or 1
local m = self.msgBox[ id ]
if m then return m[1],m[2],m[3] end
return nil
end
function FSMController:hasMsgInBox( msg )
for i, m in ipairs( self.msgBox ) do
if m[1] == msg then return true end
end
return false
end
function FSMController:updateFSM( dt )
local func = self.currentStateFunc
if func then
return func( self, dt, 0 )
end
end
function FSMController:setScheme( schemePath )
self.schemePath = schemePath
local scheme = loadAsset( schemePath )
self.scheme = scheme
if scheme then
self.currentStateFunc = scheme[0]
self:validateStateMethods()
else
self.currentStateFunc = nil
end
end
function FSMController:validateStateMethods()
--todo
end
function FSMController:getScheme()
return self.schemePath
end
function FSMController:onThreadFSMUpdate()
local dt = 0
while true do
self.stateElapsedTime = self.stateElapsedTime + dt
self.stateElapsedFrames = self.stateElapsedFrames + 1
if self.varDirty then
self:updateExprJump()
end
self:updateFSM( dt )
dt = coroutine.yield()
end
end
function FSMController:getStateElapsedTime()
return self.stateElapsedTime
end
function FSMController:getStateElapsedFrames()
return self.stateElapsedFrames
end
----
function FSMController:setVar( key, value )
local v0 = self.vars[ key ]
if v0 == value then
return
end
self.vars[ key ] = value
self.varDirty = true
end
function FSMController:getVar( key, default )
local v = self.vars[ key ]
if v == nil then return default end
return v
end
function FSMController:getEvalEnv()
return self.vars
end
function FSMController:updateExprJump()
self.varDirty = false
local exprJump = self.currentExprJump
if not exprJump then return end
local env = self:getEvalEnv()
for msg, exprFunc in pairs( exprJump ) do
local ok, value = exprFunc( env )
if ok and value then
self:tell( exprFunc )
end
end
end
registerComponent( 'FSMController', FSMController )
| mit |
ashang/koreader | plugins/evernote.koplugin/clip.lua | 5 | 8903 | local DocumentRegistry = require("document/documentregistry")
local DocSettings = require("docsettings")
local DEBUG = require("dbg")
local md5 = require("MD5")
-- lfs
local MyClipping = {
my_clippings = "/mnt/us/documents/My Clippings.txt",
history_dir = "./history",
}
function MyClipping:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
--[[
-- clippings: main table to store parsed highlights and notes entries
-- {
-- ["Title(Author Name)"] = {
-- {
-- {
-- ["page"] = 123,
-- ["time"] = 1398127554,
-- ["text"] = "Games of all sorts were played in homes and fields."
-- },
-- {
-- ["page"] = 156,
-- ["time"] = 1398128287,
-- ["text"] = "There Spenser settled down to gentleman farming.",
-- ["note"] = "This is a sample note.",
-- },
-- ["title"] = "Chapter I"
-- },
-- }
-- }
-- ]]
function MyClipping:parseMyClippings()
-- My Clippings format:
-- Title(Author Name)
-- Your Highlight on Page 123 | Added on Monday, April 21, 2014 10:08:07 PM
--
-- This is a sample highlight.
-- ==========
local file = io.open(self.my_clippings, "r")
local clippings = {}
if file then
local index = 1
local corrupted = false
local title, author, info, text
for line in file:lines() do
line = line:match("^%s*(.-)%s*$") or ""
if index == 1 then
title, author = self:getTitle(line)
clippings[title] = clippings[title] or {
title = title,
author = author,
}
elseif index == 2 then
info = self:getInfo(line)
elseif index == 3 then
-- should be a blank line, we skip this line
elseif index == 4 then
text = self:getText(line)
end
if line == "==========" then
if index == 5 then
-- entry ends normally
local clipping = {
page = info.page or info.location,
sort = info.sort,
time = info.time,
text = text,
}
-- we cannot extract chapter info so just insert clipping
-- to a place holder chapter
table.insert(clippings[title], { clipping })
end
index = 0
end
index = index + 1
end
end
return clippings
end
local extensions = {
[".pdf"] = true,
[".djvu"] = true,
[".epub"] = true,
[".fb2"] = true,
[".mobi"] = true,
[".txt"] = true,
[".html"] = true,
[".doc"] = true,
}
-- remove file extensions added by former Koreader
-- extract author name in "Title(Author)" format
-- extract author name in "Title - Author" format
function MyClipping:getTitle(line)
line = line:match("^%s*(.-)%s*$") or ""
if extensions[line:sub(-4):lower()] then
line = line:sub(1, -5)
elseif extensions[line:sub(-5):lower()] then
line = line:sub(1, -6)
end
local _, _, title, author = line:find("(.-)%s*%((.*)%)")
if not author then
_, _, title, author = line:find("(.-)%s*-%s*(.*)")
end
if not title then title = line end
return title:match("^%s*(.-)%s*$"), author
end
local keywords = {
["highlight"] = {
"Highlight",
"标注",
},
["note"] = {
"Note",
"笔记",
},
["bookmark"] = {
"Bookmark",
"书签",
},
}
local months = {
["Jan"] = 1,
["Feb"] = 2,
["Mar"] = 3,
["Apr"] = 4,
["May"] = 5,
["Jun"] = 6,
["Jul"] = 7,
["Aug"] = 8,
["Sep"] = 9,
["Oct"] = 10,
["Nov"] = 11,
["Dec"] = 12
}
local pms = {
["PM"] = 12,
["下午"] = 12,
}
function MyClipping:getTime(line)
if not line then return end
local _, _, year, month, day = line:find("(%d+)年(%d+)月(%d+)日")
if not year or not month or not day then
_, _, year, month, day = line:find("(%d%d%d%d)-(%d%d)-(%d%d)")
end
if not year or not month or not day then
for k, v in pairs(months) do
if line:find(k) then
month = v
_, _, day = line:find(" (%d?%d),")
_, _, year = line:find(" (%d%d%d%d)")
break
end
end
end
local _, _, hour, minute, second = line:find("(%d+):(%d+):(%d+)")
if year and month and day and hour and minute and second then
for k, v in pairs(pms) do
if line:find(k) then hour = hour + v end
break
end
local time = os.time({
year = year, month = month, day = day,
hour = hour, min = minute, sec = second,
})
return time
end
end
function MyClipping:getInfo(line)
local info = {}
line = line or ""
local _, _, part1, part2 = line:find("(.+)%s*|%s*(.+)")
-- find entry type and location
for sort, words in pairs(keywords) do
for _, word in ipairs(words) do
if part1 and part1:find(word) then
info.sort = sort
info.location = part1:match("(%d+-?%d+)")
break
end
end
end
-- find entry created time
info.time = self:getTime(part2 or "")
return info
end
function MyClipping:getText(line)
line = line or ""
return line:match("^%s*(.-)%s*$") or ""
end
-- get PNG string and md5 hash
function MyClipping:getImage(image)
--DEBUG("image", image)
local doc = DocumentRegistry:openDocument(image.file)
if doc then
local png = doc:clipPagePNGString(image.pos0, image.pos1,
image.pboxes, image.drawer)
--doc:clipPagePNGFile(image.pos0, image.pos1,
--image.pboxes, image.drawer, "/tmp/"..md5(png)..".png")
doc:close()
if png then return { png = png, hash = md5(png) } end
end
end
function MyClipping:parseHighlight(highlights, book)
--DEBUG("book", book.file)
for page, items in pairs(highlights) do
for _, item in ipairs(items) do
local clipping = {}
clipping.page = page
clipping.sort = "highlight"
clipping.time = self:getTime(item.datetime or "")
clipping.text = self:getText(item.text)
if item.text == "" and item.pos0 and item.pos1 and
item.pos0.x and item.pos0.y and
item.pos1.x and item.pos1.y then
-- highlights in reflowing mode don't have page in pos
if item.pos0.page == nil then item.pos0.page = page end
if item.pos1.page == nil then item.pos1.page = page end
local image = {}
image.file = book.file
image.pos0, image.pos1 = item.pos0, item.pos1
image.pboxes = item.pboxes
image.drawer = item.drawer
clipping.image = self:getImage(image)
end
-- TODO: store chapter info when exporting highlights
if clipping.text and clipping.text ~= "" or clipping.image then
table.insert(book, { clipping })
end
end
end
table.sort(book, function(v1, v2) return v1[1].page < v2[1].page end)
end
function MyClipping:parseHistory()
local clippings = {}
for f in lfs.dir(self.history_dir) do
local path = self.history_dir.."/"..f
if lfs.attributes(path, "mode") == "file" and path:find(".+%.lua$") then
local ok, stored = pcall(dofile, path)
if ok and stored.highlight then
local _, _, docname = path:find("%[.*%](.*)%.lua$")
local title, author = self:getTitle(docname)
local path = DocSettings:getPathFromHistory(f)
local name = DocSettings:getNameFromHistory(f)
clippings[title] = {
file = path .. "/" .. name,
title = title,
author = author,
}
self:parseHighlight(stored.highlight, clippings[title])
end
end
end
return clippings
end
function MyClipping:parseCurrentDoc(view)
local clippings = {}
local path = view.document.file
local _, _, docname = path:find(".*/(.*)")
local title, author = self:getTitle(docname)
clippings[title] = {
file = view.document.file,
title = title,
author = author,
}
self:parseHighlight(view.highlight.saved, clippings[title])
return clippings
end
return MyClipping
| agpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Temenos/bcnms/temenos_western_tower.lua | 35 | 1096 | -----------------------------------
-- Area: Temenos
-- Name:
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[Temenos_W_Tower]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1298),TEMENOS);
HideTemenosDoor(GetInstanceRegion(1298));
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[Temenos_W_Tower]UniqueID"));
player:setVar("LimbusID",1298);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(WHITE_CARD);
end;
-- Leaving 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
player:setPos(580,-1.5,4.452,192);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
Cyco12/PotatoBot | deps/coro-spawn.lua | 6 | 2158 | --[[lit-meta
name = "creationix/coro-spawn"
version = "2.0.0"
dependencies = {
"creationix/coro-channel@2.0.0"
}
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-spawn.lua"
description = "An coro style interface to child processes."
tags = {"coro", "spawn", "child", "process"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
local uv = require('uv')
local channel = require('coro-channel')
local wrapRead = channel.wrapRead
local wrapWrite = channel.wrapWrite
return function (path, options)
local stdin, stdout, stderr
local stdio = options.stdio
-- If no custom stdio is passed in, create pipes for stdin, stdout, stderr.
if not stdio then
stdio = {true, true, true}
options.stdio = stdio
end
if stdio then
if stdio[1] == true then
stdin = uv.new_pipe(false)
stdio[1] = stdin
end
if stdio[2] == true then
stdout = uv.new_pipe(false)
stdio[2] = stdout
end
if stdio[3] == true then
stderr = uv.new_pipe(false)
stdio[3] = stderr
end
end
local exitThread, exitCode, exitSignal
local function onExit(code, signal)
exitCode = code
exitSignal = signal
if not exitThread then return end
local thread = exitThread
exitThread = nil
return assert(coroutine.resume(thread, code, signal))
end
local handle, pid = uv.spawn(path, options, onExit)
-- If the process has exited already, return the cached result.
-- Otherwise, wait for it to exit and return the result.
local function waitExit()
if exitCode then
return exitCode, exitSignal
end
assert(not exitThread, "Already waiting on exit")
exitThread = coroutine.running()
return coroutine.yield()
end
local result = {
handle = handle,
pid = pid,
waitExit = waitExit
}
if stdin then
result.stdin = {
handle = stdin,
write = wrapWrite(stdin)
}
end
if stdout then
result.stdout = {
handle = stdout,
read = wrapRead(stdout)
}
end
if stderr then
result.stderr = {
handle = stderr,
read = wrapRead(stderr)
}
end
return result
end
| apache-2.0 |
pecio/PetHealth-Broker | Common/AceConfig-3.0/AceConfigDialog-3.0/AceConfigDialog-3.0.lua | 2 | 59595 | --- AceConfigDialog-3.0 generates AceGUI-3.0 based windows based on option tables.
-- @class file
-- @name AceConfigDialog-3.0
-- @release $Id: AceConfigDialog-3.0.lua 1163 2017-08-14 14:04:39Z nevcairiel $
local LibStub = LibStub
local gui = LibStub("AceGUI-3.0")
local reg = LibStub("AceConfigRegistry-3.0")
local MAJOR, MINOR = "AceConfigDialog-3.0", 64
local AceConfigDialog, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConfigDialog then return end
AceConfigDialog.OpenFrames = AceConfigDialog.OpenFrames or {}
AceConfigDialog.Status = AceConfigDialog.Status or {}
AceConfigDialog.frame = AceConfigDialog.frame or CreateFrame("Frame")
AceConfigDialog.frame.apps = AceConfigDialog.frame.apps or {}
AceConfigDialog.frame.closing = AceConfigDialog.frame.closing or {}
AceConfigDialog.frame.closeAllOverride = AceConfigDialog.frame.closeAllOverride or {}
-- Lua APIs
local tconcat, tinsert, tsort, tremove, tsort = table.concat, table.insert, table.sort, table.remove, table.sort
local strmatch, format = string.match, string.format
local assert, loadstring, error = assert, loadstring, error
local pairs, next, select, type, unpack, wipe, ipairs = pairs, next, select, type, unpack, wipe, ipairs
local rawset, tostring, tonumber = rawset, tostring, tonumber
local math_min, math_max, math_floor = math.min, math.max, math.floor
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: NORMAL_FONT_COLOR, GameTooltip, StaticPopupDialogs, ACCEPT, CANCEL, StaticPopup_Show
-- GLOBALS: PlaySound, GameFontHighlight, GameFontHighlightSmall, GameFontHighlightLarge
-- GLOBALS: CloseSpecialWindows, InterfaceOptions_AddCategory, geterrorhandler
local emptyTbl = {}
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...)
return Dispatchers[select("#", ...)](func, ...)
end
local width_multiplier = 170
--[[
Group Types
Tree - All Descendant Groups will all become nodes on the tree, direct child options will appear above the tree
- Descendant Groups with inline=true and thier children will not become nodes
Tab - Direct Child Groups will become tabs, direct child options will appear above the tab control
- Grandchild groups will default to inline unless specified otherwise
Select- Same as Tab but with entries in a dropdown rather than tabs
Inline Groups
- Will not become nodes of a select group, they will be effectivly part of thier parent group seperated by a border
- If declared on a direct child of a root node of a select group, they will appear above the group container control
- When a group is displayed inline, all descendants will also be inline members of the group
]]
-- Recycling functions
local new, del, copy
--newcount, delcount,createdcount,cached = 0,0,0
do
local pool = setmetatable({},{__mode="k"})
function new()
--newcount = newcount + 1
local t = next(pool)
if t then
pool[t] = nil
return t
else
--createdcount = createdcount + 1
return {}
end
end
function copy(t)
local c = new()
for k, v in pairs(t) do
c[k] = v
end
return c
end
function del(t)
--delcount = delcount + 1
wipe(t)
pool[t] = true
end
-- function cached()
-- local n = 0
-- for k in pairs(pool) do
-- n = n + 1
-- end
-- return n
-- end
end
-- picks the first non-nil value and returns it
local function pickfirstset(...)
for i=1,select("#",...) do
if select(i,...)~=nil then
return select(i,...)
end
end
end
--gets an option from a given group, checking plugins
local function GetSubOption(group, key)
if group.plugins then
for plugin, t in pairs(group.plugins) do
if t[key] then
return t[key]
end
end
end
return group.args[key]
end
--Option member type definitions, used to decide how to access it
--Is the member Inherited from parent options
local isInherited = {
set = true,
get = true,
func = true,
confirm = true,
validate = true,
disabled = true,
hidden = true
}
--Does a string type mean a literal value, instead of the default of a method of the handler
local stringIsLiteral = {
name = true,
desc = true,
icon = true,
usage = true,
width = true,
image = true,
fontSize = true,
}
--Is Never a function or method
local allIsLiteral = {
type = true,
descStyle = true,
imageWidth = true,
imageHeight = true,
}
--gets the value for a member that could be a function
--function refs are called with an info arg
--every other type is returned
local function GetOptionsMemberValue(membername, option, options, path, appName, ...)
--get definition for the member
local inherits = isInherited[membername]
--get the member of the option, traversing the tree if it can be inherited
local member
if inherits then
local group = options
if group[membername] ~= nil then
member = group[membername]
end
for i = 1, #path do
group = GetSubOption(group, path[i])
if group[membername] ~= nil then
member = group[membername]
end
end
else
member = option[membername]
end
--check if we need to call a functon, or if we have a literal value
if ( not allIsLiteral[membername] ) and ( type(member) == "function" or ((not stringIsLiteral[membername]) and type(member) == "string") ) then
--We have a function to call
local info = new()
--traverse the options table, picking up the handler and filling the info with the path
local handler
local group = options
handler = group.handler or handler
for i = 1, #path do
group = GetSubOption(group, path[i])
info[i] = path[i]
handler = group.handler or handler
end
info.options = options
info.appName = appName
info[0] = appName
info.arg = option.arg
info.handler = handler
info.option = option
info.type = option.type
info.uiType = "dialog"
info.uiName = MAJOR
local a, b, c ,d
--using 4 returns for the get of a color type, increase if a type needs more
if type(member) == "function" then
--Call the function
a,b,c,d = member(info, ...)
else
--Call the method
if handler and handler[member] then
a,b,c,d = handler[member](handler, info, ...)
else
error(format("Method %s doesn't exist in handler for type %s", member, membername))
end
end
del(info)
return a,b,c,d
else
--The value isnt a function to call, return it
return member
end
end
--[[calls an options function that could be inherited, method name or function ref
local function CallOptionsFunction(funcname ,option, options, path, appName, ...)
local info = new()
local func
local group = options
local handler
--build the info table containing the path
-- pick up functions while traversing the tree
if group[funcname] ~= nil then
func = group[funcname]
end
handler = group.handler or handler
for i, v in ipairs(path) do
group = GetSubOption(group, v)
info[i] = v
if group[funcname] ~= nil then
func = group[funcname]
end
handler = group.handler or handler
end
info.options = options
info[0] = appName
info.arg = option.arg
local a, b, c ,d
if type(func) == "string" then
if handler and handler[func] then
a,b,c,d = handler[func](handler, info, ...)
else
error(string.format("Method %s doesn't exist in handler for type func", func))
end
elseif type(func) == "function" then
a,b,c,d = func(info, ...)
end
del(info)
return a,b,c,d
end
--]]
--tables to hold orders and names for options being sorted, will be created with new()
--prevents needing to call functions repeatedly while sorting
local tempOrders
local tempNames
local function compareOptions(a,b)
if not a then
return true
end
if not b then
return false
end
local OrderA, OrderB = tempOrders[a] or 100, tempOrders[b] or 100
if OrderA == OrderB then
local NameA = (type(tempNames[a]) == "string") and tempNames[a] or ""
local NameB = (type(tempNames[b]) == "string") and tempNames[b] or ""
return NameA:upper() < NameB:upper()
end
if OrderA < 0 then
if OrderB > 0 then
return false
end
else
if OrderB < 0 then
return true
end
end
return OrderA < OrderB
end
--builds 2 tables out of an options group
-- keySort, sorted keys
-- opts, combined options from .plugins and args
local function BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
tempOrders = new()
tempNames = new()
if group.plugins then
for plugin, t in pairs(group.plugins) do
for k, v in pairs(t) do
if not opts[k] then
tinsert(keySort, k)
opts[k] = v
path[#path+1] = k
tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName)
tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName)
path[#path] = nil
end
end
end
end
for k, v in pairs(group.args) do
if not opts[k] then
tinsert(keySort, k)
opts[k] = v
path[#path+1] = k
tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName)
tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName)
path[#path] = nil
end
end
tsort(keySort, compareOptions)
del(tempOrders)
del(tempNames)
end
local function DelTree(tree)
if tree.children then
local childs = tree.children
for i = 1, #childs do
DelTree(childs[i])
del(childs[i])
end
del(childs)
end
end
local function CleanUserData(widget, event)
local user = widget:GetUserDataTable()
if user.path then
del(user.path)
end
if widget.type == "TreeGroup" then
local tree = user.tree
widget:SetTree(nil)
if tree then
for i = 1, #tree do
DelTree(tree[i])
del(tree[i])
end
del(tree)
end
end
if widget.type == "TabGroup" then
widget:SetTabs(nil)
if user.tablist then
del(user.tablist)
end
end
if widget.type == "DropdownGroup" then
widget:SetGroupList(nil)
if user.grouplist then
del(user.grouplist)
end
if user.orderlist then
del(user.orderlist)
end
end
end
-- - Gets a status table for the given appname and options path.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param path The path to the options (a table with all group keys)
-- @return
function AceConfigDialog:GetStatusTable(appName, path)
local status = self.Status
if not status[appName] then
status[appName] = {}
status[appName].status = {}
status[appName].children = {}
end
status = status[appName]
if path then
for i = 1, #path do
local v = path[i]
if not status.children[v] then
status.children[v] = {}
status.children[v].status = {}
status.children[v].children = {}
end
status = status.children[v]
end
end
return status.status
end
--- Selects the specified path in the options window.
-- The path specified has to match the keys of the groups in the table.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param ... The path to the key that should be selected
function AceConfigDialog:SelectGroup(appName, ...)
local path = new()
local app = reg:GetOptionsTable(appName)
if not app then
error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2)
end
local options = app("dialog", MAJOR)
local group = options
local status = self:GetStatusTable(appName, path)
if not status.groups then
status.groups = {}
end
status = status.groups
local treevalue
local treestatus
for n = 1, select("#",...) do
local key = select(n, ...)
if group.childGroups == "tab" or group.childGroups == "select" then
--if this is a tab or select group, select the group
status.selected = key
--children of this group are no longer extra levels of a tree
treevalue = nil
else
--tree group by default
if treevalue then
--this is an extra level of a tree group, build a uniquevalue for it
treevalue = treevalue.."\001"..key
else
--this is the top level of a tree group, the uniquevalue is the same as the key
treevalue = key
if not status.groups then
status.groups = {}
end
--save this trees status table for any extra levels or groups
treestatus = status
end
--make sure that the tree entry is open, and select it.
--the selected group will be overwritten if a child is the final target but still needs to be open
treestatus.selected = treevalue
treestatus.groups[treevalue] = true
end
--move to the next group in the path
group = GetSubOption(group, key)
if not group then
break
end
tinsert(path, key)
status = self:GetStatusTable(appName, path)
if not status.groups then
status.groups = {}
end
status = status.groups
end
del(path)
reg:NotifyChange(appName)
end
local function OptionOnMouseOver(widget, event)
--show a tooltip/set the status bar to the desc text
local user = widget:GetUserDataTable()
local opt = user.option
local options = user.options
local path = user.path
local appName = user.appName
GameTooltip:SetOwner(widget.frame, "ANCHOR_TOPRIGHT")
local name = GetOptionsMemberValue("name", opt, options, path, appName)
local desc = GetOptionsMemberValue("desc", opt, options, path, appName)
local usage = GetOptionsMemberValue("usage", opt, options, path, appName)
local descStyle = opt.descStyle
if descStyle and descStyle ~= "tooltip" then return end
GameTooltip:SetText(name, 1, .82, 0, true)
if opt.type == "multiselect" then
GameTooltip:AddLine(user.text, 0.5, 0.5, 0.8, true)
end
if type(desc) == "string" then
GameTooltip:AddLine(desc, 1, 1, 1, true)
end
if type(usage) == "string" then
GameTooltip:AddLine("Usage: "..usage, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, true)
end
GameTooltip:Show()
end
local function OptionOnMouseLeave(widget, event)
GameTooltip:Hide()
end
local function GetFuncName(option)
local type = option.type
if type == "execute" then
return "func"
else
return "set"
end
end
local function confirmPopup(appName, rootframe, basepath, info, message, func, ...)
if not StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] then
StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] = {}
end
local t = StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"]
for k in pairs(t) do
t[k] = nil
end
t.text = message
t.button1 = ACCEPT
t.button2 = CANCEL
t.preferredIndex = STATICPOPUP_NUMDIALOGS
local dialog, oldstrata
t.OnAccept = function()
safecall(func, unpack(t))
if dialog and oldstrata then
dialog:SetFrameStrata(oldstrata)
end
AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl))
del(info)
end
t.OnCancel = function()
if dialog and oldstrata then
dialog:SetFrameStrata(oldstrata)
end
AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl))
del(info)
end
for i = 1, select("#", ...) do
t[i] = select(i, ...) or false
end
t.timeout = 0
t.whileDead = 1
t.hideOnEscape = 1
dialog = StaticPopup_Show("ACECONFIGDIALOG30_CONFIRM_DIALOG")
if dialog then
oldstrata = dialog:GetFrameStrata()
dialog:SetFrameStrata("TOOLTIP")
end
end
local function validationErrorPopup(message)
if not StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"] then
StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"] = {}
end
local t = StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"]
t.text = message
t.button1 = OKAY
t.preferredIndex = STATICPOPUP_NUMDIALOGS
local dialog, oldstrata
t.OnAccept = function()
if dialog and oldstrata then
dialog:SetFrameStrata(oldstrata)
end
end
t.timeout = 0
t.whileDead = 1
t.hideOnEscape = 1
dialog = StaticPopup_Show("ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG")
if dialog then
oldstrata = dialog:GetFrameStrata()
dialog:SetFrameStrata("TOOLTIP")
end
end
local function ActivateControl(widget, event, ...)
--This function will call the set / execute handler for the widget
--widget:GetUserDataTable() contains the needed info
local user = widget:GetUserDataTable()
local option = user.option
local options = user.options
local path = user.path
local info = new()
local func
local group = options
local funcname = GetFuncName(option)
local handler
local confirm
local validate
--build the info table containing the path
-- pick up functions while traversing the tree
if group[funcname] ~= nil then
func = group[funcname]
end
handler = group.handler or handler
confirm = group.confirm
validate = group.validate
for i = 1, #path do
local v = path[i]
group = GetSubOption(group, v)
info[i] = v
if group[funcname] ~= nil then
func = group[funcname]
end
handler = group.handler or handler
if group.confirm ~= nil then
confirm = group.confirm
end
if group.validate ~= nil then
validate = group.validate
end
end
info.options = options
info.appName = user.appName
info.arg = option.arg
info.handler = handler
info.option = option
info.type = option.type
info.uiType = "dialog"
info.uiName = MAJOR
local name
if type(option.name) == "function" then
name = option.name(info)
elseif type(option.name) == "string" then
name = option.name
else
name = ""
end
local usage = option.usage
local pattern = option.pattern
local validated = true
if option.type == "input" then
if type(pattern)=="string" then
if not strmatch(..., pattern) then
validated = false
end
end
end
local success
if validated and option.type ~= "execute" then
if type(validate) == "string" then
if handler and handler[validate] then
success, validated = safecall(handler[validate], handler, info, ...)
if not success then validated = false end
else
error(format("Method %s doesn't exist in handler for type execute", validate))
end
elseif type(validate) == "function" then
success, validated = safecall(validate, info, ...)
if not success then validated = false end
end
end
local rootframe = user.rootframe
if not validated or type(validated) == "string" then
if not validated then
if usage then
validated = name..": "..usage
else
if pattern then
validated = name..": Expected "..pattern
else
validated = name..": Invalid Value"
end
end
end
-- show validate message
if rootframe.SetStatusText then
rootframe:SetStatusText(validated)
else
validationErrorPopup(validated)
end
PlaySound(PlaySoundKitID and "igPlayerInviteDecline" or 882) -- SOUNDKIT.IG_PLAYER_INVITE_DECLINE || XXX _DECLINE is actually missing from the table
del(info)
return true
else
local confirmText = option.confirmText
--call confirm func/method
if type(confirm) == "string" then
if handler and handler[confirm] then
success, confirm = safecall(handler[confirm], handler, info, ...)
if success and type(confirm) == "string" then
confirmText = confirm
confirm = true
elseif not success then
confirm = false
end
else
error(format("Method %s doesn't exist in handler for type confirm", confirm))
end
elseif type(confirm) == "function" then
success, confirm = safecall(confirm, info, ...)
if success and type(confirm) == "string" then
confirmText = confirm
confirm = true
elseif not success then
confirm = false
end
end
--confirm if needed
if type(confirm) == "boolean" then
if confirm then
if not confirmText then
local name, desc = option.name, option.desc
if type(name) == "function" then
name = name(info)
end
if type(desc) == "function" then
desc = desc(info)
end
confirmText = name
if desc then
confirmText = confirmText.." - "..desc
end
end
local iscustom = user.rootframe:GetUserData("iscustom")
local rootframe
if iscustom then
rootframe = user.rootframe
end
local basepath = user.rootframe:GetUserData("basepath")
if type(func) == "string" then
if handler and handler[func] then
confirmPopup(user.appName, rootframe, basepath, info, confirmText, handler[func], handler, info, ...)
else
error(format("Method %s doesn't exist in handler for type func", func))
end
elseif type(func) == "function" then
confirmPopup(user.appName, rootframe, basepath, info, confirmText, func, info, ...)
end
--func will be called and info deleted when the confirm dialog is responded to
return
end
end
--call the function
if type(func) == "string" then
if handler and handler[func] then
safecall(handler[func],handler, info, ...)
else
error(format("Method %s doesn't exist in handler for type func", func))
end
elseif type(func) == "function" then
safecall(func,info, ...)
end
local iscustom = user.rootframe:GetUserData("iscustom")
local basepath = user.rootframe:GetUserData("basepath") or emptyTbl
--full refresh of the frame, some controls dont cause this on all events
if option.type == "color" then
if event == "OnValueConfirmed" then
if iscustom then
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath))
else
AceConfigDialog:Open(user.appName, unpack(basepath))
end
end
elseif option.type == "range" then
if event == "OnMouseUp" then
if iscustom then
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath))
else
AceConfigDialog:Open(user.appName, unpack(basepath))
end
end
--multiselects don't cause a refresh on 'OnValueChanged' only 'OnClosed'
elseif option.type == "multiselect" then
user.valuechanged = true
else
if iscustom then
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath))
else
AceConfigDialog:Open(user.appName, unpack(basepath))
end
end
end
del(info)
end
local function ActivateSlider(widget, event, value)
local option = widget:GetUserData("option")
local min, max, step = option.min or (not option.softMin and 0 or nil), option.max or (not option.softMax and 100 or nil), option.step
if min then
if step then
value = math_floor((value - min) / step + 0.5) * step + min
end
value = math_max(value, min)
end
if max then
value = math_min(value, max)
end
ActivateControl(widget,event,value)
end
--called from a checkbox that is part of an internally created multiselect group
--this type is safe to refresh on activation of one control
local function ActivateMultiControl(widget, event, ...)
ActivateControl(widget, event, widget:GetUserData("value"), ...)
local user = widget:GetUserDataTable()
local iscustom = user.rootframe:GetUserData("iscustom")
local basepath = user.rootframe:GetUserData("basepath") or emptyTbl
if iscustom then
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath))
else
AceConfigDialog:Open(user.appName, unpack(basepath))
end
end
local function MultiControlOnClosed(widget, event, ...)
local user = widget:GetUserDataTable()
if user.valuechanged then
local iscustom = user.rootframe:GetUserData("iscustom")
local basepath = user.rootframe:GetUserData("basepath") or emptyTbl
if iscustom then
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath))
else
AceConfigDialog:Open(user.appName, unpack(basepath))
end
end
end
local function FrameOnClose(widget, event)
local appName = widget:GetUserData("appName")
AceConfigDialog.OpenFrames[appName] = nil
gui:Release(widget)
end
local function CheckOptionHidden(option, options, path, appName)
--check for a specific boolean option
local hidden = pickfirstset(option.dialogHidden,option.guiHidden)
if hidden ~= nil then
return hidden
end
return GetOptionsMemberValue("hidden", option, options, path, appName)
end
local function CheckOptionDisabled(option, options, path, appName)
--check for a specific boolean option
local disabled = pickfirstset(option.dialogDisabled,option.guiDisabled)
if disabled ~= nil then
return disabled
end
return GetOptionsMemberValue("disabled", option, options, path, appName)
end
--[[
local function BuildTabs(group, options, path, appName)
local tabs = new()
local text = new()
local keySort = new()
local opts = new()
BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
for i = 1, #keySort do
local k = keySort[i]
local v = opts[k]
if v.type == "group" then
path[#path+1] = k
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false)
local hidden = CheckOptionHidden(v, options, path, appName)
if not inline and not hidden then
tinsert(tabs, k)
text[k] = GetOptionsMemberValue("name", v, options, path, appName)
end
path[#path] = nil
end
end
del(keySort)
del(opts)
return tabs, text
end
]]
local function BuildSelect(group, options, path, appName)
local groups = new()
local order = new()
local keySort = new()
local opts = new()
BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
for i = 1, #keySort do
local k = keySort[i]
local v = opts[k]
if v.type == "group" then
path[#path+1] = k
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false)
local hidden = CheckOptionHidden(v, options, path, appName)
if not inline and not hidden then
groups[k] = GetOptionsMemberValue("name", v, options, path, appName)
tinsert(order, k)
end
path[#path] = nil
end
end
del(opts)
del(keySort)
return groups, order
end
local function BuildSubGroups(group, tree, options, path, appName)
local keySort = new()
local opts = new()
BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
for i = 1, #keySort do
local k = keySort[i]
local v = opts[k]
if v.type == "group" then
path[#path+1] = k
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false)
local hidden = CheckOptionHidden(v, options, path, appName)
if not inline and not hidden then
local entry = new()
entry.value = k
entry.text = GetOptionsMemberValue("name", v, options, path, appName)
entry.icon = GetOptionsMemberValue("icon", v, options, path, appName)
entry.iconCoords = GetOptionsMemberValue("iconCoords", v, options, path, appName)
entry.disabled = CheckOptionDisabled(v, options, path, appName)
if not tree.children then tree.children = new() end
tinsert(tree.children,entry)
if (v.childGroups or "tree") == "tree" then
BuildSubGroups(v,entry, options, path, appName)
end
end
path[#path] = nil
end
end
del(keySort)
del(opts)
end
local function BuildGroups(group, options, path, appName, recurse)
local tree = new()
local keySort = new()
local opts = new()
BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
for i = 1, #keySort do
local k = keySort[i]
local v = opts[k]
if v.type == "group" then
path[#path+1] = k
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false)
local hidden = CheckOptionHidden(v, options, path, appName)
if not inline and not hidden then
local entry = new()
entry.value = k
entry.text = GetOptionsMemberValue("name", v, options, path, appName)
entry.icon = GetOptionsMemberValue("icon", v, options, path, appName)
entry.disabled = CheckOptionDisabled(v, options, path, appName)
tinsert(tree,entry)
if recurse and (v.childGroups or "tree") == "tree" then
BuildSubGroups(v,entry, options, path, appName)
end
end
path[#path] = nil
end
end
del(keySort)
del(opts)
return tree
end
local function InjectInfo(control, options, option, path, rootframe, appName)
local user = control:GetUserDataTable()
for i = 1, #path do
user[i] = path[i]
end
user.rootframe = rootframe
user.option = option
user.options = options
user.path = copy(path)
user.appName = appName
control:SetCallback("OnRelease", CleanUserData)
control:SetCallback("OnLeave", OptionOnMouseLeave)
control:SetCallback("OnEnter", OptionOnMouseOver)
end
--[[
options - root of the options table being fed
container - widget that controls will be placed in
rootframe - Frame object the options are in
path - table with the keys to get to the group being fed
--]]
local function FeedOptions(appName, options,container,rootframe,path,group,inline)
local keySort = new()
local opts = new()
BuildSortedOptionsTable(group, keySort, opts, options, path, appName)
for i = 1, #keySort do
local k = keySort[i]
local v = opts[k]
tinsert(path, k)
local hidden = CheckOptionHidden(v, options, path, appName)
local name = GetOptionsMemberValue("name", v, options, path, appName)
if not hidden then
if v.type == "group" then
if inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) then
--Inline group
local GroupContainer
if name and name ~= "" then
GroupContainer = gui:Create("InlineGroup")
GroupContainer:SetTitle(name or "")
else
GroupContainer = gui:Create("SimpleGroup")
end
GroupContainer.width = "fill"
GroupContainer:SetLayout("flow")
container:AddChild(GroupContainer)
FeedOptions(appName,options,GroupContainer,rootframe,path,v,true)
end
else
--Control to feed
local control
local name = GetOptionsMemberValue("name", v, options, path, appName)
if v.type == "execute" then
local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName)
local image, width, height = GetOptionsMemberValue("image",v, options, path, appName)
if type(image) == "string" or type(image) == "number" then
control = gui:Create("Icon")
if not width then
width = GetOptionsMemberValue("imageWidth",v, options, path, appName)
end
if not height then
height = GetOptionsMemberValue("imageHeight",v, options, path, appName)
end
if type(imageCoords) == "table" then
control:SetImage(image, unpack(imageCoords))
else
control:SetImage(image)
end
if type(width) ~= "number" then
width = 32
end
if type(height) ~= "number" then
height = 32
end
control:SetImageSize(width, height)
control:SetLabel(name)
else
control = gui:Create("Button")
control:SetText(name)
end
control:SetCallback("OnClick",ActivateControl)
elseif v.type == "input" then
local controlType = v.dialogControl or v.control or (v.multiline and "MultiLineEditBox") or "EditBox"
control = gui:Create(controlType)
if not control then
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType)))
control = gui:Create(v.multiline and "MultiLineEditBox" or "EditBox")
end
if v.multiline and control.SetNumLines then
control:SetNumLines(tonumber(v.multiline) or 4)
end
control:SetLabel(name)
control:SetCallback("OnEnterPressed",ActivateControl)
local text = GetOptionsMemberValue("get",v, options, path, appName)
if type(text) ~= "string" then
text = ""
end
control:SetText(text)
elseif v.type == "toggle" then
control = gui:Create("CheckBox")
control:SetLabel(name)
control:SetTriState(v.tristate)
local value = GetOptionsMemberValue("get",v, options, path, appName)
control:SetValue(value)
control:SetCallback("OnValueChanged",ActivateControl)
if v.descStyle == "inline" then
local desc = GetOptionsMemberValue("desc", v, options, path, appName)
control:SetDescription(desc)
end
local image = GetOptionsMemberValue("image", v, options, path, appName)
local imageCoords = GetOptionsMemberValue("imageCoords", v, options, path, appName)
if type(image) == "string" or type(image) == "number" then
if type(imageCoords) == "table" then
control:SetImage(image, unpack(imageCoords))
else
control:SetImage(image)
end
end
elseif v.type == "range" then
control = gui:Create("Slider")
control:SetLabel(name)
control:SetSliderValues(v.softMin or v.min or 0, v.softMax or v.max or 100, v.bigStep or v.step or 0)
control:SetIsPercent(v.isPercent)
local value = GetOptionsMemberValue("get",v, options, path, appName)
if type(value) ~= "number" then
value = 0
end
control:SetValue(value)
control:SetCallback("OnValueChanged",ActivateSlider)
control:SetCallback("OnMouseUp",ActivateSlider)
elseif v.type == "select" then
local values = GetOptionsMemberValue("values", v, options, path, appName)
if v.style == "radio" then
local disabled = CheckOptionDisabled(v, options, path, appName)
local width = GetOptionsMemberValue("width",v,options,path,appName)
control = gui:Create("InlineGroup")
control:SetLayout("Flow")
control:SetTitle(name)
control.width = "fill"
control:PauseLayout()
local optionValue = GetOptionsMemberValue("get",v, options, path, appName)
local t = {}
for value, text in pairs(values) do
t[#t+1]=value
end
tsort(t)
for k, value in ipairs(t) do
local text = values[value]
local radio = gui:Create("CheckBox")
radio:SetLabel(text)
radio:SetUserData("value", value)
radio:SetUserData("text", text)
radio:SetDisabled(disabled)
radio:SetType("radio")
radio:SetValue(optionValue == value)
radio:SetCallback("OnValueChanged", ActivateMultiControl)
InjectInfo(radio, options, v, path, rootframe, appName)
control:AddChild(radio)
if width == "double" then
radio:SetWidth(width_multiplier * 2)
elseif width == "half" then
radio:SetWidth(width_multiplier / 2)
elseif width == "full" then
radio.width = "fill"
else
radio:SetWidth(width_multiplier)
end
end
control:ResumeLayout()
control:DoLayout()
else
local controlType = v.dialogControl or v.control or "Dropdown"
control = gui:Create(controlType)
if not control then
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType)))
control = gui:Create("Dropdown")
end
local itemType = v.itemControl
if itemType and not gui:GetWidgetVersion(itemType) then
geterrorhandler()(("Invalid Custom Item Type - %s"):format(tostring(itemType)))
itemType = nil
end
control:SetLabel(name)
control:SetList(values, nil, itemType)
local value = GetOptionsMemberValue("get",v, options, path, appName)
if not values[value] then
value = nil
end
control:SetValue(value)
control:SetCallback("OnValueChanged", ActivateControl)
end
elseif v.type == "multiselect" then
local values = GetOptionsMemberValue("values", v, options, path, appName)
local disabled = CheckOptionDisabled(v, options, path, appName)
local controlType = v.dialogControl or v.control
local valuesort = new()
if values then
for value, text in pairs(values) do
tinsert(valuesort, value)
end
end
tsort(valuesort)
if controlType then
control = gui:Create(controlType)
if not control then
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType)))
end
end
if control then
control:SetMultiselect(true)
control:SetLabel(name)
control:SetList(values)
control:SetDisabled(disabled)
control:SetCallback("OnValueChanged",ActivateControl)
control:SetCallback("OnClosed", MultiControlOnClosed)
local width = GetOptionsMemberValue("width",v,options,path,appName)
if width == "double" then
control:SetWidth(width_multiplier * 2)
elseif width == "half" then
control:SetWidth(width_multiplier / 2)
elseif width == "full" then
control.width = "fill"
else
control:SetWidth(width_multiplier)
end
--check:SetTriState(v.tristate)
for i = 1, #valuesort do
local key = valuesort[i]
local value = GetOptionsMemberValue("get",v, options, path, appName, key)
control:SetItemValue(key,value)
end
else
control = gui:Create("InlineGroup")
control:SetLayout("Flow")
control:SetTitle(name)
control.width = "fill"
control:PauseLayout()
local width = GetOptionsMemberValue("width",v,options,path,appName)
for i = 1, #valuesort do
local value = valuesort[i]
local text = values[value]
local check = gui:Create("CheckBox")
check:SetLabel(text)
check:SetUserData("value", value)
check:SetUserData("text", text)
check:SetDisabled(disabled)
check:SetTriState(v.tristate)
check:SetValue(GetOptionsMemberValue("get",v, options, path, appName, value))
check:SetCallback("OnValueChanged",ActivateMultiControl)
InjectInfo(check, options, v, path, rootframe, appName)
control:AddChild(check)
if width == "double" then
check:SetWidth(width_multiplier * 2)
elseif width == "half" then
check:SetWidth(width_multiplier / 2)
elseif width == "full" then
check.width = "fill"
else
check:SetWidth(width_multiplier)
end
end
control:ResumeLayout()
control:DoLayout()
end
del(valuesort)
elseif v.type == "color" then
control = gui:Create("ColorPicker")
control:SetLabel(name)
control:SetHasAlpha(GetOptionsMemberValue("hasAlpha",v, options, path, appName))
control:SetColor(GetOptionsMemberValue("get",v, options, path, appName))
control:SetCallback("OnValueChanged",ActivateControl)
control:SetCallback("OnValueConfirmed",ActivateControl)
elseif v.type == "keybinding" then
control = gui:Create("Keybinding")
control:SetLabel(name)
control:SetKey(GetOptionsMemberValue("get",v, options, path, appName))
control:SetCallback("OnKeyChanged",ActivateControl)
elseif v.type == "header" then
control = gui:Create("Heading")
control:SetText(name)
control.width = "fill"
elseif v.type == "description" then
control = gui:Create("Label")
control:SetText(name)
local fontSize = GetOptionsMemberValue("fontSize",v, options, path, appName)
if fontSize == "medium" then
control:SetFontObject(GameFontHighlight)
elseif fontSize == "large" then
control:SetFontObject(GameFontHighlightLarge)
else -- small or invalid
control:SetFontObject(GameFontHighlightSmall)
end
local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName)
local image, width, height = GetOptionsMemberValue("image",v, options, path, appName)
if type(image) == "string" or type(image) == "number" then
if not width then
width = GetOptionsMemberValue("imageWidth",v, options, path, appName)
end
if not height then
height = GetOptionsMemberValue("imageHeight",v, options, path, appName)
end
if type(imageCoords) == "table" then
control:SetImage(image, unpack(imageCoords))
else
control:SetImage(image)
end
if type(width) ~= "number" then
width = 32
end
if type(height) ~= "number" then
height = 32
end
control:SetImageSize(width, height)
end
local width = GetOptionsMemberValue("width",v,options,path,appName)
control.width = not width and "fill"
end
--Common Init
if control then
if control.width ~= "fill" then
local width = GetOptionsMemberValue("width",v,options,path,appName)
if width == "double" then
control:SetWidth(width_multiplier * 2)
elseif width == "half" then
control:SetWidth(width_multiplier / 2)
elseif width == "full" then
control.width = "fill"
else
control:SetWidth(width_multiplier)
end
end
if control.SetDisabled then
local disabled = CheckOptionDisabled(v, options, path, appName)
control:SetDisabled(disabled)
end
InjectInfo(control, options, v, path, rootframe, appName)
container:AddChild(control)
end
end
end
tremove(path)
end
container:ResumeLayout()
container:DoLayout()
del(keySort)
del(opts)
end
local function BuildPath(path, ...)
for i = 1, select("#",...) do
tinsert(path, (select(i,...)))
end
end
local function TreeOnButtonEnter(widget, event, uniquevalue, button)
local user = widget:GetUserDataTable()
if not user then return end
local options = user.options
local option = user.option
local path = user.path
local appName = user.appName
local feedpath = new()
for i = 1, #path do
feedpath[i] = path[i]
end
BuildPath(feedpath, ("\001"):split(uniquevalue))
local group = options
for i = 1, #feedpath do
if not group then return end
group = GetSubOption(group, feedpath[i])
end
local name = GetOptionsMemberValue("name", group, options, feedpath, appName)
local desc = GetOptionsMemberValue("desc", group, options, feedpath, appName)
GameTooltip:SetOwner(button, "ANCHOR_NONE")
if widget.type == "TabGroup" then
GameTooltip:SetPoint("BOTTOM",button,"TOP")
else
GameTooltip:SetPoint("LEFT",button,"RIGHT")
end
GameTooltip:SetText(name, 1, .82, 0, true)
if type(desc) == "string" then
GameTooltip:AddLine(desc, 1, 1, 1, true)
end
GameTooltip:Show()
end
local function TreeOnButtonLeave(widget, event, value, button)
GameTooltip:Hide()
end
local function GroupExists(appName, options, path, uniquevalue)
if not uniquevalue then return false end
local feedpath = new()
local temppath = new()
for i = 1, #path do
feedpath[i] = path[i]
end
BuildPath(feedpath, ("\001"):split(uniquevalue))
local group = options
for i = 1, #feedpath do
local v = feedpath[i]
temppath[i] = v
group = GetSubOption(group, v)
if not group or group.type ~= "group" or CheckOptionHidden(group, options, temppath, appName) then
del(feedpath)
del(temppath)
return false
end
end
del(feedpath)
del(temppath)
return true
end
local function GroupSelected(widget, event, uniquevalue)
local user = widget:GetUserDataTable()
local options = user.options
local option = user.option
local path = user.path
local rootframe = user.rootframe
local feedpath = new()
for i = 1, #path do
feedpath[i] = path[i]
end
BuildPath(feedpath, ("\001"):split(uniquevalue))
local group = options
for i = 1, #feedpath do
group = GetSubOption(group, feedpath[i])
end
widget:ReleaseChildren()
AceConfigDialog:FeedGroup(user.appName,options,widget,rootframe,feedpath)
del(feedpath)
end
--[[
-- INTERNAL --
This function will feed one group, and any inline child groups into the given container
Select Groups will only have the selection control (tree, tabs, dropdown) fed in
and have a group selected, this event will trigger the feeding of child groups
Rules:
If the group is Inline, FeedOptions
If the group has no child groups, FeedOptions
If the group is a tab or select group, FeedOptions then add the Group Control
If the group is a tree group FeedOptions then
its parent isnt a tree group: then add the tree control containing this and all child tree groups
if its parent is a tree group, its already a node on a tree
--]]
function AceConfigDialog:FeedGroup(appName,options,container,rootframe,path, isRoot)
local group = options
--follow the path to get to the curent group
local inline
local grouptype, parenttype = options.childGroups, "none"
for i = 1, #path do
local v = path[i]
group = GetSubOption(group, v)
inline = inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false)
parenttype = grouptype
grouptype = group.childGroups
end
if not parenttype then
parenttype = "tree"
end
--check if the group has child groups
local hasChildGroups
for k, v in pairs(group.args) do
if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then
hasChildGroups = true
end
end
if group.plugins then
for plugin, t in pairs(group.plugins) do
for k, v in pairs(t) do
if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then
hasChildGroups = true
end
end
end
end
container:SetLayout("flow")
local scroll
--Add a scrollframe if we are not going to add a group control, this is the inverse of the conditions for that later on
if (not (hasChildGroups and not inline)) or (grouptype ~= "tab" and grouptype ~= "select" and (parenttype == "tree" and not isRoot)) then
if container.type ~= "InlineGroup" and container.type ~= "SimpleGroup" then
scroll = gui:Create("ScrollFrame")
scroll:SetLayout("flow")
scroll.width = "fill"
scroll.height = "fill"
container:SetLayout("fill")
container:AddChild(scroll)
container = scroll
end
end
FeedOptions(appName,options,container,rootframe,path,group,nil)
if scroll then
container:PerformLayout()
local status = self:GetStatusTable(appName, path)
if not status.scroll then
status.scroll = {}
end
scroll:SetStatusTable(status.scroll)
end
if hasChildGroups and not inline then
local name = GetOptionsMemberValue("name", group, options, path, appName)
if grouptype == "tab" then
local tab = gui:Create("TabGroup")
InjectInfo(tab, options, group, path, rootframe, appName)
tab:SetCallback("OnGroupSelected", GroupSelected)
tab:SetCallback("OnTabEnter", TreeOnButtonEnter)
tab:SetCallback("OnTabLeave", TreeOnButtonLeave)
local status = AceConfigDialog:GetStatusTable(appName, path)
if not status.groups then
status.groups = {}
end
tab:SetStatusTable(status.groups)
tab.width = "fill"
tab.height = "fill"
local tabs = BuildGroups(group, options, path, appName)
tab:SetTabs(tabs)
tab:SetUserData("tablist", tabs)
for i = 1, #tabs do
local entry = tabs[i]
if not entry.disabled then
tab:SelectTab((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value)
break
end
end
container:AddChild(tab)
elseif grouptype == "select" then
local select = gui:Create("DropdownGroup")
select:SetTitle(name)
InjectInfo(select, options, group, path, rootframe, appName)
select:SetCallback("OnGroupSelected", GroupSelected)
local status = AceConfigDialog:GetStatusTable(appName, path)
if not status.groups then
status.groups = {}
end
select:SetStatusTable(status.groups)
local grouplist, orderlist = BuildSelect(group, options, path, appName)
select:SetGroupList(grouplist, orderlist)
select:SetUserData("grouplist", grouplist)
select:SetUserData("orderlist", orderlist)
local firstgroup = orderlist[1]
if firstgroup then
select:SetGroup((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or firstgroup)
end
select.width = "fill"
select.height = "fill"
container:AddChild(select)
--assume tree group by default
--if parenttype is tree then this group is already a node on that tree
elseif (parenttype ~= "tree") or isRoot then
local tree = gui:Create("TreeGroup")
InjectInfo(tree, options, group, path, rootframe, appName)
tree:EnableButtonTooltips(false)
tree.width = "fill"
tree.height = "fill"
tree:SetCallback("OnGroupSelected", GroupSelected)
tree:SetCallback("OnButtonEnter", TreeOnButtonEnter)
tree:SetCallback("OnButtonLeave", TreeOnButtonLeave)
local status = AceConfigDialog:GetStatusTable(appName, path)
if not status.groups then
status.groups = {}
end
local treedefinition = BuildGroups(group, options, path, appName, true)
tree:SetStatusTable(status.groups)
tree:SetTree(treedefinition)
tree:SetUserData("tree",treedefinition)
for i = 1, #treedefinition do
local entry = treedefinition[i]
if not entry.disabled then
tree:SelectByValue((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value)
break
end
end
container:AddChild(tree)
end
end
end
local old_CloseSpecialWindows
local function RefreshOnUpdate(this)
for appName in pairs(this.closing) do
if AceConfigDialog.OpenFrames[appName] then
AceConfigDialog.OpenFrames[appName]:Hide()
end
if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then
for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do
if not widget:IsVisible() then
widget:ReleaseChildren()
end
end
end
this.closing[appName] = nil
end
if this.closeAll then
for k, v in pairs(AceConfigDialog.OpenFrames) do
if not this.closeAllOverride[k] then
v:Hide()
end
end
this.closeAll = nil
wipe(this.closeAllOverride)
end
for appName in pairs(this.apps) do
if AceConfigDialog.OpenFrames[appName] then
local user = AceConfigDialog.OpenFrames[appName]:GetUserDataTable()
AceConfigDialog:Open(appName, unpack(user.basepath or emptyTbl))
end
if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then
for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do
local user = widget:GetUserDataTable()
if widget:IsVisible() then
AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(user.basepath or emptyTbl))
end
end
end
this.apps[appName] = nil
end
this:SetScript("OnUpdate", nil)
end
-- Upgrade the OnUpdate script as well, if needed.
if AceConfigDialog.frame:GetScript("OnUpdate") then
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate)
end
--- Close all open options windows
function AceConfigDialog:CloseAll()
AceConfigDialog.frame.closeAll = true
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate)
if next(self.OpenFrames) then
return true
end
end
--- Close a specific options window.
-- @param appName The application name as given to `:RegisterOptionsTable()`
function AceConfigDialog:Close(appName)
if self.OpenFrames[appName] then
AceConfigDialog.frame.closing[appName] = true
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate)
return true
end
end
-- Internal -- Called by AceConfigRegistry
function AceConfigDialog:ConfigTableChanged(event, appName)
AceConfigDialog.frame.apps[appName] = true
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate)
end
reg.RegisterCallback(AceConfigDialog, "ConfigTableChange", "ConfigTableChanged")
--- Sets the default size of the options window for a specific application.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param width The default width
-- @param height The default height
function AceConfigDialog:SetDefaultSize(appName, width, height)
local status = AceConfigDialog:GetStatusTable(appName)
if type(width) == "number" and type(height) == "number" then
status.width = width
status.height = height
end
end
--- Open an option window at the specified path (if any).
-- This function can optionally feed the group into a pre-created container
-- instead of creating a new container frame.
-- @paramsig appName [, container][, ...]
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param container An optional container frame to feed the options into
-- @param ... The path to open after creating the options window (see `:SelectGroup` for details)
function AceConfigDialog:Open(appName, container, ...)
if not old_CloseSpecialWindows then
old_CloseSpecialWindows = CloseSpecialWindows
CloseSpecialWindows = function()
local found = old_CloseSpecialWindows()
return self:CloseAll() or found
end
end
local app = reg:GetOptionsTable(appName)
if not app then
error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2)
end
local options = app("dialog", MAJOR)
local f
local path = new()
local name = GetOptionsMemberValue("name", options, options, path, appName)
--If an optional path is specified add it to the path table before feeding the options
--as container is optional as well it may contain the first element of the path
if type(container) == "string" then
tinsert(path, container)
container = nil
end
for n = 1, select("#",...) do
tinsert(path, (select(n, ...)))
end
local option = options
if type(container) == "table" and container.type == "BlizOptionsGroup" and #path > 0 then
for i = 1, #path do
option = options.args[path[i]]
end
name = format("%s - %s", name, GetOptionsMemberValue("name", option, options, path, appName))
end
--if a container is given feed into that
if container then
f = container
f:ReleaseChildren()
f:SetUserData("appName", appName)
f:SetUserData("iscustom", true)
if #path > 0 then
f:SetUserData("basepath", copy(path))
end
local status = AceConfigDialog:GetStatusTable(appName)
if not status.width then
status.width = 700
end
if not status.height then
status.height = 500
end
if f.SetStatusTable then
f:SetStatusTable(status)
end
if f.SetTitle then
f:SetTitle(name or "")
end
else
if not self.OpenFrames[appName] then
f = gui:Create("Frame")
self.OpenFrames[appName] = f
else
f = self.OpenFrames[appName]
end
f:ReleaseChildren()
f:SetCallback("OnClose", FrameOnClose)
f:SetUserData("appName", appName)
if #path > 0 then
f:SetUserData("basepath", copy(path))
end
f:SetTitle(name or "")
local status = AceConfigDialog:GetStatusTable(appName)
f:SetStatusTable(status)
end
self:FeedGroup(appName,options,f,f,path,true)
if f.Show then
f:Show()
end
del(path)
if AceConfigDialog.frame.closeAll then
-- close all is set, but thats not good, since we're just opening here, so force it
AceConfigDialog.frame.closeAllOverride[appName] = true
end
end
-- convert pre-39 BlizOptions structure to the new format
if oldminor and oldminor < 39 and AceConfigDialog.BlizOptions then
local old = AceConfigDialog.BlizOptions
local new = {}
for key, widget in pairs(old) do
local appName = widget:GetUserData("appName")
if not new[appName] then new[appName] = {} end
new[appName][key] = widget
end
AceConfigDialog.BlizOptions = new
else
AceConfigDialog.BlizOptions = AceConfigDialog.BlizOptions or {}
end
local function FeedToBlizPanel(widget, event)
local path = widget:GetUserData("path")
AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(path or emptyTbl))
end
local function ClearBlizPanel(widget, event)
local appName = widget:GetUserData("appName")
AceConfigDialog.frame.closing[appName] = true
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate)
end
--- Add an option table into the Blizzard Interface Options panel.
-- You can optionally supply a descriptive name to use and a parent frame to use,
-- as well as a path in the options table.\\
-- If no name is specified, the appName will be used instead.
--
-- If you specify a proper `parent` (by name), the interface options will generate a
-- tree layout. Note that only one level of children is supported, so the parent always
-- has to be a head-level note.
--
-- This function returns a reference to the container frame registered with the Interface
-- Options. You can use this reference to open the options with the API function
-- `InterfaceOptionsFrame_OpenToCategory`.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param name A descriptive name to display in the options tree (defaults to appName)
-- @param parent The parent to use in the interface options tree.
-- @param ... The path in the options table to feed into the interface options panel.
-- @return The reference to the frame registered into the Interface Options.
function AceConfigDialog:AddToBlizOptions(appName, name, parent, ...)
local BlizOptions = AceConfigDialog.BlizOptions
local key = appName
for n = 1, select("#", ...) do
key = key.."\001"..select(n, ...)
end
if not BlizOptions[appName] then
BlizOptions[appName] = {}
end
if not BlizOptions[appName][key] then
local group = gui:Create("BlizOptionsGroup")
BlizOptions[appName][key] = group
group:SetName(name or appName, parent)
group:SetTitle(name or appName)
group:SetUserData("appName", appName)
if select("#", ...) > 0 then
local path = {}
for n = 1, select("#",...) do
tinsert(path, (select(n, ...)))
end
group:SetUserData("path", path)
end
group:SetCallback("OnShow", FeedToBlizPanel)
group:SetCallback("OnHide", ClearBlizPanel)
InterfaceOptions_AddCategory(group.frame)
return group.frame
else
error(("%s has already been added to the Blizzard Options Window with the given path"):format(appName), 2)
end
end
| gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Labyrinth_of_Onzozo/mobs/Goblin_Shepherd.lua | 3 | 1216 | -----------------------------------
-- Area: Labyrinth of Onzozo
-- MOB: Goblin Shepherd
-- Note: Place holder Soulstealer Skullnix
-----------------------------------
require("scripts/globals/groundsofvalor");
require("scripts/zones/Labyrinth_of_Onzozo/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
checkGoVregime(player,mob,771,2);
checkGoVregime(player,mob,772,2);
checkGoVregime(player,mob,774,2);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
if (Soulstealer_Skullnix_PH[mobID] ~= nil) then
local ToD = GetServerVariable("[POP]Soulstealer_Skullnix");
if (ToD <= os.time() and GetMobAction(Soulstealer_Skullnix) == 0) then
if (math.random(1,20) == 5) then
UpdateNMSpawnPoint(Soulstealer_Skullnix);
GetMobByID(Soulstealer_Skullnix):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Soulstealer_Skullnix", mobID);
DisallowRespawn(mobID, true);
end
end
end
end; | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/zones/Southern_San_dOria/npcs/Esmallegue.lua | 3 | 1528 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Esmallegue
-- General Info NPC
-- @zone 230
-- !pos 0 2 -83
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- player:startEvent(0x37e);-- cavernous maw
player:startEvent(0x0375)
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 |
rafradek/wire | lua/entities/gmod_wire_relay.lua | 10 | 4490 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Relay"
ENT.WireDebugName = "Relay"
ENT.Author = "tad2020"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Value = {} //stores current output value
self.Last = {} //stores last input value for each input
self.Inputs = Wire_CreateInputs(self, { "1A", "2A", "Switch" })
self.Outputs = Wire_CreateOutputs(self, { "A" })
end
function ENT:Setup(keygroup1, keygroup2, keygroup3, keygroup4, keygroup5, keygroupoff, toggle, normclose, poles, throws, nokey)
local outpoles = {"A", "B", "C", "D", "E", "F", "G", "H"} //output names
// Clamp
throws = throws > 10 and 10 or throws
poles = poles > #outpoles and #outpoles or poles
local inputs = {} //wont need this outside setup
self.outputs = {} //need to rebuild output names
self.keygroup1 = keygroup1
self.keygroup2 = keygroup2
self.keygroup3 = keygroup3
self.keygroup4 = keygroup4
self.keygroup5 = keygroup5
self.keygroupoff = keygroupoff
self.toggle = toggle
self.normclose = normclose or 0
self.selinput = normclose or 0
self.poles = poles
self.throws = throws
self.nokey = nokey
//build inputs and putputs, init all nil values
for p=1, self.poles do
self.outputs[p] = outpoles[p]
self.Value[p] = self.Value[p] or 0
for t=1, self.throws do
//inputs[ p * self.poles + t ] = t .. outpoles[p]
table.insert(inputs, ( t .. outpoles[p] ))
self.Last[ t .. outpoles[p] ] = self.Last[ t .. outpoles[p] ] or 0
end
end
//add switch input to end of input list
table.insert(inputs, "Switch")
Wire_AdjustInputs(self, inputs)
Wire_AdjustOutputs(self, self.outputs)
//set the switch to its new normal state
self:Switch( normclose )
if not nokey then
local pl = self:GetPlayer()
if (keygroupoff) then
numpad.OnDown( pl, keygroupoff, "WireRelay_On", self, 0 )
numpad.OnUp( pl, keygroupoff, "WireRelay_Off", self, 0 )
end
if (keygroup1) then
numpad.OnDown( pl, keygroup1, "WireRelay_On", self, 1 )
numpad.OnUp( pl, keygroup1, "WireRelay_Off", self, 1 )
end
if (keygroup2) then
numpad.OnDown( pl, keygroup2, "WireRelay_On", self, 2 )
numpad.OnUp( pl, keygroup2, "WireRelay_Off", self, 2 )
end
if (keygroup3) then
numpad.OnDown( pl, keygroup3, "WireRelay_On", self, 3 )
numpad.OnUp( pl, keygroup3, "WireRelay_Off", self, 3 )
end
if (keygroup4) then
numpad.OnDown( pl, keygroup4, "WireRelay_On", self, 4 )
numpad.OnUp( pl, keygroup4, "WireRelay_Off", self, 4 )
end
if (keygroup5) then
numpad.OnDown( pl, keygroup5, "WireRelay_On", self, 5 )
numpad.OnUp( pl, keygroup5, "WireRelay_Off", self, 5 )
end
end
end
function ENT:TriggerInput(iname, value)
if (iname == "Switch") then
if (math.abs(value) >= 0 && math.abs(value) <= self.throws) then
self:Switch(math.abs(value))
end
elseif (iname) then
self.Last[iname] = value or 0
self:Switch(self.selinput)
end
end
function ENT:Switch( mul )
if (!self:IsValid()) then return false end
self.selinput = mul
for p,v in ipairs(self.outputs) do
self.Value[p] = self.Last[ mul .. v ] or 0
Wire_TriggerOutput(self, v, self.Value[p])
end
self:ShowOutput()
return true
end
function ENT:ShowOutput()
local txt = self.poles .. "P" .. self.throws .. "T "
if (self.selinput == 0) then
txt = txt .. "Sel: off"
else
txt = txt .. "Sel: " .. self.selinput
end
for p,v in ipairs(self.outputs) do
txt = txt .. "\n" .. v .. ": " .. self.Value[p]
end
self:SetOverlayText( txt )
end
function ENT:InputActivate( mul )
if ( self.toggle && self.selinput == mul) then //only toggle for the same key
return self:Switch( self.normclose )
else
return self:Switch( mul )
end
end
function ENT:InputDeactivate( mul )
if ( self.toggle ) then return true end
return self:Switch( self.normclose )
end
local function On( pl, ent, mul )
if (!ent:IsValid()) then return false end
return ent:InputActivate( mul )
end
local function Off( pl, ent, mul )
if (!ent:IsValid()) then return false end
return ent:InputDeactivate( mul )
end
numpad.Register( "WireRelay_On", On )
numpad.Register( "WireRelay_Off", Off )
duplicator.RegisterEntityClass("gmod_wire_relay", WireLib.MakeWireEnt, "Data", "keygroup1", "keygroup2", "keygroup3", "keygroup4", "keygroup5", "keygroupoff", "toggle", "normclose", "poles", "throws", "nokey")
| apache-2.0 |
koppa/wireshark | test/lua/pcre_sets.lua | 35 | 6911 | -- See Copyright Notice in the file lrexlib.h
local luatest = require "luatest"
local N = luatest.NT
local function norm(a) return a==nil and N or a end
local function fill (n, m)
local t = {}
for i = n, m, -1 do table.insert (t, i) end
return t
end
local function set_named_subpatterns (lib, flg)
return {
Name = "Named Subpatterns",
Func = function (subj, methodname, patt, name1, name2)
local r = lib.new (patt)
local _,_,caps = r[methodname] (r, subj)
return norm(caps[name1]), norm(caps[name2])
end,
--{} N.B. subject is always first element
{ {"abcd", "tfind", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
{ {"abcd", "exec", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
}
end
local function set_f_find (lib, flg)
local cp1251 =
"ÀÁÂÃÄŨÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÜÛÚÝÞßàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ"
local loc = "Russian_Russia.1251"
return {
Name = "Function find",
Func = lib.find,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N } }, -- failing st
{ {"abcd", ".*?"}, { 1,0 } }, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, { 1,3 } }, -- cf
{ {"abc", "aBC", N,"i" }, { 1,3 } }, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N } }, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N } }, -- ef
--{ {cp1251, "[[:upper:]]+", N,N,N, loc}, { 1,33} }, -- locale
--{ {cp1251, "[[:lower:]]+", N,N,N, loc}, {34,66} }, -- locale
}
end
local function set_f_match (lib, flg)
return {
Name = "Function match",
Func = lib.match,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N }}, -- failing st
{ {"abcd", ".*?"}, { "" }}, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, {"abc" }}, -- cf
{ {"abc", "aBC", N,"i" }, {"abc" }}, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N }}, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N }}, -- ef
}
end
local function set_f_gmatch (lib, flg)
-- gmatch (s, p, [cf], [ef])
local pCSV = "(^[^,]*)|,([^,]*)"
local F = false
local function test_gmatch (subj, patt)
local out, guard = {}, 10
for a, b in lib.gmatch (subj, patt) do
table.insert (out, { norm(a), norm(b) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function gmatch",
Func = test_gmatch,
--{ subj patt results }
{ {"a\0c", "." }, {{"a",N},{"\0",N},{"c",N}} },--nuls in subj
{ {"", pCSV}, {{"",F}} },
{ {"12", pCSV}, {{"12",F}} },
{ {",", pCSV}, {{"", F},{F,""}} },
{ {"12,,45", pCSV}, {{"12",F},{F,""},{F,"45"}} },
{ {",,12,45,,ab,", pCSV}, {{"",F},{F,""},{F,"12"},{F,"45"},{F,""},{F,"ab"},{F,""}} },
}
end
local function set_f_split (lib, flg)
-- split (s, p, [cf], [ef])
local function test_split (subj, patt)
local out, guard = {}, 10
for a, b, c in lib.split (subj, patt) do
table.insert (out, { norm(a), norm(b), norm(c) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function split",
Func = test_split,
--{ subj patt results }
{ {"a,\0,c", ","}, {{"a",",",N},{"\0",",",N},{"c",N,N}, } },--nuls in subj
{ {"ab", "$"}, {{"ab","",N}, {"",N,N}, } },
{ {"ab", "^|$"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
{ {"ab45ab","(?<=ab).*?"}, {{"ab","",N}, {"45ab","",N},{"",N,N}, } },
{ {"ab", "\\b"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
}
end
local function set_m_exec (lib, flg)
return {
Name = "Method exec",
Method = "exec",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_tfind (lib, flg)
return {
Name = "Method tfind",
Method = "tfind",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_dfa_exec (lib, flg)
return {
Name = "Method dfa_exec",
Method = "dfa_exec",
--{patt,cf,lo}, {subj,st,ef,os,ws} { results }
{ {".+"}, {"abcd"}, {1,{4,3,2,1},4} }, -- [none]
{ {".+"}, {"abcd",2}, {2,{4,3,2}, 3} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,{4,3}, 2} }, -- negative st
{ {".+"}, {"abcd",5}, {N } }, -- failing st
{ {".*"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- [none]
{ {".*?"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,{3},1} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,{3},1} }, -- cf
{ {"bc"}, {"abc"}, {2,{3},1} }, -- [none]
{ {"bc",flg.ANCHORED}, {"abc"}, {N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, {N } }, -- ef
{ { "(.)b.(d)"}, {"abcd"}, {1,{4},1} }, --[captures]
{ {"abc"}, {"ab"}, {N } },
{ {"abc"}, {"ab",N,flg.PARTIAL}, {1,{2},flg.ERROR_PARTIAL} },
{ {".+"}, {string.rep("a",50),N,N,50,50}, {1, fill(50,26), 0}},-- small ovecsize
}
end
return function (libname, isglobal)
local lib = isglobal and _G[libname] or require (libname)
local flags = lib.flags ()
local sets = {
set_f_match (lib, flags),
set_f_find (lib, flags),
set_f_gmatch (lib, flags),
set_f_split (lib, flags),
set_m_exec (lib, flags),
set_m_tfind (lib, flags),
}
if flags.MAJOR >= 4 then
table.insert (sets, set_named_subpatterns (lib, flags))
end
if flags.MAJOR >= 6 then
table.insert (sets, set_m_dfa_exec (lib, flags))
end
return sets
end
| gpl-2.0 |
JunichiWatanuki/wireshark | test/lua/pcre_sets.lua | 35 | 6911 | -- See Copyright Notice in the file lrexlib.h
local luatest = require "luatest"
local N = luatest.NT
local function norm(a) return a==nil and N or a end
local function fill (n, m)
local t = {}
for i = n, m, -1 do table.insert (t, i) end
return t
end
local function set_named_subpatterns (lib, flg)
return {
Name = "Named Subpatterns",
Func = function (subj, methodname, patt, name1, name2)
local r = lib.new (patt)
local _,_,caps = r[methodname] (r, subj)
return norm(caps[name1]), norm(caps[name2])
end,
--{} N.B. subject is always first element
{ {"abcd", "tfind", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
{ {"abcd", "exec", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
}
end
local function set_f_find (lib, flg)
local cp1251 =
"ÀÁÂÃÄŨÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÜÛÚÝÞßàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ"
local loc = "Russian_Russia.1251"
return {
Name = "Function find",
Func = lib.find,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N } }, -- failing st
{ {"abcd", ".*?"}, { 1,0 } }, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, { 1,3 } }, -- cf
{ {"abc", "aBC", N,"i" }, { 1,3 } }, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N } }, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N } }, -- ef
--{ {cp1251, "[[:upper:]]+", N,N,N, loc}, { 1,33} }, -- locale
--{ {cp1251, "[[:lower:]]+", N,N,N, loc}, {34,66} }, -- locale
}
end
local function set_f_match (lib, flg)
return {
Name = "Function match",
Func = lib.match,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N }}, -- failing st
{ {"abcd", ".*?"}, { "" }}, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, {"abc" }}, -- cf
{ {"abc", "aBC", N,"i" }, {"abc" }}, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N }}, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N }}, -- ef
}
end
local function set_f_gmatch (lib, flg)
-- gmatch (s, p, [cf], [ef])
local pCSV = "(^[^,]*)|,([^,]*)"
local F = false
local function test_gmatch (subj, patt)
local out, guard = {}, 10
for a, b in lib.gmatch (subj, patt) do
table.insert (out, { norm(a), norm(b) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function gmatch",
Func = test_gmatch,
--{ subj patt results }
{ {"a\0c", "." }, {{"a",N},{"\0",N},{"c",N}} },--nuls in subj
{ {"", pCSV}, {{"",F}} },
{ {"12", pCSV}, {{"12",F}} },
{ {",", pCSV}, {{"", F},{F,""}} },
{ {"12,,45", pCSV}, {{"12",F},{F,""},{F,"45"}} },
{ {",,12,45,,ab,", pCSV}, {{"",F},{F,""},{F,"12"},{F,"45"},{F,""},{F,"ab"},{F,""}} },
}
end
local function set_f_split (lib, flg)
-- split (s, p, [cf], [ef])
local function test_split (subj, patt)
local out, guard = {}, 10
for a, b, c in lib.split (subj, patt) do
table.insert (out, { norm(a), norm(b), norm(c) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function split",
Func = test_split,
--{ subj patt results }
{ {"a,\0,c", ","}, {{"a",",",N},{"\0",",",N},{"c",N,N}, } },--nuls in subj
{ {"ab", "$"}, {{"ab","",N}, {"",N,N}, } },
{ {"ab", "^|$"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
{ {"ab45ab","(?<=ab).*?"}, {{"ab","",N}, {"45ab","",N},{"",N,N}, } },
{ {"ab", "\\b"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
}
end
local function set_m_exec (lib, flg)
return {
Name = "Method exec",
Method = "exec",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_tfind (lib, flg)
return {
Name = "Method tfind",
Method = "tfind",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_dfa_exec (lib, flg)
return {
Name = "Method dfa_exec",
Method = "dfa_exec",
--{patt,cf,lo}, {subj,st,ef,os,ws} { results }
{ {".+"}, {"abcd"}, {1,{4,3,2,1},4} }, -- [none]
{ {".+"}, {"abcd",2}, {2,{4,3,2}, 3} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,{4,3}, 2} }, -- negative st
{ {".+"}, {"abcd",5}, {N } }, -- failing st
{ {".*"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- [none]
{ {".*?"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,{3},1} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,{3},1} }, -- cf
{ {"bc"}, {"abc"}, {2,{3},1} }, -- [none]
{ {"bc",flg.ANCHORED}, {"abc"}, {N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, {N } }, -- ef
{ { "(.)b.(d)"}, {"abcd"}, {1,{4},1} }, --[captures]
{ {"abc"}, {"ab"}, {N } },
{ {"abc"}, {"ab",N,flg.PARTIAL}, {1,{2},flg.ERROR_PARTIAL} },
{ {".+"}, {string.rep("a",50),N,N,50,50}, {1, fill(50,26), 0}},-- small ovecsize
}
end
return function (libname, isglobal)
local lib = isglobal and _G[libname] or require (libname)
local flags = lib.flags ()
local sets = {
set_f_match (lib, flags),
set_f_find (lib, flags),
set_f_gmatch (lib, flags),
set_f_split (lib, flags),
set_m_exec (lib, flags),
set_m_tfind (lib, flags),
}
if flags.MAJOR >= 4 then
table.insert (sets, set_named_subpatterns (lib, flags))
end
if flags.MAJOR >= 6 then
table.insert (sets, set_m_dfa_exec (lib, flags))
end
return sets
end
| gpl-2.0 |
TheRikyHUN/fooniks | resources/admin/client/gui/admin_report.lua | 2 | 4590 | --[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* gui\admin_report.lua
*
* Original File by lil_Toady
*
**************************************]]
aReportForm = nil
function aReport ( player )
if ( aReportForm == nil ) then
local x, y = guiGetScreenSize()
aReportForm = guiCreateWindow ( x / 2 - 150, y / 2 - 150, 300, 300, "Kontakteeru Adminiga", false )
guiCreateLabel ( 0.05, 0.11, 0.20, 0.09, "Kategooria:", true, aReportForm )
guiCreateLabel ( 0.05, 0.21, 0.20, 0.09, "Teema:", true, aReportForm )
guiCreateLabel ( 0.05, 0.30, 0.20, 0.07, "Kirjeldus:", true, aReportForm )
aReportCategory = guiCreateEdit ( 0.30, 0.10, 0.65, 0.09, "Kysimus", true, aReportForm )
guiEditSetReadOnly ( aReportCategory, true )
aReportDropDown = guiCreateStaticImage ( 0.86, 0.10, 0.09, 0.09, "client\\images\\dropdown.png", true, aReportForm )
guiBringToFront ( aReportDropDown )
aReportCategories = guiCreateGridList ( 0.30, 0.10, 0.65, 0.30, true, aReportForm )
guiGridListAddColumn( aReportCategories, "", 0.85 )
guiSetVisible ( aReportCategories, false )
guiGridListSetItemText ( aReportCategories, guiGridListAddRow ( aReportCategories ), 1, "Kysimus", false, false )
guiGridListSetItemText ( aReportCategories, guiGridListAddRow ( aReportCategories ), 1, "Viga Serveris", false, false )
guiGridListSetItemText ( aReportCategories, guiGridListAddRow ( aReportCategories ), 1, "Cheater/Hacker", false, false )
guiGridListSetItemText ( aReportCategories, guiGridListAddRow ( aReportCategories ), 1, "Ettepanek", false, false )
guiGridListSetItemText ( aReportCategories, guiGridListAddRow ( aReportCategories ), 1, "Muu", false, false )
aReportSubject = guiCreateEdit ( 0.30, 0.20, 0.65, 0.09, "", true, aReportForm )
aReportMessage = guiCreateMemo ( 0.05, 0.38, 0.90, 0.45, "", true, aReportForm )
aReportAccept = guiCreateButton ( 0.40, 0.88, 0.25, 0.09, "Saada", true, aReportForm )
aReportCancel = guiCreateButton ( 0.70, 0.88, 0.25, 0.09, "Katkesta", true, aReportForm )
addEventHandler ( "onClientGUIClick", aReportForm, aClientReportClick )
addEventHandler ( "onClientGUIDoubleClick", aReportForm, aClientReportDoubleClick )
end
guiBringToFront ( aReportForm )
showCursor ( true )
end
addCommandHandler ( "report", aReport )
addCommandHandler ( "teata", aReport )
bindKey("F2", "down", function( ) aReport( getLocalPlayer( ) ); end );
function aReportClose ( )
guiSetInputEnabled ( false )
if ( aReportForm ) then
removeEventHandler ( "onClientGUIClick", aReportForm, aClientReportClick )
removeEventHandler ( "onClientGUIDoubleClick", aReportForm, aClientReportDoubleClick )
destroyElement ( aReportForm )
aReportForm = nil
showCursor ( false )
end
end
function aClientReportDoubleClick ( button )
if ( button == "left" ) then
if ( source == aReportCategories ) then
if ( guiGridListGetSelectedItem ( aReportCategories ) ~= -1 ) then
local cat = guiGridListGetItemText ( aReportCategories, guiGridListGetSelectedItem ( aReportCategories ), 1 )
guiSetText ( aReportCategory, cat )
guiSetVisible ( aReportCategories, false )
end
end
end
end
function aClientReportClick ( button )
if ( source == aReportCategory ) then
guiBringToFront ( aReportDropDown )
end
if ( source ~= aReportCategories ) then
guiSetVisible ( aReportCategories, false )
end
if ( button == "left" ) then
if ( source == aReportAccept ) then
if ( ( string.len ( guiGetText ( aReportSubject ) ) < 1 ) or ( string.len ( guiGetText ( aReportMessage ) ) < 5 ) ) then
aMessageBox ( "error", "Subject/Message missing." )
else
aMessageBox ( "info", "Your message has been submited and will be processed as soon as possible." )
setTimer ( aMessageBoxClose, 3000, 1, true )
local tableOut = {}
tableOut.category = guiGetText ( aReportCategory )
tableOut.subject = guiGetText ( aReportSubject )
tableOut.message = guiGetText ( aReportMessage )
triggerServerEvent ( "aMessage", getLocalPlayer(), "new", tableOut )
aReportClose ()
end
elseif ( source == aReportSubject ) then
guiSetInputEnabled ( true )
elseif ( source == aReportMessage ) then
guiSetInputEnabled ( true )
elseif ( source == aReportCancel ) then
aReportClose ()
elseif ( source == aReportDropDown ) then
guiBringToFront ( aReportCategories )
guiSetVisible ( aReportCategories, true )
end
end
end | gpl-3.0 |
RebootRevival/FFXI_Test | scripts/globals/items/bibiki_slug.lua | 12 | 1424 | -----------------------------------------
-- ID: 5122
-- Item: Bibiki Slug
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 4
-- defense % 16
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5122);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_DEFP, 16);
end;
| gpl-3.0 |
ahm3d97/Th3_BOOS | plugins/map.lua | 2 | 1855 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY Th3_BOOS ▀▄ ▄▀
▀▄ ▄▀ BY Th3_BOOS (@Th3_BOOS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY Th3_BOOS ▀▄ ▄▀
▀▄ ▄▀ map : طقس ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Get Man Location by Name",
usage = "/خريطه (name) : get map and location",
patterns = {"^خريطه (.*)$"},
run = run
}
end
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/North_Gustaberg/npcs/Cavernous_Maw_2.lua | 3 | 1882 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Cavernous Maw
-- !pos -78 -0.5 600 106
-- Teleports Players to Abyssea - Grauberg
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/abyssea");
require("scripts/zones/North_Gustaberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then
local HasStone = getTravStonesTotal(player);
if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED
and player:getQuestStatus(ABYSSEA, AN_ULCEROUS_URAGNITE) == QUEST_AVAILABLE) then
player:startEvent(0);
else
player:startEvent(908,0,1); -- No param = no entry.
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- print("CSID:",csid);
-- print("RESULT:",option);
if (csid == 0) then
player:addQuest(ABYSSEA, AN_ULCEROUS_URAGNITE);
elseif (csid == 1) then
-- Killed Amphitrite
elseif (csid == 908 and option == 1) then
player:setPos(-555,31,-760,0,254);
end
end; | gpl-3.0 |
mahdib9/mahk | bot/xamarin.lua | 3 | 13667 | 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/utilsLUA")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
-- local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"welcome",
"admin",
"addsudo",
"inrealm",
"ingroup",
"inpm",
"info",
"banhammer",
"stats",
"anti_spam",
"xamar",
"lock_join",
"lock_link",
"lock_tag",
"lock_eng",
"lock_badword",
"arabic_lock",
"owners",
"set",
"get",
"broadcast",
"download_media",
"invite",
"leave_ban",
"spammer",
"salam",
"fosh",
"wiki",
"echo",
"feedback",
"qr",
"joke",
"tex",
"calc",
"tosupport",
"google",
"weather",
"addplug",
"getplug",
"plugins",
"all",
},
sudo_users = {119626024,0,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[⚡️ Xamarin Anti Spam Bot v1.7
📢 Channel : @DarkTeam
👤 Admin : @AmirDark
🙏 Special Thanks to :
@PokerFace_Dev
@ShahabDark
@MR_Flat
@SinAw1
📝 Please send your feedback
The command /feedback [text]
Checkout yeo.ir/Xamarin
]],
help_text_realm = [[
📝 لیست دستورات Realm :
✏️ ساخت یک گروه جدید
!creategroup [نام گروه]
🖍 ساخت یک گروه Realm جدید
!createrealm [نام گروه]
✏️ تغییر نام گروه Realm
!setname [نام مورد نظر]
🏳 تغییر توضیحات یک گروه
!setabout [کد گروه] [متن]
🏳 تغییر قوانین یک گروه
!setrules [کد گروه] [متن]
🏳 قفل تنظیمات یک گروه
!lock [کد گروه] [bots|name...]
🏳 باز کردن قفل تنظیمات یک گروه
!unlock [کد گروه] [bots|name...]
📝 مشاهده نوع گروه (گروه یا Realm)
!type
📝 دریافت لیست کاربران (متن)
!wholist
📝 دریافت لیست کاربران (فایل)
!who
🚫 حذف کاربران و پاک کردن گروه
!kill chat [کد گروه]
🚫 حذف کاربران و پاک کردن Realm
!kill realm [کد ریالیم]
👥 افزودن ادمین به ربات
!addadmin [نام کاربری|یوزر آی دی]
👥 حذف کردن ادمین از ربات
!removeadmin [نام کاربری|یوزر آی دی]
🌐 دریافت لیست گروه ها
!list groups
🌐 دریافت لیست Realm ها
!list realms
🗯 دریافت لاگ Realm
!log
📢 ارسال پیام به همه گروه ها
!broadcast [متن پیام]
📢 ارسال پیام به یک گروه خاص
!bc [کد گروه] [متن پیام]
🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹
⚠️ شما ميتوانيد از ! و / استفاده کنيد.
⚠️ تنها مدیران ربات و سودو ها
میتوانند جزییات مدیریتی سایر گروه
های ربات را ویرایش یا حذف نمایند.
⚠️ تنها سودو ربات میتواند
گروهی را بسازد یا حذف کند.
🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹
]],
help_text = [[
📝 ليست دستورات مدیریت گروه :
🚫 حذف کردن کاربر
!kick [یوزنیم/یوزر آی دی]
🚫 کردن کاربر ( حذف برای همیشه )
!ban [یوزنیم/یوزر آی دی]
🚫 حذف بن کاربر ( آن بن )
!unban [یوزر آی دی]
🚫 حذف خودتان از گروه
!kickme
🚫 حذف کاربران غیر فعال
!kickinactive
👥 دريافت ليست مديران گروه
!modlist
👥 افزودن یک مدیر به گروه
!promote [یوزنیم]
👥 حذف کردن یک مدير
!demote [یوزنیم]
📃 توضيحات گروه
!about
📜 قوانين گروه
!rules
🌅 انتخاب و قفل عکس گروه
!setphoto
🔖 انتخاب نام گروه
!setname [نام مورد نظر]
📜 انتخاب قوانين گروه
!set rules [متن قوانین]
📃 انتخاب توضيحات گروه
!set about [متن مورد نظر]
🔒 قفل اعضا ، نام گروه ، ربات و ...
!lock [member|name|bots|tag|adds|badw|join|arabic|eng|sticker|leave]
🔓 باز کردن قفل اعضا ، نام گروه و ...
!unlock [member|name|bots|tag|adds|badw|join|arabic|eng|sticker|leave]
📥 دريافت یوزر آی دی گروه يا کاربر
!id
📥 دریافت اطلاعات کاربری و مقام
!info
⚙ دریافت تنظیمات گروه
!settings
📌 ساخت / تغيير لينک گروه
!newlink
📌 دريافت لينک گروه
!link
📌 دريافت لينک گروه در پی وی
!linkpv
🛃 انتخاب مالک گروه
!setowner [یوزر آی دی]
🔢 تغيير حساسيت ضد اسپم
!setflood [5-20]
✅ دريافت ليست اعضا گروه
!who
✅ دريافت آمار در قالب متن
!stats
〽️ سيو کردن يک متن
!save [value] <text>
〽️ دريافت متن سيو شده
!get [value]
❌ حذف قوانين ، مديران ، اعضا و ...
!clean [modlist|rules|about]
♻️ دريافت يوزر آی دی یک کاربر
!res [یوزنیم]
🚸 دريافت گزارشات گروه
!log
🚸 دريافت ليست کاربران بن شده
!banlist
🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹
📝 ليست دستورات ابزار ها :
😂 ارسال جک های خفن
!joke
🌀 تکرار متن مورد نظر شما
!echo [متن]
🎤 فعال کردن قابلیت چت با ربات
!plugins + chat group
🎤 غیر فعال کردن قابلیت چت با ربات
!plugins - chat group
📝 فعال کردن پیام خوش آمد گویی
!plugins + welcome group
📝 غیر فعال کردن پیام خوش آمد گویی
!plugins - welcome group
🃏 ساخت عکس نوشته
!tex [متن]
🃏 ساخت بارکد QR
!qr [متن]
⌨ انجام محاسبات ریاضی
!calc 2+8
🌐 جستجو در ویکی پديا انگلیسی
!wiki [متن]
🌐 جستجو در ویکی پديا فارسی
!wikifa [متن]
🌐 جستجو در گوگل
!google [متن]
☀️ هواشناسی و وضعیت هوا
!weather [نام شهر]
📢 ارتباط با پشتیبانی ربات
!feedback [متن پیام]
🔍 دریافت لینک گروه پشتیبانی
!tosupport
👤 اضافه کردن ادمین ربات به گروه
!addsudo
💬 توضيحات ضد اسپم
!xamarin
💬 راهنمای ربات (همین متن)
!help
🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹
⚠️ هرگونه سوال یا مشکل در ربات
را از طریق دستور فیدبک برای مدیران
ربات ارسال و منتظر جواب باشید.
⚠️ شما ميتوانيد از ! و / استفاده کنيد.
⚠️ تنها مديران ميتوانند ربات ادد کنند.
⚠️ تنها معاونان و مديران ميتوانند
جزييات مديريتی گروه را تغيير دهند.
🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
RebootRevival/FFXI_Test | scripts/globals/mobskills/chains_of_rage.lua | 1 | 1302 | ---------------------------------------------
-- Chains of Rage
--
---------------------------------------------
package.loaded["scripts/zones/Empyreal_Paradox/TextIDs"] = nil;
---------------------------------------------
require("scripts/zones/Empyreal_Paradox/TextIDs");
require("scripts/globals/monstertpmoves");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/msg");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local targets = mob:getEnmityList();
for i,v in pairs(targets) do
if (v:isPC()) then
local race = v:getRace()
if (race == 8) and not v:hasKeyItem(LIGHT_OF_ALTAIEU) then
mob:showText(mob, PROMATHIA_TEXT + 4);
return 0;
end
end
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_TERROR;
local power = 30;
local duration = 30;
if target:isPC() and ((target:getRace() == 8) and not target:hasKeyItem(LIGHT_OF_ALTAIEU)) then
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration));
else
skill:setMsg(msgBasic.NO_EFFECT);
end
return typeEffect;
end;
| gpl-3.0 |
jthomasbarry/aafmt | archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/layered/NodeRankingGansnerKNV1993.lua | 3 | 3598 | -- Copyright 2011 by Jannis Pohlmann
--
-- This file may be distributed and/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/layered/NodeRankingGansnerKNV1993.lua,v 1.1 2012/11/27 17:24:26 tantau Exp $
local NodeRankingGansnerKNV1993 = {}
-- Imports
local Edge = require "pgf.gd.deprecated.Edge"
local Node = require "pgf.gd.deprecated.Node"
local NetworkSimplex = require "pgf.gd.layered.NetworkSimplex"
function NodeRankingGansnerKNV1993:run()
local simplex = NetworkSimplex.new(self.graph, NetworkSimplex.BALANCE_TOP_BOTTOM)
simplex:run()
self.ranking = simplex.ranking
return simplex.ranking
end
function NodeRankingGansnerKNV1993:mergeClusters()
self.cluster_nodes = {}
self.cluster_node = {}
self.cluster_edges = {}
self.original_nodes = {}
self.original_edges = {}
for _,cluster in ipairs(self.graph.clusters) do
local cluster_node = Node.new{
name = 'cluster@' .. cluster.name,
}
table.insert(self.cluster_nodes, cluster_node)
for _,node in ipairs(cluster.nodes) do
self.cluster_node[node] = cluster_node
table.insert(self.original_nodes, node)
end
self.graph:addNode(cluster_node)
end
for _,edge in ipairs(self.graph.edges) do
local tail = edge:getTail()
local head = edge:getHead()
if self.cluster_node[tail] or self.cluster_node[head] then
table.insert(self.original_edges, edge)
local cluster_edge = Edge.new{
direction = Edge.RIGHT,
weight = edge.weight,
minimum_levels = edge.minimum_levels,
}
table.insert(self.cluster_edges, cluster_edge)
if self.cluster_node[tail] then
cluster_edge:addNode(self.cluster_node[tail])
else
cluster_edge:addNode(tail)
end
if self.cluster_node[head] then
cluster_edge:addNode(self.cluster_node[head])
else
cluster_edge:addNode(head)
end
end
end
for _,edge in ipairs(self.cluster_edges) do
self.graph:addEdge(edge)
end
for _,edge in ipairs(self.original_edges) do
self.graph:deleteEdge(edge)
end
for _,node in ipairs(self.original_nodes) do
self.graph:deleteNode(node)
end
end
function NodeRankingGansnerKNV1993:createClusterEdges()
for n = 1, #self.cluster_nodes-1 do
local first_cluster = self.cluster_nodes[n]
local second_cluster = self.cluster_nodes[n+1]
local edge = Edge.new{
direction = Edge.RIGHT,
weight = 1,
minimum_levels = 1,
}
edge:addNode(first_cluster)
edge:addNode(second_cluster)
self.graph:addEdge(edge)
table.insert(self.cluster_edges, edge)
end
end
function NodeRankingGansnerKNV1993:removeClusterEdges()
end
function NodeRankingGansnerKNV1993:expandClusters()
for _,node in ipairs(self.original_nodes) do
assert(self.ranking:getRank(self.cluster_node[node]))
self.ranking:setRank(node, self.ranking:getRank(self.cluster_node[node]))
self.graph:addNode(node)
end
for _,edge in ipairs(self.original_edges) do
for _,node in ipairs(edge.nodes) do
node:addEdge(edge)
end
self.graph:addEdge(edge)
end
for _,node in ipairs(self.cluster_nodes) do
self.ranking:setRank(node, nil)
self.graph:deleteNode(node)
end
for _,edge in ipairs(self.cluster_edges) do
self.graph:deleteEdge(edge)
end
end
-- done
return NodeRankingGansnerKNV1993 | gpl-2.0 |
RebootRevival/FFXI_Test | scripts/zones/Aht_Urhgan_Whitegate/npcs/Yafaaf.lua | 3 | 1094 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Yafaaf
-- Type: Standard Merchant
-- !pos 76.889 -7 -140.379 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, YAFAAF_SHOP_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
tommo/mock | mock/common/EntityGUID.lua | 1 | 1808 | module 'mock'
local generateGUID = MOAIEnvironment.generateGUID
--------------------------------------------------------------------
local function affirmGUID( entity )
if not entity.__guid then
entity.__guid = generateGUID()
end
for com in pairs( entity.components ) do
if not com.__guid then
com.__guid = generateGUID()
end
end
for child in pairs( entity.children ) do
affirmGUID( child )
end
end
local function affirmSceneGroupGUID( group )
if not group.__guid then
group.__guid = generateGUID()
end
for childGroup in pairs( group.childGroups ) do
affirmSceneGroupGUID( childGroup )
end
end
local function affirmSceneGUID( scene )
--affirm entity guid
for entity in pairs( scene.entities ) do
affirmGUID( entity )
end
--affirm group guid
for i, rootGroup in ipairs( scene.rootGroups ) do
affirmSceneGroupGUID( rootGroup )
end
end
local function _reallocObjectGUID( obj, replaceMap )
local id0 = obj.__guid
local id1
if not id0 then
id1 = generateGUID()
else
local base, ns = id0:match( '(.*:)(%w+)$' )
if not ns then
id1 = generateGUID()
replaceMap[ id0 ] = id1
else
local ns1 = replaceMap[ ns ]
if ns1 then
id1 = base .. ns1
replaceMap[ id0 ] = id1
else
_error("???????")
return
end
end
end
obj.__guid = id1
return id0, id1
end
local function reallocGUID( entity, replaceMap )
replaceMap = replaceMap or {}
local id0, id1 = _reallocObjectGUID( entity, replaceMap )
for child in pairs( entity.children ) do
reallocGUID( child, replaceMap )
end
for com in pairs( entity.components ) do
_reallocObjectGUID( com, replaceMap )
end
end
--------------------------------------------------------------------
_M.affirmGUID = affirmGUID
_M.affirmSceneGUID = affirmSceneGUID
_M.reallocGUID = reallocGUID | mit |
kengonakajima/lua-msgpack-native | test.lua | 1 | 13387 | -- Load our native module
local mp = require("./msgpack")
local io = require("io")
local string = require("string")
local table = require("table")
local math = require("math")
math.randomseed(1)
function display(m,x)
local _t = type(x)
io.stdout:write(string.format("\n%s: %s ",m,_t))
if _t == "table" then print(x) end
end
function printf(p,...)
io.stdout:write(string.format(p,...)); io.stdout:flush()
end
function simpledump(s)
local out=""
for i=1,string.len(s) do
out = out .. " " .. string.format( "%x", string.byte(s,i) )
end
print(out)
end
-- copy(right) from penlight tablex module! for test in MOAI environment.
function deepcompare(t1,t2,ignore_mt,eps)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' then
if ty1 == 'number' and eps then return abs(t1-t2) < eps end
return t1 == t2
end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(t1)
if not ignore_mt and mt and mt.__eq then return t1 == t2 end
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or not deepcompare(v1,v2,ignore_mt,eps) then return false end
end
for k2,v2 in pairs(t2) do
local v1 = t1[k2]
if v1 == nil or not deepcompare(v1,v2,ignore_mt,eps) then return false end
end
return true
end
function streamtest(unp,t,dolog)
local s = mp.pack(t)
if dolog and #s < 1000 then simpledump(s) end
local startat = 1
while true do
local unit = 1+math.floor( math.random(0, #s/10 ) )
local subs = string.sub( s, startat, startat+unit-1 )
if subs and #subs > 0 then
unp:feed( subs )
startat = startat + unit
else
break
end
end
local out = unp:pull()
if t ~= nil and t ~= false then
assert(out, "no result")
end
local res = deepcompare(out,t)
assert(res,"table differ")
out = unp:pull()
assert(not out,"have to be nil")
end
local msgpack_cases = {
false,true,nil,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1,127,127,255,65535,
4294967295,-32,-32,-128,-32768,-2147483648, 0.0,-0.0,1.0,-1.0,
"a","a","a","","","",
{0},{0},{0},{},{},{},{},{},{},{a=97},{a=97},{a=97},{{}},{{"a"}},
}
-- quick test
local origt = {{"multi","level",{"lists","used",45,{{"trees"}}},"work",{}},"too"}
local sss = mp.pack(origt)
local l,t = mp.unpack(sss)
assert(#t == #origt)
assert(t[1][1]=="multi")
assert(t[1][2]=="level")
assert(t[1][3][1]=="lists")
assert(t[1][3][2]=="used")
assert(t[1][3][3]==45)
assert(t[1][3][4][1][1]=="trees")
assert(t[1][4]=="work")
assert(t[1][5][1]==nil)
assert(t[2]=="too")
-- streaming API test
unp = mp.createUnpacker(1024*1024)
-- stream raw test
streamtest(unp,{ hoge = { 5,6 }, fug="11" },true)
streamtest(unp,"a")
streamtest(unp,"aaaaaaaaaaaaaaaaa")
--streaming: basic test
print("stream basic test")
t = { aho=7, hoge = { 5,6,"7", {8,9,10} }, fuga="11" }
sss = mp.pack(t)
assert(unp)
unp:feed( string.char( 0x83, 0xa3, 0x61, 0x68 ) )
unp:feed( string.char( 0x6f, 0x7, 0xa4, 0x66 ) )
unp:feed( string.char( 0x75, 0x67, 0x61, 0xa2 ) )
unp:feed( string.char( 0x31, 0x31, 0xa4, 0x68 ) )
unp:feed( string.char( 0x6f, 0x67, 0x65, 0x94 ) )
unp:feed( string.char( 0x5, 0x6, 0xa1, 0x37 ) )
unp:feed( string.char( 0x93, 0x8, 0x9, 0xa ) )
out = unp:pull()
assert( out )
assert( deepcompare(t,out) )
assert( not unp:pull() )
--streaming: empty table
print("stream empty containers" )
streamtest(unp,{})
streamtest(unp,"")
-- streaming: types
print("stream types test")
t = {}
for i=1,70000 do table.insert( t, "a" ) end -- raw32
streamtest( unp, { table.concat( t ) } )
t = {}
for i=1,100 do table.insert( t, "a" ) end -- raw16
streamtest( unp, { table.concat( t ) } )
t = {}
for i=1,70000 do t[ "key" .. i ] = i end -- map32
streamtest( unp, t )
t = {}
for i=1,100 do t[ "key" .. i ] = i end -- map16
streamtest( unp, t )
t = {}
for i=1,70000 do table.insert(t,1) end -- ary32
streamtest( unp, t )
t = {}
for i=1,100 do table.insert(t,i) end -- ary16
streamtest( unp, t )
streamtest( unp, {0.001}) -- double
streamtest( unp, {-10000000000000000}) -- i64
streamtest( unp, {-1000000000000000}) -- i64
streamtest( unp, {-100000000000000}) -- i64
streamtest( unp, {-10000000000000}) -- i64
streamtest( unp, {-1000000000000}) -- i64
streamtest( unp, {-100000000000}) -- i64
streamtest( unp, {-10000000000}) -- i64
streamtest( unp, {-1000000000}) -- i32
streamtest( unp, {-100000000}) -- i32
streamtest( unp, {-10000000}) -- i32
streamtest( unp, {-1000000}) -- i32
streamtest( unp, {-100000}) -- i32
streamtest( unp, {-10000}) -- i16
streamtest( unp, {-1000}) -- i16
streamtest( unp, {-100}) -- i8
streamtest( unp, {-10}) -- neg fixnum
streamtest( unp, {-1}) -- neg fixnum
streamtest( unp, { 1000000000000000000 }) -- u64
streamtest( unp, { 100000000000000000 }) -- u64
streamtest( unp, { 10000000000000000 }) -- u64
streamtest( unp, { 1000000000000000 }) -- u64
streamtest( unp, { 100000000000000 }) -- u64
streamtest( unp, { 10000000000000 }) -- u64
streamtest( unp, { 1000000000000 }) -- u64
streamtest( unp, { 100000000000 }) -- u64
streamtest( unp, { 10000000000 }) -- u64
streamtest( unp, { 1000000000 }) -- u32
streamtest( unp, { 100000000 }) -- u32
streamtest( unp, { 10000000 }) -- u32
streamtest( unp, { 1000000 }) -- u32
streamtest( unp, { 100000 }) -- u32
streamtest( unp, { 10000 }) -- u16
streamtest( unp, { 1000 }) -- u16
streamtest( unp, { 1,10,100 }) -- u8
-- streaming: multiple tables
print("stream multiple tables")
t1 = {10,20,30}
s1 = mp.pack(t1)
t2 = {"aaa","bbb","ccc"}
s2 = mp.pack(t2)
t3 = {a=1,b=2,c=3}
s3 = mp.pack(t3)
sss = s1 .. s2 .. s3
assert( #sss == (#s1 + #s2 + #s3 ) )
unp:feed(s1)
unp:feed(s2)
out1 = unp:pull()
assert(out1)
assert( deepcompare(t1,out1))
out2 = unp:pull()
assert(out2)
assert( deepcompare(t2,out2))
out3 = unp:pull()
assert( not out3 )
unp:feed(s3)
out3 = unp:pull()
assert( deepcompare(t3,out3))
out4 = unp:pull()
assert( not out4 )
-- stream: gc test
print("stream gc test")
t = { aho=7, hoge = { 5,6,"7", {8,9,10} }, fuga="11" }
s = mp.pack(t)
for i=1,100000 do
local u = mp.createUnpacker(1024)
u:feed( string.sub(s,1,11))
u:feed( string.sub(s,12,#s))
local out = u:pull()
assert(out)
out = u:pull()
assert(not out)
end
-- stream: find corrupt data
print("stream corrupt input")
s = string.char( 0x91, 0xc1 ) -- c1: reserved code
local uc = mp.createUnpacker(1024)
local res = uc:feed(s)
assert( res == -1 )
-- stream: too deep
print("stream too deep")
t={}
for i=1,2000 do
table.insert(t, 0x91 )
end
s = string.char( unpack(t) )
uc = mp.createUnpacker(1024*1024)
res = uc:feed(s)
assert(res==-1)
-- normal test
print("simple table")
sss = mp.pack({1,2,3})
l,t = mp.unpack(sss)
assert(t[1]==1)
assert(t[2]==2)
assert(t[3]==3)
assert(t[4]==nil)
sss = mp.pack({a=1,b=2,c=3})
l,t = mp.unpack(sss)
assert(t.a==1)
assert(t.b==2)
assert(t.c==3)
assert(t.d==nil)
simpledump(sss)
-- number edge test
function isnan(n)
return n ~= n
end
print("nan")
packed = mp.pack( 0/0 )
assert( packed == string.char( 0xcb, 0xff, 0xf8, 0,0,0,0,0,0 ) )
l,unpacked = mp.unpack(packed)
assert( isnan( unpacked ) )
print("+inf")
packed = mp.pack(1/0)
assert( packed == string.char( 0xcb, 0x7f, 0xf0, 0,0,0,0,0,0 ) )
l,unpacked = mp.unpack(packed)
assert( unpacked == 1/0 )
print("-inf")
packed = mp.pack(-1/0)
assert( packed == string.char( 0xcb, 0xff, 0xf0, 0,0,0,0,0,0 ) )
l,unpacked = mp.unpack(packed)
assert( unpacked == -1/0)
-- misc data
local data = {
nil,
true,
false,
1,
-1,
-2,
-5,
-31,
-32,
-128, -- 10
-32768,
-2147483648,
-2147483648*100,
127,
255, --15
65535,
4294967295,
4294967295*100,
42,
-42, -- 20
0.79,
"Hello world!",
{},
{1,2,3},
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18}, -- 25
{a=1,b=2},
{a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10,k=11,l=12,m=13,n=14,o=15,p=16,q=17,r=18},
{true,false,42,-42,0.79,"Hello","World!"}, -- 28
{{"multi","level",{"lists","used",45,{{"trees"}}},"work",{}},"too"},
{foo="bar",spam="eggs"}, -- 30
{nested={maps={"work","too"}}},
{"we","can",{"mix","integer"},{keys="and"},{2,{maps="as well"}}}, -- 32
msgpack_cases,
}
local offset,res
-- Custom tests
print("Custom tests")
for i=1,#data do -- 0 tests nil!
printf("%d ", i )
offset,res = mp.unpack(mp.pack(data[i]))
assert(offset,"decoding failed")
if not deepcompare(res,data[i]) then
display("expected type:",data[i])
display("found type:",res)
print( "found value:", res)
assert(false,string.format("wrong value in case %d",i))
end
end
print(" OK")
-- on streaming
for i=1,#data do
printf("%d ",i)
streamtest(unp, data[i])
end
-- Corrupt data test
print("corrupt data test")
local s = mp.pack(data)
local corrupt_tail = string.sub( s, 1, 10 )
offset,res = mp.unpack(s)
assert(offset)
offset,res = mp.unpack(corrupt_tail)
assert(not offset)
-- error bits test
local res,msg = pcall( function() mp.pack( { a=function() end } ) end )
assert( not res )
assert( msg == "invalid type: function" )
-- Empty data test
print("empty test")
local offset,res = mp.unpack(mp.pack({}))
assert(offset==1)
assert(res[1]==nil)
print("MessagePack test suite")
local files = { "./cases.mpac", "./cases_compact.mpac" }
for i,v in pairs(files) do
print( "test on ", v )
local f = io.open(v,'rb')
assert(f)
local bindata = f:read("*all")
print("file len:", string.len(bindata))
f:close()
--
local offset,i = 0,0
while true do
i = i+1
printf("%d ", i)
if i==#msgpack_cases then break end
local rlen,res = mp.unpack(string.sub(bindata,offset+1))
assert(rlen)
if not deepcompare(res,msgpack_cases[i]) then
display("expected",msgpack_cases[i])
display("found",res)
assert(false,string.format("wrong value %d",i))
end
-- stream too.
streamtest(unp,msgpack_cases[i])
offset = offset + rlen
end
print("")
end
print("OK")
-- Raw tests
print("Raw tests ")
function rand_raw(len)
local t = {}
for i=1,len do t[i] = string.char(math.random(0,255)) end
return table.concat(t)
end
function raw_test(raw,overhead)
offset,res = mp.unpack(mp.pack(raw))
assert(offset,"decoding failed")
if not res == raw then
assert(false,string.format("wrong raw (len %d - %d)",#res,#raw))
end
assert(offset-#raw == overhead,string.format(
"wrong overhead %d for #raw %d (expected %d)",
offset-#raw,#raw,overhead
))
end
printf(".")
for n=0,31 do -- fixraw
raw_test(rand_raw(n),1)
end
-- raw16
printf("test raw16:")
for n=32,32+100 do
raw_test(rand_raw(n),3)
end
print("OK")
for n=65535-5,65535 do
printf(".")
raw_test(rand_raw(n),3)
end
print("OK")
-- raw32
printf("test raw32:")
for n=65536,65536+5 do
printf(".")
raw_test(rand_raw(n),5)
end
print("OK")
-- Integer tests
printf("Integer tests ")
function nb_test(n,sz)
offset,res = mp.unpack(mp.pack(n))
assert(offset,"decoding failed")
if not res == n then
assert(false,string.format("wrong value %d, expected %d",res,n))
end
assert(offset == sz,string.format(
"wrong size %d for number %d (expected %d)",
offset,n,sz
))
end
printf(".")
for n=0,127 do -- positive fixnum
nb_test(n,1)
end
printf(".")
for n=128,255 do -- uint8
nb_test(n,2)
end
printf(".")
for n=256,65535 do -- uint16
nb_test(n,3)
end
-- uint32
printf(".")
for n=65536,65536+100 do
nb_test(n,5)
end
for n=4294967295-100,4294967295 do
nb_test(n,5)
end
-- no 64 bit!
printf(".")
for n=4294967296,4294967296+100 do -- uint64
nb_test(n,9)
end
printf(".")
for n=-1,-32,-1 do -- negative fixnum
nb_test(n,1)
end
printf(".")
for n=-33,-128,-1 do -- int8
nb_test(n,2)
end
printf(".")
for n=-129,-32768,-1 do -- int16
nb_test(n,3)
end
-- int32
printf(".")
for n=-32769,-32769-100,-1 do
nb_test(n,5)
end
for n=-2147483648+100,-2147483648,-1 do
nb_test(n,5)
end
print("OK")
printf(".")
for n=-2147483649,-2147483649-100,-1 do -- int64
nb_test(n,9)
end
print(" OK")
printf("Floating point tests ")
printf(".")
for i=1,100 do
local n = math.random()*200-100
nb_test(n,9)
end
print(" OK")
print("long array test (16bit-32bit)")
for i=65530,65600 do
if (i%10)==0 then printf(".") end
local ary = rand_raw(i)
local ofs,res = mp.unpack(mp.pack(ary))
assert(ofs,"decoding failed")
if not deepcompare(res,ary) then
assert(false,"long ary fail. len:"..i)
end
end
print("")
print("long map test")
for n=65532,65540 do
printf(".")
local t = {}
for i=1,n do
t[ "key" .. i ] = i
end
local ss = mp.pack(t)
local ofs,res = mp.unpack(ss)
assert(ofs,"decoding failed")
if not deepcompare(res,t) then
assert(false,"long map fail. len:"..n)
end
end
print("")
print("long str test")
for n=65532,65540 do
printf(".")
local s = ""
for i=1,n do
s = s .. "a"
end
local ss = mp.pack(s)
local ofs,res = mp.unpack(ss)
if not deepcompare(res,s) then
assert(false,"long str fail. len:"..n)
end
end
print("\nOK")
-- below: too slow and >4G mem.. cannot in i386 build
--for n=4294967295-100,4294967295 do
-- raw_test(rand_raw(n),5)
--end
--print(" OK")
print("test finished")
| apache-2.0 |
ys1045097987/Face-Experiments | train.lua | 1 | 7931 | --convery grey to color
--subtract mean before enter the network
require 'nn'
require 'image'
require 'torchx'
local ffi = require 'ffi'
require 'optim'
require 'sys'
require 'cudnn'
require 'cunn'
require 'paths'
local image = require 'image'
local trainer = {}
local casia = {}
--casia.root_folder = '/data/yann/Webface/CASIA-WebFace/'
casia.root_folder = '/data/yann/LFW/lfw/'
local mean = {127.5, 127.5, 127.5}
function trainer.initialize(network, criterion, options)
optim_state = {
learningRate = options.lr,
momentum = options.mom,
learningRateDecay = options.lrd,
weightDecay = options.wd,
dampening = 0.0,
nesterov = false,
}
trainer.tensor_type = torch.getdefaulttensortype()
print('default tensor_type ', trainer.tensor_type)
if not options.no_cuda then
trainer.tensor_type = 'torch.CudaTensor'
print('Targets Convert to : ' .. trainer.tensor_type)
print('Inputs should keep Float type before Copy module ...')
end
trainer.batch_size = options.bs
trainer.network = network
trainer.params, trainer.gradParams = trainer.network:getParameters()
print('Network has', trainer.params:numel(), 'parameters')
if criterion then
trainer.criterion = criterion
end
end
function center_crop(input, crop_size)
local w1 = math.ceil((input:size(3) - crop_size) / 2)
local h1 = math.ceil((input:size(2) - crop_size) / 2)
return image.crop(input, w1, h1, w1+crop_size, h1+crop_size)
end
function random_crop(input, size)
local w, h = input:size(3), input:size(2)
if w == size and h == size then return input end
local x1, y1 = torch.random(0, w-size), torch.random(0, h-size)
local output = image.crop(input, x1, y1, x1+size, y1+size)
assert(output:size(2) == size and output:size(3) == size)
return output
end
function grey_tocolor(input, size_samples)
local t = torch.Tensor(3, size_samples, size_samples)
t[1]:copy(input)
t[2]:copy(input)
t[3]:copy(input)
return t
end
function trainer.train(dataset, opt, epoch)
trainer.network:training()
if (epoch % opt.epoch_step == 0) then
optim_state.learningRate = optim_state.learningRate * opt.lrDecay
end
print(optim_state)
print('<trainer> on training set:')
local epoch_error = 0
local nbr_samples = dataset.data:size(1)
local centercrop_size = 224
local time = sys.clock()
-- generate random training batches
local indices = torch.randperm(nbr_samples):long():split(trainer.batch_size)
indices[#indices] = nil -- remove last partial batch
-- preallocate input and target tensors
--local inputs_char = torch.CharTensor(trainer.batch_size, 16)
local inputs_char = torch.CharTensor(trainer.batch_size, 81)
local inputs = torch.zeros(trainer.batch_size, 3,
centercrop_size, centercrop_size, trainer.tensor_type) -- inputs should be Float type before Copy module if using real-time augmentation ...
local targets = torch.zeros(trainer.batch_size, 1,
trainer.tensor_type) --targets should be Cuda Tensor due to the Criterion module
local function feval()
return loss, trainer.gradParams
end
for t,ind in ipairs(indices) do
print(('%d/%d'):format(t, #indices))
inputs_char:copy(dataset.data:index(1,ind))
for i=1, inputs_char:size(1) do
local img_path = ffi.string(inputs_char[i]:data())
local img = image.load(casia.root_folder .. img_path)
img = image.scale(img, 384, 384, 'bicubic')
img = center_crop(img, 224) --modified random_crop to center_crop
img = img* 255
for i=1, 3 do
img[i]:add(-mean[i])
end
img = img / 128
inputs[i]:copy(img)
end
targets:copy(dataset.label:index(1,ind))
--local output = trainer.network:forward(inputs) --for st4, real-time can't use.
local output = trainer.network:forward(inputs:float())
targets = targets:float()
output = output:float()
local loss = trainer.criterion:float():forward(output,targets)
epoch_error = epoch_error + loss
trainer.network:zeroGradParameters() --zero gradParams per batch
dl_do = trainer.criterion:backward(output,targets)
trainer.network:backward(inputs,dl_do:cuda())
optim.sgd(feval,trainer.params,optim_state)
end
-- time taken
time = sys.clock() - time
time = time
print("<trainer> time to train a whole train_set = " .. (time / 3600) .. ' hours')
print("<trainer> mean error (train set) = " .. epoch_error/nbr_samples)
return epoch_error
end
function trainer.test(dataset, opt)
trainer.network:evaluate() --no batchnorm, no data augmentation, no dropout
if not trainer.network then
error('Trainer not initialized properly. Use trainer.initialize first.')
end
-- test over given dataset
print('')
print('<trainer> on testing Set:')
local time = sys.clock()
local nbr_samples = dataset.data:size(1)
local centercrop_size = 200
local epoch_error = 0
local correct = 0
local all = 0
-- generate indices and split them into batches
local indices = torch.linspace(1,nbr_samples,nbr_samples):long()
indices = indices:split(trainer.batch_size)
-- preallocate input and target tensors
--local inputs_char = torch.CharTensor(trainer.batch_size,16)
local inputs_char = torch.CharTensor(trainer.batch_size,81)
local inputs = torch.zeros(trainer.batch_size, 3,
224, 224,
trainer.tensor_type)
local targets = torch.zeros(trainer.batch_size, 1,
trainer.tensor_type)
for t,ind in ipairs(indices) do
print(('%d/%d'):format(t, #indices))
-- last batch may not be full
local local_batch_size = ind:size(1)
-- resize prealocated tensors (should only happen on last batch)
inputs:resize(local_batch_size, 3, 224, 224)
--inputs_char:resize(local_batch_size,16)
inputs_char:resize(local_batch_size,81)
inputs_char:copy(dataset.data:index(1,ind))
for i=1, inputs_char:size(1) do
local img_path = ffi.string(inputs_char[i]:data())
local img = image.load(casia.root_folder .. img_path)
img = center_crop(img, centercrop_size)
img = image.scale(img, 224, 224, 'bicubic')
img = img* 255
for i=1, 3 do
img[i]:add(-mean[i])
end
img = img / 128
inputs[i]:copy(img)
end
targets:resize(local_batch_size,1)
targets:copy(dataset.label:index(1,ind))
local scores = trainer.network:forward(inputs)
-- local features = trainer.network:forward(inputs):float()
-- for i=1, opt.num_classes do
-- local tmp = torch.find(targets, i)
-- if next(tmp) ~= nil then
-- centers[i] = centers[i]:add(features:index(1,torch.Tensor(tmp):long()):sum(1))
-- sum[i] = sum[i] + #tmp
-- end
-- end
scores = scores:float()
targets = targets:float()
epoch_error = epoch_error + trainer.criterion:float():forward(scores,
targets)
local _, preds = scores:max(2)
correct = correct + preds:float():eq(targets:float()):sum()
all = all + preds:size(1)
end
-- for i=1, centers:size(1) do
-- assert(sum[i]~=0)
-- centers[i] = centers[i] / sum[i]
-- end
-- torch.save('precomputed_centers.t7', centers)
time = sys.clock() - time
time = time
print("<trainer> time to test a whole test_dataset = " .. (time / 3600) .. ' hours')
print("<trainer> mean error (test set) = " .. epoch_error/nbr_samples)
local accuracy = correct / all
print('accuracy % : ', accuracy * 100)
return epoch_error, accuracy
end
return trainer
| apache-2.0 |
PolyCement/swallow-squad | engine/colliders.lua | 1 | 4651 | local Object = require "lib.classic"
local vector = require "lib.hump.vector"
-- polygonal colliders
-- they're components now btw
-- this is an edge
local Segment = Object:extend()
function Segment:new(a, b)
self.a = a
self.b = b
self.direction = b - a
self.normal = self.direction:perpendicular():normalized()
end
-- should probably remove this once im done debugging
function Segment:__tostring()
local a_string = tostring(self.a)
local b_string = tostring(self.b)
local dir_string = tostring(self.direction)
return "Segment(" .. a_string .. ", " .. b_string .. ", " .. dir_string .. ")"
end
-- THIS is the collider
local Collider = Object:extend()
-- assumes clockwise winding
function Collider:new(...)
-- store coordinates as vertices
local args = {...}
self.vertices = {}
for i = 1, #args, 2 do
table.insert(self.vertices, vector(args[i], args[i+1]))
end
-- create edges
self.edges = {}
for i = 1, #self.vertices do
table.insert(self.edges, Segment(self.vertices[i], self.vertices[1+i%(#self.vertices)]))
end
-- solidity
self.solid = true
-- callback function
self.onCollision = function() end
-- tag (so other colliders know what hit em)
self.tag = ""
-- parent, for when a collider's parents need to know about each other in order to react properly
-- (only useful for a handful of colliders, so it's optional)
self.parent = nil
end
function Collider:setCallback(func)
self.onCollision = func
end
function Collider:getTag()
return self.tag
end
function Collider:setTag(tag)
self.tag = tag
end
function Collider:getParent()
return self.parent
end
function Collider:setParent(parent)
self.parent = parent
end
-- draw the collider's bounding box
function Collider:drawBoundingBox()
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(255, 0, 0, 255)
-- shove all coordinates in a table
local vertices = {}
for _, v in pairs(self.vertices) do
table.insert(vertices, v.x)
table.insert(vertices, v.y)
end
-- we need at least 3 points to draw a polygon
if #vertices < 6 then
love.graphics.line(unpack(vertices))
else
love.graphics.polygon("line", unpack(vertices))
end
love.graphics.setColor(r, g, b, a)
end
-- move by the requested amount, no collision handling
local function movement_helper(self, delta)
for i, v in pairs(self.vertices) do
self.vertices[i] = v + delta
end
-- technically we don't need to update these since the direction is the only
-- bit we actually use, and since we don't support rotation direction never changes
for i, v in pairs(self.edges) do
v.a = v.a + delta
v.b = v.b + delta
end
end
-- move by the requested amount, correct our position if we hit something
function Collider:move(delta)
movement_helper(self, delta)
local correction_delta = collisionHandler:checkCollision(self)
movement_helper(self, correction_delta)
end
function Collider:isSolid()
return self.solid
end
-- get one vertex
function Collider:getVertex(idx)
return self.vertices[idx]
end
-- get all the vertices
function Collider:getVertices()
return self.vertices
end
-- calculate the centre of the polygon
function Collider:getCenter()
local num_vertices = #self.vertices
local total = self.vertices[1]
for i = 2, num_vertices do
total = total + self.vertices[i]
end
return total/num_vertices
end
function Collider:__tostring()
return "Collider"
end
-- a one-way platform
local Platform = Collider:extend()
-- a on the left, b on the right
function Platform:new(a_x, a_y, b_x, b_y)
Platform.super.new(self, a_x, a_y, b_x, b_y)
end
-- platforms are only solid if the given collider was above them on the previous cycle
function Platform:isSolid(collider)
local obj = collider:getParent()
-- if the collider was above the bounding box of the platform, stay solid (allows hanging on edges)
if obj.prevBottomPos.y <= math.min(self.vertices[1].y, self.vertices[2].y) then
return true
end
-- if the determinant of ba and "ca" is negative, we're above the platform
local ca = obj.prevBottomPos - self.vertices[1]
local ba = self.edges[1].direction
local determinant = ba.x * ca.y - ba.y * ca.x
return determinant < 0
end
-- a non-solid collider
local Trigger = Collider:extend()
function Trigger:new(...)
Trigger.super.new(self, ...)
self.solid = false
end
return {
Collider = Collider,
Platform = Platform,
Trigger = Trigger
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.